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
4

1 回答 1

2

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

注释第 6 页可能在某种意义上有所帮助。

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

于 2013-12-15T05:29:25.717 回答