Python 我应该如何在ano函数中分配numpy数组?
假设我有一个theano函数:Python 我应该如何在ano函数中分配numpy数组?,python,numpy,theano,Python,Numpy,Theano,假设我有一个theano函数: def my_fun(x, y): # Create output array for example sake z = np.asarray( shape=(x.shape[0], y.shape[1]), dtype=theano.config.floatX ) z = x + y # this is wrong, how should I convert this to a theano # tensor? r
def my_fun(x, y):
# Create output array for example sake
z = np.asarray(
shape=(x.shape[0], y.shape[1]),
dtype=theano.config.floatX
)
z = x + y
# this is wrong, how should I convert this to a theano
# tensor?
return z
x = theano.tensor.dmatrix("x")
y = theano.tensor.dmatrix("y")
f = function(
inputs=[x, y],
outputs=[my_fun]
)
a = numpy.asarray([[1,2],[3,4]])
b = numpy.asarray([[1,2],[3,4]])
c = my_fun(a,b)
很抱歉,我不理解您的具体问题,但可以对您提供的代码示例进行评论 首先,您上面的评论
return z
不正确。如果x
和y
是无变量,则z
在z=x+y
之后也将是无变量
其次,不需要使用numpy为返回变量预先分配内存。因此,您的my_fun
可以更改为
def my_fun(x, y):
z = x + y
return z
第三,Theano函数的输出必须是Theano变量,而不是Python函数。输出需要是输入的函数。因此,您的theano.function
调用需要更改为
f = function(
inputs=[x, y],
outputs=[my_fun(x, y)]
)
关于Theano,最重要的一点是要理解符号世界和可执行世界之间的差异,这一点在开始时可能有点难以理解。与此相关的是Python表达式和Theano表达式之间的区别
上面修改的my_fun
可以像符号函数一样使用,也可以像普通的可执行Python函数一样使用,但每个函数的行为都不同。如果传入普通Python输入,则加法操作立即发生,返回值是计算的结果。所以my_-fun(1,2)
返回3
。相反,如果传入符号变量,则加法操作不会立即发生。相反,该函数返回一个符号表达式,该表达式在编译和执行之后将返回添加两个输入的结果。因此,my_fun(theano.tensor.scalar(),theano.tensor.scalar())
的结果是一个Python对象,它表示符号化的theano计算图。当该结果作为输出传递给theano.function
时,它被编译成可执行的内容。当编译后的函数被执行,并且为输入提供了一些具体的值时,您实际上得到了您想要的结果