[英]Optional parameter to theano function
我在theano中有一个函数f
,它带有两个参数,其中一个是可选的。 当我使用可选参数None
调用函数时, f
内的检查失败。 此脚本重现该错误:
import theano
import theano.tensor as T
import numpy as np
# function setup
def f(b, c=None):
if c is not None:
return (c*b).mean()
else:
return b.mean()
y = T.vector()
c = T.vector()
ins = [y,c]
tfn = theano.function(ins, f(y,c), allow_input_downcast=True, mode=None)
# eval function
first = np.array([1])
second = np.array([2])
second = None
res = tfn(first, second)
print res
出现错误消息失败
ValueError: expected an ndarray, not None
Apply node that caused the error: Elemwise{mul,no_inplace}(<TensorType(float64, vector)>, <TensorType(float64, vector)>)
Inputs types: [TensorType(float64, vector), TensorType(float64, vector)]
Inputs shapes: ['No shapes', (1,)]
Inputs strides: ['No strides', (8,)]
Inputs values: [None, array([ 1.])]
Backtrace when the node is created:
File "test_theano.py", line 14, in f
return (c*b).mean()
c
没有输入形状也没有输入步幅是有意义的。 但是我想知道为什么f
内部的if
校验似乎不起作用。
如何在f
内部进行检查,以便正确处理可选参数c
?
我将尝试更完整的答复。
1)条件“ c不是None”在构建图形时仅运行一次。 由于c是符号变量,因此将始终执行else路径。 如果要在运行时执行条件,请参阅此文档页面:
http://deeplearning.net/software/theano/tutorial/conditions.html
2)Theano有一个特殊的“无”类型。 但是我不建议您使用它。 大多数时候它没有用,也没有记录在案。 因此,在您更加熟悉Theano之前,请不要使用它。
3)告诉使用2个功能的其他答案将起作用。
4)在那种简单的情况下,您可以传递一个只有一个而不是没有一个而正确大小的向量。 那也可以,但是比较慢。
Theano不支持可选参数。 通过将函数的输入参数指定为ins=[y,c]
您将告诉Theano函数具有两个一维(矢量)参数。 就Theano而言,两者都是强制性的。 当您尝试为c
传递None
时,Theano将检查您传递的值的类型是否与编译函数时声明的类型(即两个向量)相符,但显然None
不是向量,因此会引发此异常。
一种解决方案是编译两个Theano函数,一个仅接受一个参数,另一个接受两个参数。 您甚至都可以使用现有的Python函数f
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.