python:Linear Regression
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:pip install scikit-learn pip3 install scikit-learn -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip3 install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
# Author : geovindu,Geovin Du 涂聚文.
# IDE : PyCharm 2024.3.6 python 3.11
# os : windows 10
# database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j
# Datetime : 2026/11/20 23:09
# User : geovindu
# Product : PyCharm
# Project : PythonAlgorithms
# File : LinearRegression.py
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# 设置中文字体(Windows 常用)
# ========== 字体修复段 ==========
# 优先顺序:微软雅黑 > 黑体 > 宋体
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'SimSun']
plt.rcParams['axes.unicode_minus'] = False # 负号正常显示
#matplotlib.rcParams['axes.unicode_minus'] = False
# 清除缓存(可选,第一次乱码时启用一次)
# matplotlib.font_manager._rebuild()
# =================================
# 1. 准备数据
years = np.array([2000, 2005, 2008, 2010, 2013, 2015, 2017, 2019, 2021, 2023, 2024, 2025]).reshape(-1, 1)
prices = np.array([5000, 7000, 11000, 16600, 24900, 41400, 51400, 54700, 57000, 63700, 58400, 53300])
# 2. 模型训练
model = LinearRegression()
model.fit(years, prices)
# 3. 输出参数
w = model.coef_[0]
b = model.intercept_
print(f"拟合的线性方程: y = {w:.2f} * X + {b:.2f}")
print(f"模型解释度 (R²): {model.score(years, prices):.4f}")
# 4. 预测
future_years = np.array([2026, 2027]).reshape(-1, 1)
predicted_prices = model.predict(future_years)
print(f"\n预测 2026 年均价: {predicted_prices[0]:.2f} 元/㎡")
print(f"预测 2027 年均价: {predicted_prices[1]:.2f} 元/㎡")
# 5. 可视化
plt.figure(figsize=(10, 6))
plt.scatter(years, prices, color='blue', label='历史真实房价')
plt.plot(years, model.predict(years), color='red', label='线性回归拟合线')
plt.scatter(future_years, predicted_prices, color='green', marker='x', s=100, label='未来预测值')
plt.title('深圳房价线性回归预测 (2000-2025)')
plt.xlabel('年份')
plt.ylabel('均价 (元/㎡)')
plt.legend()
plt.grid(True)
plt.show()
输出:
拟合的线性方程: y = 2666.19 * X + -5335345.93
模型解释度 (R²): 0.9035
预测 2026 年均价: 66361.46 元/㎡
预测 2027 年均价: 69027.65 元/㎡

哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)
浙公网安备 33010602011771号