1 print('=====您好!这里是简单线性回归方程求解模型=====')
2 num = int(input('请输入您需要操作的样本对数'))
3 # 接收自变量的List
4 xList = []
5 # 接收因变量的List
6 yList = []
7
8 for i in range(num):
9 x = int(input('自变量:'))
10 xList.append(x)
11 y = int(input('因变量:'))
12 yList.append(y)
13 print()
14 # X表示自变量的均值
15 # Y表示因变量的均值
16 X = sum(xList)/len(xList)
17 Y = sum(yList)/len(yList)
18
19 totalX = 0
20 totalX_Y = 0
21 SST = 0 # 总的平方和
22 SSE = 0 # 误差平方和
23
24 for i in range(num):
25 totalX_Y += (xList[i]-X)*(yList[i]-Y)
26 totalX += (xList[i]-X)**2
27 SST += (yList[i]-Y)**2
28
29 b1 = totalX_Y/totalX
30 b0 = Y-b1*X
31
32 for i in range(num):
33 # 求因变量的预测值
34 yi = b0 + b1*xList[i]
35 SSE += (yList[i]-yi)**2
36
37 r2 = 1 - SSE/SST
38
39 print('估计的回归方程:y={0}x+{1}'.format(b1,b0))
40 print('判定系数:{0}'.format(r2))
作者李安国