线性回归代码

3

我正在学习 机器学习,并参加 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
< p> J_history 的值不断增加。 它给出了非常异常的值(大值),即比它应该的值高约1000倍。

< p> image


如果您能解释如何确定某些问题的出处,那么回答这样的问题会更容易。这意味着要么发布完整的错误信息(最好附带示例输入),要么发布输出并解释为什么与您的预期不同。您可以编辑帖子以添加这些内容。 - Dan
J_history的值不断增加,它给出了非常异常的值(大约比它应该的值高1000倍)。 - Zain Ahmed
你能添加一些样本数据吗?否则调试数值算法会非常困难。 - Ander Biguri
2
在更新 theta 之后,你不应该更新 h 吗? - Ander Biguri
2
你正在computeCost函数中更新h,但没有将它作为输出参数,因此你的代码仍在使用先前h的值。 - Sardar Usama
显示剩余2条评论
1个回答

0

您需要在循环中按照以下方式更新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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接