1.概念
参照这篇文章:
python实现线性回归之最小二乘法,最小二乘法详解
2.python代码实现
import matplotlib.pyplot as plt
import random
import numpy as np
# x-输入值,y-目标值
x=np.array([0.50,0.75,1.00,1.25,1.50,1.75,1.75,2.00,2.25,2.50,2.75,3.00,3.25,3.50,4.00,4.25,4.50,4.75,5.00,5.50])
y=np.array([10, 26, 23, 43, 20, 22, 43, 50, 62, 50, 55, 75, 62, 78, 87, 76, 64, 85, 90, 98])
# w-权重,b-偏移量
w = sum(np.multiply(y,(x-np.mean(x))))/(sum(x**2)-len(x)*(np.mean(x)**2))
b = sum(y-w*x)/len(x)
# 均方误差
meanCost = np.mean(np.multiply(x,(y-w*x-b)**2))
# 画图
plt.figure()
plt.suptitle("meancost is "+str(meanCost))
plt.scatter(x,y)
plt.plot(x,w*x+b,'r')
plt.show()
print("w = "+str(w)+", b = "+str(b))
print("meancost = "+str(meanCost))