我在Matlab中學習了這個課程,並且我已經完成了梯度下降實現,但它給出了不正確的結果。在Matlab中梯度下降的結果不正確
代碼:
for iter = 1:num_iters
sumTheta1 = 0;
sumTheta2 = 0;
for s = 1:m
sumTheta1 = theta(1) + theta(2) .* X(s,2) - y(s);
sumTheta2 = theta(1) + theta(2) .* X(s,2) - y(s) .* X(s,2);
end
theta(1) = theta(1) - alpha .* (1/m) .* sumTheta1;
theta(2) = theta(2) - alpha .* (1/m) .* sumTheta2;
J_history(iter) = computeCost(X, y, theta);
end
這是重要的組成部分。我認爲公式的實現是正確的,即使它沒有被優化。公式是:
theta1 = theta1 - (alpha)(1/m)(summation_i^m(theta1 + theta2*x(i)-y(i)))
theta2 = theta2 - (alpha)(1/m)(summation_i^m(theta1 + theta2*x(i)-y(i)))(x(i))
那麼問題出在哪裏呢?
編輯:CODE更新
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
for s = 1:m
sumTheta1 = ((theta(1) .* X(s,1)) + (theta(2) .* X(s,2))) - (y(s));
sumTheta2 = ((theta(1) .* X(s,1)) + (theta(2) .* X(s,2))) - (y(s)) .* X(s,2);
end
temp1 = theta(1) - alpha .* (1/m) .* sumTheta1;
temp2 = theta(2) - alpha .* (1/m) .* sumTheta2;
theta(1) = temp1;
theta(2) = temp2;
J_history(iter) = computeCost(X, y, theta);
end
end
EDIT(2):固定它,工作碼。
明白了,這是+丹的暗示,做到了這一點,我會接受他的答案,仍然把代碼放在這裏給任何卡住:),歡呼聲。
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
sumTheta1 = 0;
sumTheta2 = 0;
for s = 1:m
sumTheta1 = sumTheta1 + ((theta(1) .* X(s,1)) + (theta(2) .* X(s,2))) - (y(s));
sumTheta2 = sumTheta2 + (((theta(1) .* X(s,1)) + (theta(2) .* X(s,2))) - (y(s))) .* X(s,2);
end
temp1 = theta(1) - alpha .* (1/m) .* sumTheta1;
temp2 = theta(2) - alpha .* (1/m) .* sumTheta2;
theta(1) = temp1;
theta(2) = temp2;
% Save the cost J in every iteration
J_history(iter) = computeCost(X, y, theta);
end
end
你知道Matlab的不理解語法'(阿爾法)(1/M)'對不對?你需要明確地輸入一個乘號,例如'(α*(1/m)*(summation_i^m *(theta1 + theta2 * x(i)-y(i)))* x(i)'。這有意義嗎? –
是的,這是在筆記中說的公式,而不是matlab的實現,matlab代碼在上面。因爲我不知道如何在這裏寫公式。 –
不確定在SO上是否有公認的寫方程。就個人而言,我寧願*不*使用方程式上的代碼高亮顯示,但有些用戶會這樣做。如果您想全力以赴,可以使用Google API - 請參閱[這裏](http://meta.stackexchange.com/questions/76902/how-can-i-write-math-formula-in-a -stack-overflow-question) –