matlab - 牛顿梯度下降线性回归

标签 matlab machine-learning linear-regression newtons-method gradient-descent

我正在尝试在 MatLab 中实现一个函数,该函数使用牛顿法计算最佳线性回归。 但是,我陷入了一点。我不知道如何找到二阶导数。所以我无法实现它。这是我的代码。

感谢您的帮助。

function [costs,thetas] = mod_gd_linear_reg(x,y,numofit)

    theta=zeros(1,2);
    o=ones(size(x));
    x=[x,o]';
    for i=1:numofit

        err=(x.'*theta.')-y;
        delta=(x * err) / length(y); %% first derivative
        delta2; %% second derivative

        theta = theta - (delta./delta2).';

        costs(i)=cost(x,y,theta);
        thetas(i,:)=theta;


    end

end
function totCost = cost(x,y,theta)

 totCost=sum(((x.'*theta.')-y).*((x.'*theta.')-y)) / 2*length(y);

end

编辑:

我用一些纸和笔解决了这个问题。您所需要的只是一些微积分和矩阵运算。我找到了二阶导数,现在可以使用了。我正在为感兴趣的人分享我的工作代码。

function [costs,thetas] = mod_gd_linear_reg(x,y,numofit)

theta=zeros(1,2);
sos=0;
for i=1:size(x)
    sos=sos+(x(i)^2);
end
sumx=sum(x);
o=ones(size(x));
x=[x,o]';
for i=1:numofit

    err=(x.'*theta.')-y;
    delta=(x * err) / length(y); %% first derivative
   delta2=2*[sos,1;1,sumx];  %% second derivative

    theta = theta - (delta.'*length(y)/delta2);

    costs(i)=cost(x,y,theta);
    thetas(i,:)=theta;


end

end

function totCost = cost(x,y,theta)

 totCost=sum(((x.'*theta.')-y).*((x.'*theta.')-y)) / 2*length(y);

end

最佳答案

众所周知,二阶导数可能很难找到。

note page 6在某种意义上可能会有帮助。

如果你觉得完全牛顿法很困难,你可以使用一些其他函数,比如 fminuncfmincg

关于matlab - 牛顿梯度下降线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20591199/

相关文章:

matlab - 在关闭等待栏时中止当前脚本

matlab - 朴素贝叶斯分类器——标准化是否必要?

python - 无法读取远程 Ubuntu 服务器上 flask 中保存的机器学习模型

r - 在 R 中提取回归 P 值

matlab - 如何避免循环以减少这段代码的计算时间?

matlab - filter2函数中滤波器矩阵旋转的物理意义

matlab - 用值替换 simulink 模块中使用的变量的脚本

machine-learning - 模糊逻辑、人工智能、机器学习、深度学习

python - 为什么在线性回归中创建矩阵的逆时,numpy.linalg.pinv() 优于 numpy.linalg.inv()