[英]Gradient Descent & linear regression - Code not converging
我正在嘗試從零開始解決玩具問題上的梯度下降算法。 我的代碼總是返回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)
顯然,這里沒有最低要求。 我哪里出問題了?
謝謝
在theta更新中,第二項應除以訓練集的大小。 有更多詳細信息: 使用python和numpy進行梯度下降
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.