# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Scikit-Learn 库的决策树回归(DecisionTreeRegressor)
# Author : geovindu,Geovin Du 涂聚文.
# IDE : PyCharm 2024.3.6 python 3.11
# os : windows 10
# database : mysql 9.0 sql server 2025, postgreSQL 18.0 Oracle 21c Neo4j
# Datetime : 2026/11/25 21:01
# User : geovindu
# Product : PyCharm
# Project : Pysimple
# File : DecisionTreeRegressor.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_percentage_error
# ==========================================
# 1. 准备数据 (2000-2025年深圳二手房均价)
# ==========================================
data = {
'年份': list(range(2000, 2026)),
'均价': [5275, 5531, 5570, 5680, 5980, 5157, 6766, 9947, 9663, 11205, 13847,
16866, 17290, 22445, 26465, 35589, 50934, 55013, 57195, 57786, 66227,
70773, 65637, 64624, 54886, 51690]
}
df = pd.DataFrame(data)
# ==========================================
# 2. 特征工程 (构造滞后特征)
# ==========================================
# 决策树无法直接预测未来的时间,必须将时间序列转化为监督学习问题
# 我们使用前1年、前2年的房价来预测当年的房价
df['前1年房价'] = df['均价'].shift(1)
df['前2年房价'] = df['均价'].shift(2)
# 删除因 shift 产生的空值行
df = df.dropna().reset_index(drop=True)
# 定义特征 X 和 目标 y
X = df[['前1年房价', '前2年房价']]
y = df['均价']
# ==========================================
# 3. 划分训练集与测试集
# ==========================================
# 注意:时间序列数据不能随机打乱划分,必须按时间顺序切分
# 这里我们留出最后 5 年(2021-2025)作为测试集
split_idx = len(df) - 5
X_train, X_test = X.iloc[:split_idx], X.iloc[split_idx:]
y_train, y_test = y.iloc[:split_idx], y.iloc[split_idx:]
# ==========================================
# 4. 构建与训练决策树模型
# ==========================================
# max_depth=3 限制了树的深度,防止在小样本数据上过拟合
model = DecisionTreeRegressor(max_depth=3, random_state=42)
model.fit(X_train, y_train)
# ==========================================
# 5. 预测与评估
# ==========================================
y_pred = model.predict(X_test)
# 计算评估指标
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)
mape = mean_absolute_percentage_error(y_test, y_pred) * 100
print("📊 决策树回归模型评估结果 (测试集: 2021-2025年):")
print(f" - 均方根误差 (RMSE): {rmse:,.2f} 元/㎡")
print(f" - 决定系数 (R²): {r2:.4f}")
print(f" - 平均绝对百分比误差 (MAPE): {mape:.2f}%")
# 打印具体的预测对比
print("\n🔍 具体年份预测对比:")
result_df = pd.DataFrame({
'年份': df['年份'].iloc[split_idx:],
'真实均价': y_test,
'预测均价': y_pred.round(0)
})
print(result_df.to_string(index=False))
# ==========================================
# 6. 可视化结果
# ==========================================
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei'] # 解决中文显示问题
plt.rcParams['axes.unicode_minus'] = False
plt.figure(figsize=(10, 6))
plt.plot(df['年份'].iloc[:split_idx], y_train, 'b-', label='训练集 (历史真实)')
plt.plot(df['年份'].iloc[split_idx:], y_test, 'g-', label='测试集 (真实值)')
plt.plot(df['年份'].iloc[split_idx:], y_pred, 'r--', marker='o', label='决策树预测值')
plt.title('深圳房价走势与决策树回归预测 (2000-2025)')
plt.xlabel('年份')
plt.ylabel('均价 (元/㎡)')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()