首页 > 解决方案 > Octave 中的线性回归实现

问题描述

我最近尝试在 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-learningoctavelinear-regressiongradient-descent

解决方案


您不需要内部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

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


推荐阅读