首页 > 其他分享 >一元线性回归代码实现

一元线性回归代码实现

时间:2022-11-02 00:45:13浏览次数:57  
标签:__ 一元 return slope 代码 args 线性 avg sum

在代码中需要去分析一些数据,就用到了线性回归方程,关键是最小二乘
根据公式把代码实现了一下,虽然可以用别人封装好的函数实现,但还是想自己写出来强化记忆
# -*- coding: utf-8 -*-
# @Time : 2022/11/1
# @Author : Naihe
# @Email : [email protected]
# @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) # 平均值x
avg_y = avg(*y) # 平均值y
print(avg_x, 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(slope, intercept)

x_ = 12
y_ = slope * x_ + intercept
print(y_)

plt.plot(x, y, color='r', marker='o', linestyle='dashed')
plt.show()

输出内容

5.5 11.0
2.0 0.0
24.0

数据画图显示,对于这种简单的数据,还是很好拟合的

 

 

 


 

标签:__,一元,return,slope,代码,args,线性,avg,sum
From: https://www.cnblogs.com/1314h/p/16849687.html

相关文章