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