看來,下面的代碼找到正確的梯度下降:瞭解梯度下降多元線性迴歸Python實現
def gradientDescent(x, y, theta, alpha, m, numIterations):
xTrans = x.transpose()
for i in range(0, numIterations):
hypothesis = np.dot(x, theta)
loss = hypothesis - y
cost = np.sum(loss ** 2)/(2 * m)
print("Iteration %d | Cost: %f" % (i, cost))
# avg gradient per example
gradient = np.dot(xTrans, loss)/m
# update
theta = theta - alpha * gradient
return theta
現在假設我們有下面的示例數據:
對於第一行樣本數據,我們將有: x = [2104, 5, 1, 45]
,theta = [1,1,1,1]
,y = 460
。 然而,我們無處指定的線路:
hypothesis = np.dot(x, theta)
loss = hypothesis - y
考慮哪些樣本數據的行。那麼這個代碼是怎麼工作的呢?
這是否意味着x是一個m×n維矩陣(m =樣本數據的數量,n =特徵的數量)並且y和m * 1矩陣? –
有些謹慎:是的!是否可以調試你的代碼並仔細看看'x'和'y'?如果是這樣,請嘗試看看你自己。我認爲這是因爲如果'x'和'z'不是m * n或m * 1,那麼在這個函數中定義的梯度下降就沒有任何意義。 –