我正在学习 机器学习,并参加 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](https://istack.dev59.com/H0Itw.webp)
theta
之后,你不应该更新h
吗? - Ander BiguricomputeCost
函数中更新h
,但没有将它作为输出参数,因此你的代码仍在使用先前h
的值。 - Sardar Usama