Algorithm matlab中给出错误答案的梯度下降算法
我正在学习机器学习课程,并尝试在matlab中实现梯度下降算法。computeCost函数运行良好,因为我已经分别对其进行了测试。我用它来查看每次迭代的成本,它似乎一点也没有减少。它只是随机波动。alpha的值被设定为0.01,所以我知道这不是学习率太高的问题。我得到的θ的答案与预期的结果相差甚远。我哪里做错了?提前谢谢Algorithm matlab中给出错误答案的梯度下降算法,algorithm,matlab,machine-learning,Algorithm,Matlab,Machine Learning,我正在学习机器学习课程,并尝试在matlab中实现梯度下降算法。computeCost函数运行良好,因为我已经分别对其进行了测试。我用它来查看每次迭代的成本,它似乎一点也没有减少。它只是随机波动。alpha的值被设定为0.01,所以我知道这不是学习率太高的问题。我得到的θ的答案与预期的结果相差甚远。我哪里做错了?提前谢谢 function theta = gradientDescent(X, y, theta, alpha, num_iters) %GRADIENTDESCENT Perform
function theta = gradientDescent(X, y, theta, alpha, num_iters)
%GRADIENTDESCENT Performs gradient descent to learn theta
% Initialize some useful values
m = length(y); % number of training examples
temp1=0;
temp2=0;
for iter = 1:num_iters
for k = 1:m
temp1 = temp1 + (theta(1) + theta(2)*X(k, 2) - y(k));
temp2 = temp2 + ((theta(1) + theta(2)*X(k, 2) - y(k))*X(k, 2));
end
theta(1) = theta(1)-(1/m)*alpha*temp1;
theta(2) = theta(2)-(1/m)*alpha*temp2;
computeCost(X, y, theta)
end
end
编辑:这里还有计算成本
function J = computeCost(X, y, theta)
m = length(y); % number of training examples
J = 0;
temp = 0;
for index = 1:m
temp = temp + (theta(1) + theta(2)*X(index, 2)-y(index))^2;
end
J = temp/(2*m);
end
尝试更改:
temp1=0;
temp2=0;
for iter = 1:num_iters
到
每次迭代都需要重新计算梯度(或者你实际上是在建立动量项)。查看computeCost会很有用-你的梯度完全不依赖于X(k,1)是否正确?X是一个矩阵,第一列中有1,作为θ1的系数。我不认为梯度取决于它。我还增加了计算成本。
for iter = 1:num_iters
temp1=0;
temp2=0;