文章目录
代码实操
简单线性回归公式推导
普通实现
import numpy as np
import matplotlib.pyplot as plt
#描点
x = np.array([1., 2., 3., 4., 5.])
y = np.array([1., 3., 2., 3., 5.])
plt.scatter(x, y)
plt.axis([0, 6, 0, 6])
plt.show()
#利用公式计算a,b,找出拟合直线
a = (np.mean(x*y) - np.mean(x)*np.mean(y))/(np.mean(x**2) - np.mean(x)**2)
print(a)
b = np.mean(y)-a*np.mean(x)
print(b)
plt.scatter(x,y)
plt.plot(x, a*x+b, color="r")
plt.axis([0,6,0,6])
plt.show()
#预测新数据
x_predict = 6
y_predict = a * x_predict