一个简单的线性回归程序
#简单线性回归:只有一个自变量 y=k*x+b 预测使 (y-y*)^2 最小
1 import numpy as np 2 3 def fitSLR(x, y): 4 num = len(x) 5 dinominator = 0 # 分母 6 numerator = 0 # 分子 7 for i in range(0, num): 8 numerator += (x[i] - np.mean(x)) * (y[i] - np.mean(y)) 9 dinominator += (x[i] - np.mean(x)) ** 2 10 b1 = numerator / float(dinominator) 11 b0 = np.mean(y) - b1 * np.mean(x) 12 return b1, b0 13 14 def test(x, b1, b0): 15 y = b0 + b1 * x 16 print(y) 17 18 x = [1, 3, 2, 1, 3] 19 y = [14, 24, 18, 17, 27] 20 b1, b0 = fitSLR(x, y) 21 x_input = float(input("请输入要测试的数据:")) 22 test(x_input, b1, b0)