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 

回答

2

已知二阶导数可能很难找到。

这个note page 6可能在某种意义上是有帮助的。

如果您发现全面牛顿的方法比较困难,您可以使用fminuncfmincg之类的其他功能。