前言
当数据不是很复杂的时候,感觉用很多库就有点麻烦了。
正好学校前几天的水课有讲到回归直线的计算原理,就打算发个文章记录一下。
正文
原理
回归直线是与数据误差最小的直线,可以表示为 y = a x + b y=ax+b y=ax+b。
其中,斜率 a = σ x y / σ x 2 a=\sigma_{xy}/\sigma_x^2 a=σxy/σx2,截距 b = y ‾ − a x ‾ b=\overline{y}-a\overline{x} b=y−ax。
x ‾ \overline{x} x和 y ‾ \overline{y} y分别表示x与y的平均值。
σ x y \sigma_{xy} σxy为x与y的协方差,计算公式为 1 N ∑ i = 1 N ( x i − x ‾ ) ( y i − y ‾ ) {1\over{N}}{\sum\limits_{i=1}^N(x_i-\overline{x})(y_i-\overline{y})} N1i=1∑N(xi−x)(yi−y)
σ x 2 \sigma_x^2 σx2为x的方差,计算公式为 1 N ∑ i = 1 N ( x i − x ‾ ) 2 {1\over{N}}{\sum\limits_{i=1}^N(x_i-\overline{x})^2} N1i=1∑N(xi−x)2
代码
知道原理以后代码实现就很简单了。注意下面的Prepare data是要自己改的。
import matplotlib.pyplot as plt
# Prepare data
x_data = Prepare(x_data)
y_data = Prepare(y_data)
# Calculate the mean of the data
mean_x = sum(x_data) / len(x_data)
mean_y = sum(y_data) / len(y_data)
# Calculate the covariance of x and y
covariance = 0
for x, y in zip(x_data, y_data):
covariance += (x - mean_x) * (y - mean_y)
covariance = covariance / len(x_data)
# Calculate the variance of x
variance_x = 0
for x in idx:
variance_x += (x - mean_x) ** 2
variance_x = variance_x / len(x_data)
# Calculate the slope and the intercept
slope = covariance / variance_x
intercept = mean_y - slope * mean_x
# Build the data of the line
z_data = list(map(lambda z: slope*z + intercept, x_data))
# Show
plt.plot(x_data, y_data)
plt.plot(x_data, z_data)