2016-12-29 13 views
0

私は、玩具の問題で最初から勾配降下アルゴリズムを実装しようとしています。私のコードは常にNaN年代のベクトルを返します。勾配降下&線形回帰 - コードが収束しない

from sklearn.linear_model import LinearRegression 
import numpy as np 
import matplotlib.pyplot as plt 

np.random.seed(45) 
x = np.linspace(0, 1000, num=1000) 
y = 3*x + 2 + np.random.randn(len(x)) 

# sklearn output - This works (returns intercept = 1.6, coef = 3) 
lm = LinearRegression() 
lm.fit(x.reshape(-1, 1), y.reshape(-1, 1)) 
print("Intercept = {:.2f}, Coef = {:.2f}".format(lm.coef_[0][0], lm.intercept_[0])) 

# BGD output 
theta = np.array((0, 0)).reshape(-1, 1) 
X = np.hstack([np.ones_like(x.reshape(-1, 1)), x.reshape(-1, 1)]) # [1, x] 
Y = y.reshape(-1, 1) # Column vector 
alpha = 0.05 
for i in range(100): 
    # Update: theta <- theta - alpha * [X.T][X][theta] - [X.T][Y] 
    h = np.dot(X, theta) # Hypothesis 
    loss = h - Y 
    theta = theta - alpha*np.dot(X.T, loss) 
theta 

sklearn一部が正常に動作するので、私は、forループで何か間違ったことしなければなりません。私は様々な異なるalphaの値を試しましたが、それらのどれも収束しません。

問題はthetaがループ全体で大きくなり続けていて、最終的にはPythonが格納するには大きすぎます。

はここで、コスト関数の等高線図です:

J = np.dot((np.dot(X, theta) - y).T, (np.dot(X, theta) - y)) 
plt.contour(J) 

enter image description here

明らかに最低がここにありません。どこが間違っていたのですか?

おかげシータ更新で

答えて