import sys
x = [1,2,3,4,5,6]
y = [13,14,20,21,25,30]
epsilon = 1
alpha = 0.01
diff = [0,0]
max_itor = 20
error1 = 0
error0 = 0
cnt = 0
m = len(x)
theta0 = 0
theta1 = 0
while 1:
cnt = cnt + 1
diff = [0,0]
for i in range(m):
diff[0] += theta0 + theta1 * x[i] -y[i]
diff[1] += (theta0 + theta1 * x[i] -y[i]) * x[i]
theta0 = theta0 - alpha/m * diff[0]
theta1 = theta1 - alpha/m * diff[1]
error1 = 0
for i in range(m):
error1 += (theta0 + theta1 * x[i] - y[i]) ** 2
if abs(error1 - error0) < epsilon:
break
print ('theta0 :%f,theta1 :%f,error :%f' %(theta0,theta1,error1))
if cnt > 200000:
print ('cnt > 200000')
break
print ('theta0 :%f,theta1 :%f,error :%f' %(theta0,theta1,error1))
#简单的线性回归算法
#调试时可以修改alpha和cnt的值
打开App,阅读手记