【问题标题】:Gradient descent algorithm giving incorrect answer in matlab梯度下降算法在matlab中给出不正确的答案
【发布时间】:2018-01-10 04:52:55
【问题描述】:

我正在学习机器学习课程并尝试在 matlab 中实现梯度下降算法。函数 computeCost 工作正常,因为我已经单独测试过了。我用它来查看每次迭代的成本,它似乎根本没有减少。它只是随机波动。 alpha 的值为 0.01,所以我知道学习率太大不是问题。我得到的 theta 答案与预期的输出相差甚远。我哪里错了?提前致谢!

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

编辑:这里也是 computeCost

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

【问题讨论】:

  • 查看 computeCost 会很有用 - 你的梯度完全不依赖于 X(k,1) 是否正确?
  • X 是一个矩阵,第一列中有一个,作为 theta1 的系数。我不认为渐变取决于它。我也添加了 computeCost。

标签: algorithm matlab machine-learning


【解决方案1】:

尝试改变:

temp1=0;
temp2=0;
for iter = 1:num_iters

到

for iter = 1:num_iters
  temp1=0;
  temp2=0;

每次迭代都需要重新计算梯度(或者您正在有效地构建动量项)。

【讨论】:

    猜你喜欢
    • 2017-02-18
    • 2019-03-22
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    相关资源
    最近更新 更多