07.线性回归模型
import numpy as np import matplotlib.pyplot as plt # 实验数据 y = ax + b + ε x = np.arange(1, 11, dtype=float) y = 2 * x + 1 + np.random.normal(size=10) # 最小二乘法: # a = Σ(x - x_mean)(y - y_mean) / Σ(x - x_mean) ** 2 # b = y_mean - a * x_mean x_mean, y_mean = np.mean(x), np.mean(y) a = (x - x_mean).dot(y - y_mean) / (x - x_mean).dot(x - x_mean) b = y_mean - a * x_mean y_hat = a * x + b plt.scatter(x , y) plt.plot(x, y_hat, "r") plt.show()