一元线性回归代码实现
在代码中需要去预测一些数据,就用到了线性回归方程,其关键是最小二乘
根据公式把代码实现了一下,虽然可以用别人封装好的函数实现,但还是想自己写出来强化记忆
# -*- coding: utf-8 -*- # @Time : 2022/11/1 # @Author : Naihe # @Email : 239144498@qq.com # @File : LinearRegression.py # @Software: PyCharm import matplotlib.pyplot as plt def avg(*args): """求平均值""" return sum(args) / len(args) def subt(x, _x): """求差""" return x - _x def square(x, _x=0): """求平方""" return subt(x, _x) ** 2 def square_sum(gap=0, *args): """求平方和""" return sum(map(square, args, [gap] * len(args))) def mult(x, _x, y, _y): """求乘积""" return subt(x, _x) * subt(y, _y) def iter_mult_sum(x, y, _x=0, _y=0): """求乘积和""" for x, y in zip(x, y): yield mult(x, _x, y, _y) if __name__ == '__main__': x = list(range(1, 11)) y = list(range(2, 22, 2)) avg_x = avg(*x) avg_y = avg(*y) dived = sum(iter_mult_sum(x, y, avg_x, avg_y)) div = square_sum(avg_x, *x) slope = dived / div intercept = avg_y - slope * avg_x print(f"斜率:{slope}\t截距{intercept}") x_ = 222 y_ = slope * x_ + intercept print(f"预测值:{x_}\t结果:{y_}") plt.plot(x, y, color='r', marker='o', linestyle='dashed') plt.show()
输出内容
斜率:2.0 截距0.0
预测值:222 结果:444.0
数据画图显示,对于这种简单的数据,还是很好拟合的