2015-05-27 53 views
2

我是theano的新手。我想實現的簡單線性迴歸,但我的程序引發以下錯誤:theano功能的輸入參數不好

TypeError: ('Bad input argument to theano function with name "/home/akhan/Theano-Project/uog/theano_application/linear_regression.py:36" at index 0(0-based)', 'Expected an array-like object, but found a Variable: maybe you are trying to call a function on a (possibly shared) variable instead of a numeric array?')

這裏是我的代碼:

import theano 
from theano import tensor as T 
import numpy as np 
import matplotlib.pyplot as plt 

x_points=np.zeros((9,3),float) 
x_points[:,0] = 1 
x_points[:,1] = np.arange(1,10,1) 
x_points[:,2] = np.arange(1,10,1) 
y_points = np.arange(3,30,3) + 1 


X = T.vector('X') 
Y = T.scalar('Y') 

W = theano.shared(
      value=np.zeros(
       (3,1), 
       dtype=theano.config.floatX 
      ), 
      name='W', 
      borrow=True 
     ) 

out = T.dot(X, W) 
predict = theano.function(inputs=[X], outputs=out) 

y = predict(X) # y = T.dot(X, W) work fine 

cost = T.mean(T.sqr(y-Y)) 

gradient=T.grad(cost=cost,wrt=W) 

updates = [[W,W-gradient*0.01]] 

train = theano.function(inputs=[X,Y], outputs=cost, updates=updates, allow_input_downcast=True) 


for i in np.arange(x_points.shape[0]): 
    print "iteration" + str(i) 
    train(x_points[i,:],y_points[i]) 

sample = np.arange(x_points.shape[0])+1 
y_p = np.dot(x_points,W.get_value()) 
plt.plot(sample,y_p,'r-',sample,y_points,'ro') 
plt.show() 

這是什麼錯誤背後的原因呢? (沒有從錯誤信息中獲得)。提前致謝。

回答

4

Theano在定義計算圖形和使用這樣的圖形計算結果的函數之間有一個重要的區別。

當你定義

out = T.dot(X, W) 
predict = theano.function(inputs=[X], outputs=out) 

您先設置一個計算圖形爲outXW條款。請注意,X是純粹的符號變量,它沒有任何值,但out的定義告訴Theano,「給定值X,這是如何計算out」。

在另一方面,predicttheano.function這需要用於Xout計算圖和實際的數字值,以產生一個數字輸出。當你調用它時,你傳遞給theano.function的東西總是必須有一個實際的數值。因此,它根本沒有任何意義做

y = predict(X) 

因爲X是一個象徵性的變量,不具有實際價值。

你想這樣做的原因是,你可以使用y來進一步構建你的計算圖。但是不需要使用predictpredict的計算圖已經在前面定義的變量out中可用。所以,你可以簡單地刪除定義y線完全,然後定義你的成本

cost = T.mean(T.sqr(out - Y)) 

代碼的其餘部分將工作,然後修改。

+0

我明白了,並感謝您的解釋。 – Adnan