2016-08-21 65 views
0

我是通過theano文檔/教程的學習,並在第一個例子是這樣的:Theano功能不工作簡單,4值陣列

>>> 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)無法正常工作,當他們是完全相同的表達式。我試圖用方括號替換/括起括號,結果是一樣的。

回答

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]) 
+0

謝謝,太多了。我完全不知道發生了什麼事。 – Rich

+0

但僅供將來參考,我如何讓Theano接受一個元組? – Rich

+0

很高興幫助。 僅支持[這些類型](http://deeplearning.net/software/theano/library/tensor/basic.html#all-fully-typed-constructors),如果它是單個元組,則不能直接使用元組將它轉換爲向量,可以使用矩陣的元組列表。 'import numpy as np' 'x _ =(2,3)' 'x = np.asarray(a,dtype ='int32')' – uyaseen