【问题标题】:My gradient descent is not giving the exact value我的梯度下降没有给出确切的值
【发布时间】:2020-01-14 08:40:09
【问题描述】:

我已经用 Octave 编写了梯度下降 算法,但它并没有给我确切的答案。答案从一位数到两位数不等。

这是我的代码:

function theta = gradientDescent(X, y, theta, alpha, num_iters)

m = length(y); % number of training examples
s = 0;
temp = theta;
for iter = 1:num_iters
  for j = 1:size(theta, 1)
    for i = 1:m
      h = theta' * X(i, :)';
      s = s + (h - y(i))*X(i, j);
    end
    s = s/m;
    temp(j) = temp(j) - alpha * s;
  end 
  theta = temp; 
end

end

为:

theta = gradientDescent([1 5; 1 2; 1 4; 1 5],[1 6 4 2]',[0 0]',0.01,1000);

我的梯度下降给出了这个:

 4.93708
-0.50549

但预计会给出这个:

 5.2148
-0.5733

【问题讨论】:

  • 为什么结果有误?如:您是如何确定“预期”输出的,为什么您确信这些是正确的?
  • 因为这些结果由机器学习课程提供者提供。
  • 那么你想从我们这里得到什么?您实现的是梯度下降(据说)。在我们得到确切的值之前,我们不会为您摆弄参数或更改算法。您必须准确找出这两种算法开始分歧的地方,并从那里调查哪里出了问题。如果可以的话,获取老师提供的代码并比较它们的差异
  • 我只是想知道我的算法是否正确,很抱歉给您带来不便。
  • 您已经确定这是不正确的,因为您的结果与老师的结果不同。问题是我们无法说明为什么它们不同,或者帮助您获得相同的结果,因为我们不知道老师是如何得到这些结果的。我们需要完整的书/课程/网络研讨会/无论你在哪里学习,看看老师做了什么。因此,我们根本无法帮助您。对不起。

标签: machine-learning neural-network octave gradient-descent


【解决方案1】:

小修复:

  1. 您的变量s 可能增量初始化不正确。
  2. 所以它是temp 变量可能是new theta
  3. 增量计算不正确

尝试以下更改。

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)

m = length(y); % number of training examples
J_history = zeros(num_iters, 1);
temp = theta;
for iter = 1:num_iters
    temp = zeros(length(theta), 1);
    for j = 1:size(theta)
        s = 0
        for i = 1:m
            s = s + (X(i, :)*theta - y(i)) * X(i, j);
        end
    end
    s = s/m;
    temp(j) = temp(j) - alpha * s;
end 
    theta = temp; 
    J_history(iter) = computeCost(X, y, theta);
end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 2018-01-10
    • 2019-11-11
    • 1970-01-01
    • 2016-09-25
    • 2012-08-17
    • 1970-01-01
    相关资源
    最近更新 更多