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之類的其他功能。