【问题标题】:Linear regression implementation in OctaveOctave 中的线性回归实现
【发布时间】:2019-06-03 20:58:11
【问题描述】:

我最近尝试在 octave 中实现线性回归,但无法通过在线评委。这是代码

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

m = length(y); % number of training examples
J_history = zeros(num_iters, 1);

for iter = 1:num_iters
    for i = 1:m
      temp1 = theta(1)-(alpha/m)*(X(i,:)*theta-y(i,:));
      temp2 = theta(2)-(alpha/m)*(X(i,:)*theta-y(i,:))*X(i,2);
      theta = [temp1;temp2];
    endfor

    J_history(iter) = computeCost(X, y, theta);

end

end

我知道矢量化实现,但只是想尝试迭代方法。任何帮助将不胜感激。

【问题讨论】:

    标签: machine-learning octave linear-regression gradient-descent


    【解决方案1】:

    您不需要内部 for 循环。相反,您可以使用sum 函数。

    在代码中:

    for iter = 1:num_iters
    
        j= 1:m;
    
        temp1 = sum((theta(1) + theta(2) .* X(j,2)) - y(j)); 
        temp2 = sum(((theta(1) + theta(2) .* X(j,2)) - y(j)) .* X(j,2));
    
        theta(1) = theta(1) - (alpha/m) * (temp1 );
        theta(2) = theta(2) - (alpha/m) * (temp2 );
    
        J_history(iter) = computeCost(X, y, theta);
    
    end
    

    实现矢量化解决方案也是一个很好的练习,然后比较它们以了解矢量化在实践中的效率如何。

    【讨论】:

    • 我知道可以这样做。您能否向我指出我的方法中的错误是什么?
    猜你喜欢
    • 2017-01-21
    • 2020-05-24
    • 2021-08-02
    • 2014-08-21
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多