[英]Why didn't theta change after iterations? I debugged and didn't get any error
import numpy as np
X = np.matrix([[1,6.1101],[1,5.5277]])
y = np.matrix([17.592,9.1302])
theta = np.matrix(np.array([0, 0]))
def gradientDescent(X, y, theta, alpha, iters):
count = theta.ravel().shape[1]
for i in range(iters):
predict = X * theta.T
for j in range(count):
theta[0, j] = theta[0, j] - alpha * np.sum(np.multiply(predict - y, X[:, j])) / len(X)
return theta
# def gradientDescent(X, y, theta, alpha, iters):
# temp_theta = np.matrix(np.zeros(theta.shape))
# count = theta.ravel().shape[1]
# for i in range(iters):
# predict = X * theta.T
# for j in range(count):
# temp_theta[0, j] = theta[0, j] - alpha * np.sum(np.multiply(predict - y, X[:, j])) / len(X)
# theta = temp_theta
# return theta
alpha = 0.01
iters = 1000
g= gradientDescent(X, y, theta, alpha, iters)
print(g)
右邊有注釋function。 為什么我必須添加一個臨時變量? 我的 function 中的 theta 值在任何迭代后都不會改變。
您需要為theta指定一個類型。
theta = np.matrix(np.array([0, 0]), dtype=float)
最后,你的腳本給你[[0.99642971 2.11975865]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.