继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

9.蜜汁代码(2)

Coder_zheng
关注TA
已关注
手记 71
粉丝 23
获赞 45
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,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP