Matlab 牛顿';s梯度下降线性回归
我试图在MatLab中实现一个函数,该函数使用牛顿法计算最佳线性回归。 然而,我陷入了一个问题。我不知道如何求二阶导数。所以我不能实施它。这是我的密码 谢谢你的帮助Matlab 牛顿';s梯度下降线性回归,matlab,machine-learning,linear-regression,newtons-method,gradient-descent,Matlab,Machine Learning,Linear Regression,Newtons Method,Gradient Descent,我试图在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;
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
众所周知,二阶导数可能很难找到 这在某种意义上可能是有帮助的 如果您发现完整的牛顿法很困难,您可以使用一些其他函数,如
fminunc
和fmincg