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는 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
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
업데이트.
그걸 얻은 것은 + Dan 힌트였습니다. 나는 그의 대답을 받아 들일 것이지만 아직도 코드를 붙인 사람에게 붙이 셨습니다. :), 건배. 언뜻
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
? 명시 적으로 곱셈 기호를 넣어 주어야합니다. 예를 들어'(alpha) * (1/m) * (summation_i^m * (theta1 + theta2 * x (i) - y (i))) * x (i)'. 이게 말이 돼? –
그렇습니다 노트에 matlab 구현이 아니라는식이 있습니다. matlab 코드는 그 위에 있습니다. 여기에 공식을 쓰는 방법을 모르겠다. –
SO에 방정식을 작성하는 데 일반적으로 합의 된 방법이 있는지 확실하지 않습니다. 개인적으로, 방정식에 코드 강조 표시를 사용하지 않고 * 일부 사용자가 선호합니다.모두 나가고 싶다면 Google API를 사용할 수 있습니다. [here] (http://meta.stackexchange.com/questions/76902/how-can-i-write-math-formula-in-a)를 참조하십시오. -stack-overflow-question) –