2015-09-26 60 views
3

我在用python實現漸變下降的時候遇到了困難。Python中的漸變下降實現

爲梯度下降的公式爲:

for iter in range(1, num_iters): 
    hypo_function = np.sum(np.dot(np.dot(theta.T, X)-y, X[:,iter])) 

    theta_0 = theta[0] - alpha * (1.0/m) * hypo_function 
    theta_1 = theta[1] - alpha * (1.0/m) * hypo_function 

得到了一個錯誤:

---> hypo_function = np.sum(np.dot(np.dot(theta.T, X)-y, X[:,iter])) ValueError: shapes (1,97) and (2,) not aligned: 97 (dim 1) != 2 (dim 0)

PS:這裏我的X爲(2L,97L),Y是(97L)theta是( 2L)。

回答

1

np.dot(A,B)取的內積和b,如果a和b是向量(1-d陣列)如果a和b是2D陣列,np.dot(A,B )做矩陣乘法。

如果a的最後一個維度的大小與b的第二個維度的大小不匹配,它將拋出ValueError。他們必須匹配。

在你的情況下,你正試圖乘以一個由97數組中的東西乘以某個數組中的某個數組,這樣就會出現不匹配。所以你需要修正你的輸入數據,所以點積/矩陣乘法是可計算的。

+0

嗨派桑科,你能幫我糾正代碼嗎? – Vamsi

+0

好的。但在這裏,我的X是(2L,97L),y是(97L,)theta是(2L,).. – Vamsi

+0

那麼,例如X的轉置就是97 x 2,可以乘以theta(2x1)成功。你可以使用numpy.transpose來完成這個技巧。 – paisanco