牛顿梯度下降线性回归

4

我正在尝试在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
1个回答

2

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

这个笔记第6页在某种意义上可能会有所帮助。

如果您发现完整的牛顿法困难,您可以使用一些其他函数,比如fminuncfmincg


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接