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-(tmpmartrixx)’.*(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,結果矩陣列表[i1]
%theta,爲參數列表[j*1]
function J = costFunctionJ2(X,y,theta)
m=size(X,1);
predictions=theta’X’;
sqrtmp = predictions - y’;
sqrErrors=sqrtmp.^2;
J=1/(2m)*sum(sqrErrors);
end;