对简单数据进行简单的线性回归

前言

当数据不是很复杂的时候,感觉用很多库就有点麻烦了。

正好学校前几天的水课有讲到回归直线的计算原理,就打算发个文章记录一下。

正文

原理

回归直线是与数据误差最小的直线,可以表示为 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=yax

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=1N(xix)(yiy)

σ 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=1N(xix)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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值