【线性回归】最简单的线性回归函数在Octave中及Python中的实现(一)

线性回归
最简单的线性回归函数在Octave中的实现
数据集为
x,y
[1,-890
2,-1411
2,-1560
3,-2220
3,-2091
4,-2878
5,-3537
6,-3268
6,-3920
6,-4163
8,-5471
10,-5157]
命题:
假设线性函数为y=theta0+theta1*x;

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

function [TheTa,bResult] = RepeatGetMini(rap,minvalues,maxtimes,x,y,theta)
curtimes=0;
m=size(theta)(1);
while true,
curtimes=curtimes+1
J1=costFunctionJ2(x,y,theta);
tmpmartrix=theta’*x’-y’;
%计算两个theta的值,由于计算导数的函数不一样,这里无法写成For循环去计算导数,这个问题留着后续在多元函数中进行考虑。
theta(1,1)=theta(1,1)-(rap/m)*sum(tmpmartrix);
theta(2,1)=theta(2,1)-(rap/m)sum(tmpmartrixx(:,2));
J2=costFunctionJ2(x,y,theta);
steperr=J2-J1
if abs(steperr)<=minvalues,
TheTa=theta;
bResult=true;
break;
elseif curtimes>= maxtimes,
TheTa=theta;
bResult=false;
break;
end;
end;
end;

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;

计算(使用吴恩达教程中的数据)
%CD到上面的文件保存到的位置
cd C:\Octave\OctaveTest;
x=[1,1;1,2;1,2;1,3;1,3;1,4;1,5;1,6;1,6];
y=[-890;-1411;-1560;-2220;-2091;-2878;-3537;-3268;-3920];
theta=[-500;-100];

%设置步长为:0.001,两次方差的误差为0.1表示已经收敛,最大训练次数为1000
[thResult,bResult]=RepeatGetMini(0.001,0.1,1000,x,y,theta)

注:
1、theta的矩阵可以随意设置,例如[0;0],对结果不会有太多的影响,也许可能就是多几次或者少几次回归而已;
2、对theta0,theta1求导数,是theta、不是x,之前看到x就比theta要亲切,算错过几次;——求导数,一定要尝试自己去求解
3、数据集总共是12条,上面的案例拿了9个数据集来进行拟合,还有3个数据集进行验证,但是验证结果并不太好,偏差仍比较大,所以该数据集的模型还是需要优化的;
4、可以尝试去调整步长rap,去观察每两次计算的方差的差值,这能验证吴恩达教授中的很多理论。

最后,将以上Octave代码翻译成Python代码,如下所示:
#coding=utf-8

import numpy as np
‘’’
计算平方差SUM(THETAX-Y)/2m
X,条件的矩阵,包括x0
y,结果的矩阵,包括x0
theta,参数矩阵
‘’’
def costFunctionJ2(X,y,theta):
m=np.size(X,0)
predictions=theta.T
X.T
sqrtmp=predictions-y.T
sqrErrors=np.power(sqrtmp,2)
return 1/(2*m)*np.sum(sqrErrors)
‘’’
%rap表示回归计算的步长
%minvalues表示回归计算的最小偏差,如果小于该值则表示拟合成功,返回TheTa
%maxtimes表示最大拟合次数,如果达到该次数,即使没有拟合成功,也返回最后一次的TheTa值
%x表示x的矩阵
%y表示结果集
%theta表示参数集[TheTa,bResult] =
‘’’

def RepeatGetMini(rap,minvalues,maxtimes,x,y,theta):
curTimes=0
m=np.size(theta,0)
while True:
curTimes+=1
J1=costFunctionJ2(x,y,theta)
tmpMartrix=theta.T*x.T-y.T
theta[0, 0] = theta[0, 0] - (rap / m) * np.sum(tmpMartrix);
theta[1, 0] = theta[1, 0] - (rap / m) * np.sum(tmpMartrix * x[:,1]);
J2=costFunctionJ2(x,y,theta)
steperr = J2 - J1
print(“第%d次计算,最近两次的偏差为:%f” % (curTimes,steperr))
if abs(steperr)<=minvalues:
return theta,True
elif curTimes>=maxtimes:
return theta,False

x=np.matrix([[1,1],[1,2],[1,2],[1,3],[1,3],[1,4],[1,5],[1,6],[1,6]])
y=np.matrix([-890,-1411,-1560,-2220,-2091,-2878,-3537,-3268,-3920]).T
theta=np.zeros([2,1])
theta,bResult=RepeatGetMini(0.001,0.1,10000,x,y,theta)
print(theta,bResult)

猜你喜欢

转载自blog.csdn.net/wx0628/article/details/86290129