【发布时间】:2017-08-10 17:32:56
【问题描述】:
def computeCost(X, y, theta):
inner = np.power(((X * theta.T) - y), 2)
return np.sum(inner) / (2 * len(X))
def gradientDescent(X, y, theta, alpha, iters):
temp = np.matrix(np.zeros(theta.shape))
params = int(theta.ravel().shape[1]) #flattens
cost = np.zeros(iters)
for i in range(iters):
err = (X * theta.T) - y
for j in range(params):
term = np.multiply(err, X[:,j])
temp[0, j] = theta[0, j] - ((alpha / len(X)) * np.sum(term))
theta = temp
cost[i] = computeCost(X, y, theta)
return theta, cost
这是我在教程中找到的线性回归成本函数和梯度下降的代码,但我不太确定它是如何工作的。
首先我了解computeCost 代码的工作原理,因为它只是 (1/2M),其中 M 是数据数。
对于gradientDescent 代码,我只是不明白它一般是如何工作的。我知道更新 theta 的公式类似于
theta = theta - (learningRate) * derivative of J(cost function)。但我不确定alpha / len(X)) * np.sum(term) 这来自于在线更新temp[0,j]。
请帮我理解!
【问题讨论】: