我正在完成theano文档/教程,第一个例子是:
>>> import numpy
>>> import theano.tensor as T
>>> from theano import function
>>> x = T.dscalar('x')
>>> y = T.dscalar('y')
>>> z = x + y
>>> f = function([x, y], z)
这看起来很简单,所以我编写了自己的程序,扩展了它:
import numpy as np
import theano.tensor as T
from theano import function
x = T.dscalar('x')
y = T.dscalar('y')
z = x + y
f = function([x, y], z)
print f(2, 3)
print np.allclose(f(16.3, 12.1), 28.4)
print ""
r = (2, 3), (2, 2), (2, 1), (2, 0)
for i in r:
print i
print f(i)
由于某种原因,它不会迭代:
5.0
True
(2, 3)
Traceback (most recent call last):
File "TheanoBase2.py", line 20, in <module>
print f(i)
File "/usr/local/lib/python2.7/dist-packages/theano/compile/function_module.py", line 786, in __call__
allow_downcast=s.allow_downcast)
File "/usr/local/lib/python2.7/dist-packages/theano/tensor/type.py", line 177, in filter
data.shape))
TypeError: ('Bad input argument to theano function with name "TheanoBase2.py:9" at index 0(0-based)', 'Wrong number of dimensions: expected 0, got 1 with shape (2,).')
为什么print f(2, 3)
有效且print f(i)
不起作用,而它们是完全相同的表达式。我尝试用方括号替换/括起括号,结果是一样的。
答案 0 :(得分:1)
function f
将两个标量作为输入并返回它们的总和,r
的每个元素,即(x,y)是tuple而不是标量。这应该有效:
import numpy as np
import theano.tensor as T
from theano import function
x = T.dscalar('x')
y = T.dscalar('y')
z = x + y
f = function([x, y], z)
print f(2, 3)
print np.allclose(f(16.3, 12.1), 28.4)
print ""
r = (2, 3), (2, 2), (2, 1), (2, 0)
for i in r:
print i
print f(i[0], i[1])