首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >python 最小二乘法实现线性回归

python 最小二乘法实现线性回归

作者头像
Dragon水魅
发布2026-01-23 18:51:48
发布2026-01-23 18:51:48
1080
举报
基本原理

代码实现

线性回归的原理留作后补,以下为代码实现:

代码语言:javascript
复制
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'SimHei'  # 黑体

time = []
year = []
average_year_time = 0
average_year_year = 0

data = [[12, 1896], [11, 1900], [11, 1904], [10.8, 1908], [10.8, 1912], [10.8, 1920], [10.6, 1924], [10.8, 1928],[10.3, 1932], [10.3, 1936], [10.3, 1948], [10.4, 1952], [10.5, 1956], [10.2, 1960], [10.0, 1964], [9.95, 1968],[10.14, 1972], [10.06, 1976], [10.25, 1980], [9.99, 1984], [9.92, 1988], [9.96, 1992], [9.84, 1996],[9.87, 2000], [9.85, 2004], [9.69, 2008]]
length = len(data)

# plt.xlim(1896, 2008)
# plt.ylim(9, 12)  # 设置坐标区间

for i in data:
    time.append(i[0])
    year.append(i[1])

time = np.array(time)
year = np.array(year)

average_year = sum(year) / length  # year拔
average_time = sum(time) / length  # time拔

for i in data:
    average_year_time = average_year_time + i[0] * i[1]
    average_year_year = average_year_year + i[1] ** 2
average_year_time = average_year_time / length  # (year, time)拔
average_year_year = average_year_year / length  # (year, year)拔

w1 = (average_year_time - average_year * average_time) / (average_year_year - average_year * average_year)
w0 = average_time - w1 * average_year

# 线性回归:t = w0 + w1 * x
if w1 > 0:
    print('t={}+{}x'.format(w0, w1))
else:
    print('t={}{}x'.format(w0, w1))

t_2008 = w0 + w1 * 2008
t_1896 = w0 + w1 * 1896  # 回归直线的两个端点

plt.plot(np.array([1896, 2008]), np.array([t_1896, t_2008]), '-r', label='回归直线')

for i in data:
    plt.scatter(i[1], i[0], c='#DC143C', alpha=0.4)

plt.legend()
plt.show()
在这里插入图片描述
在这里插入图片描述
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2026-01-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 基本原理
  • 代码实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档