线性回归码

时间:2018-08-23 12:23:22

标签: matlab linear-regression gradient-descent

我正在学习机器学习上的 Andrew Ng类,并实现了线性回归算法。

我的代码有什么问题?

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y); 
J_history = zeros(num_iters, 1);
h = (X*theta)
for iter = 1:num_iters
    theta(1,1) = theta(1,1)-(alpha/m)*sum((h-y).*X(:,1));
    theta(2,1) = theta(2,1)-(alpha/m)*sum((h-y).*X(:,2));  
    J_history(iter) = computeCost(X, y, theta);
end
end

成本函数表示为:

function J = computeCost(X, y, theta)
m = length(y); 
h = (X*theta)
J = (1/(2*m))*sum((h-y).^2)
end

J_history的值一直在增加。它给出了非常异常的值(较大的值),即比应有的值大1000倍。

image

1 个答案:

答案 0 :(得分:0)

您需要在如下所示的for循环中更新htheta

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
    h = ((X*theta)-y)'*X;
    theta = theta - alpha*(1/m)*h';
    J_history(iter) = computeCost(X, y, theta);
end
end