【线性回归】多元线性回归函数在Octave中的实现(二)

1、在《【线性回归】最简单的线性回归函数在Octave中的实现(一)》的基础上进行了扩展,主要是标识出来的那段代码;
2、将训练结果Thsl,【i(训练集的条数),2(第一列训练的次数,第二列是两次训练的方差的误差)】,在训练完成之后,将Thsl的结果打印出来,就可以明显看到整体拟合的过程以及如何去调整rap(步长)

代码记录,以备后查

%rap表示回归计算的步长
%minvalues表示回归计算的最小偏差,如果小于该值则表示拟合成功,返回TheTa
%maxtimes表示最大拟合次数,如果达到该次数,即使没有拟合成功,也返回最后一次的TheTa值
%x表示x的矩阵
%y表示结果集
%theta表示参数集

function [TheTa,bResult,Thsl] = RepeatGetMini(rap,minvalues,maxtimes,x,y,theta)
curtimes=0;
m=size(theta)(1);
while true,
curtimes=curtimes+1;
J1=costFunctionJ2(x,y,theta);

%theta1=theta1-(rap/m)*(后面i从0到记录集求和)(theta1*x(i)-y(i))*x(i)
%...到j,下面的表达达就是theta=theta-(tmpmartrix*x)'.*(rap/m)就上面所说的矩阵

tmpmartrix=theta’x’-y’;
theta=theta-(tmpmartrix
x)’.*(rap/m);

J2=costFunctionJ2(x,y,theta);
steperr=J2-J1;
Thsl(curtimes,:)=[curtimes,steperr];

if abs(steperr)<=minvalues,
  TheTa=theta;
  bResult=true;
  break;
elseif curtimes>= maxtimes,
  TheTa=theta;
  bResult=false;
  break;
end;

end;
end;

%计算theta1+theta2x1+theta3x2,与y的方差
%X,特征项的矩阵列表[ij],i是记录集的条数,j代表参j-1数的个数(其中x0的列恒为1),x1,x2…xj
%y,结果矩阵列表[i
1]
%theta,为参数列表[j*1]
function J = costFunctionJ2(X,y,theta)
m=size(X,1);
predictions=theta’X’;
sqrtmp = predictions - y’;
sqrErrors=sqrtmp.^2;
J=1/(2
m)*sum(sqrErrors);
end;

猜你喜欢

转载自blog.csdn.net/wx0628/article/details/86362237
今日推荐