2016-12-15 4 views
2

정상적인 방정식을 시도했는데 결과가 정확했습니다. 그러나 그래디언트 강하를 사용하면 그림이 잘못 나온 것으로 나타났습니다. 나는 온라인 자원을 언급했지만, 무엇이 잘못되었는지를 찾지 못했습니다. 나는 다음 코드에서 특별한 것이 없다고 생각한다.선형 회귀 코드에 어떤 문제가 있는지 알 수 없습니다.

clear; 
clc; 
m = 100; % generate 100 points 
noise = randn(m,1); % 100 noise of normal distribution 
x = rand(m, 1) * 10; % generate 100 x's ranging from 0 to 10 
y = 10 + 2 * x + noise; 
plot (x, y, '.'); 
hold on; 


X = [ones(m, 1) x]; 
theta = [0; 0]; 
plot (x, X * theta, 'y'); 
hold on; 

% Method 1 gradient descent 
alpha = 0.02; % alpha too big will cause going far away from the result 
num_iters = 5; 
[theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters) 

% Method 2 normal equation 
% theta = (pinv(X' * X)) * X' * y 

plot (x, X * theta, 'r'); 



function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters) 
    m = length(y); 
    J_history = zeros(num_iters, 1); 
    for iter = 1:num_iters, 
     theta = theta - alpha * (1/m) * (X' * (X * theta - y)); 

     % plot (X(:, 2), X * theta, 'g'); 
     % hold on; 

     J_history(iter) = costFunction(X, y, theta); 
    end 
end 

function J = costFunction(X, y, theta) 
    m = length(y); 
    predictions = X * theta; % prediction on all m examples 
    sqrErrors = (predictions - y).^2; % Squared errors 
    J = 1/(2*m) * sum(sqrErrors); 
end 
+0

코드가 깨끗해 보입니다. github에서 그라디언트 디센트의 coursera 구현 학습 기계를 확인하십시오. 이 문제를 해결하는 데 도움을 줄 수 있습니다. – 16per9

답변

1

코드가 정확합니다. 문제는 반복 횟수가 적습니다. num_iters = 5000을 사용할 수 있습니다. 세타가 올바른 값 ([10; 2])으로 수렴한다는 것을 알 수 있습니다.