# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:将决策树(DecisionTree)整合进多模型对比流水线
# 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:07
# User : geovindu
# Product : PyCharm
# Project : Pysimple
# File : DecisionTree.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings
import logging
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.metrics import mean_absolute_percentage_error, r2_score
from sklearn.preprocessing import StandardScaler
# 屏蔽警告和日志
warnings.filterwarnings('ignore')
logging.getLogger('statsmodels').setLevel(logging.ERROR)
logging.getLogger('cmdstanpy').setLevel(logging.ERROR)
# 尝试导入可选的时间序列库
try:
from statsmodels.tsa.arima.model import ARIMA
HAS_ARIMA = True
except ImportError:
HAS_ARIMA = False
print("️ 未安装 statsmodels,ARIMA 模型将被跳过。")
try:
from prophet import Prophet
HAS_PROPHET = True
except ImportError:
HAS_PROPHET = False
print("️ 未安装 prophet,Prophet 模型将被跳过。")
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
# ==========================================
# 1. 数据准备 (模拟深圳房价数据 2000-2025)
# ==========================================
years = np.arange(2000, 2026)
# 模拟房价趋势:快速上涨 -> 2021年拐点 -> 2022-2025回调
base_price = 5000 + (years - 2000) * 1500
trend_shift = np.where(years >= 2021, -(years - 2020) * 2500, 0)
noise = np.random.normal(0, 1500, len(years))
prices = base_price + trend_shift + noise
df = pd.DataFrame({'年份': years, '均价': prices})
# ==========================================
# 2. 数据划分
# ==========================================
# 前21年用于训练 (2000-2020),后5年用于测试 (2021-2025)
train_data = df[df['年份'] <= 2020]
test_data = df[df['年份'] > 2020]
X_train = train_data[['年份']].values
y_train = train_data['均价'].values
X_test = test_data[['年份']].values
y_test = test_data['均价'].values
# 未来预测年份 (2026-2030)
future_years = np.arange(2026, 2031)
X_future = future_years.reshape(-1, 1)
# ==========================================
# 3. 模型配置与训练
# ==========================================
models_config = {
'LinearRegression': {'model': LinearRegression(), 'params': {}},
'SVR': {'model': SVR(), 'params': {'C': [10, 100], 'gamma': [0.01, 0.1], 'kernel': ['rbf']}},
'RandomForest': {'model': RandomForestRegressor(random_state=42),
'params': {'n_estimators': [50, 100], 'max_depth': [None, 10]}},
'GradientBoosting': {'model': GradientBoostingRegressor(random_state=42),
'params': {'n_estimators': [50, 100], 'learning_rate': [0.05, 0.1]}},
}
if HAS_ARIMA:
# 定义多个 ARIMA 参数组合进行网格搜索
models_config['ARIMA'] = {
'model': 'arima',
'params': {'order': [(1, 1, 1), (2, 1, 1), (1, 1, 2), (2, 1, 2)]}
}
if HAS_PROPHET:
models_config['Prophet'] = {
'model': 'prophet',
'params': {'changepoint_prior_scale': [0.05, 0.1, 0.5], 'seasonality_mode': ['additive', 'multiplicative']}
}
results = []
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print("\n 开始训练与评估模型...")
for name, config in models_config.items():
print(f"正在训练: {name}...")
# --- ARIMA 模块 ---
if name == 'ARIMA':
best_aic = np.inf
best_order = None
best_arima_model = None
for order in config['params']['order']:
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
model = ARIMA(y_train, order=order).fit()
if model.aic < best_aic:
best_aic = model.aic
best_order = order
best_arima_model = model
except Exception:
continue
if best_arima_model:
y_pred = best_arima_model.forecast(steps=len(y_test))
# 确保 y_pred 是 numpy 数组
if isinstance(y_pred, pd.Series):
y_pred = y_pred.values
r2 = r2_score(y_test, y_pred)
mape = mean_absolute_percentage_error(y_test, y_pred) * 100
results.append({
'模型': name, 'R²': r2, 'MAPE': mape,
'pred': y_pred, 'type': 'arima',
'model_instance': best_arima_model,
'best_params': best_order
})
# --- Prophet 模块 ---
elif name == 'Prophet':
best_mape = np.inf
best_prophet_model = None
best_params = None
df_prophet = pd.DataFrame({'ds': pd.to_datetime(train_data['年份'], format='%Y'), 'y': y_train})
for cps in config['params']['changepoint_prior_scale']:
for sm in config['params']['seasonality_mode']:
try:
model = Prophet(changepoint_prior_scale=cps, seasonality_mode=sm, daily_seasonality=False).fit(
df_prophet)
future = model.make_future_dataframe(periods=len(y_test), freq='YS')
forecast = model.predict(future)
pred = forecast['yhat'].tail(len(y_test)).values
mape = mean_absolute_percentage_error(y_test, pred) * 100
if mape < best_mape:
best_mape = mape
best_prophet_model = model
best_params = (cps, sm)
except Exception:
continue
if best_prophet_model:
future_test = best_prophet_model.make_future_dataframe(periods=len(y_test), freq='YS')
y_pred = best_prophet_model.predict(future_test)['yhat'].tail(len(y_test)).values
r2 = r2_score(y_test, y_pred)
results.append({
'模型': name, 'R²': r2, 'MAPE': best_mape,
'pred': y_pred, 'type': 'prophet',
'model_instance': best_prophet_model,
'best_params': best_params
})
# --- 传统机器学习模型 ---
else:
grid = GridSearchCV(config['model'], config['params'], cv=3, scoring='r2')
grid.fit(X_train_scaled, y_train)
y_pred = grid.predict(X_test_scaled)
r2 = r2_score(y_test, y_pred)
mape = mean_absolute_percentage_error(y_test, y_pred) * 100
results.append({
'模型': name, 'R²': r2, 'MAPE': mape,
'pred': y_pred, 'type': 'ml',
'model_instance': grid.best_estimator_,
'scaler': scaler
})
# ==========================================
# 4. 结果汇总与最佳模型选择
# ==========================================
results_df = pd.DataFrame(results).sort_values('R²', ascending=False)
print("\n" + "=" * 50)
print(" 模型评估结果汇总 (按 R² 排序)")
print("=" * 50)
print(results_df[['模型', 'R²', 'MAPE']].to_string(index=False))
best_model_res = results_df.iloc[0]
print(f"\n 最佳模型为: {best_model_res['模型']} (R²={best_model_res['R²']:.4f})")
# ==========================================
# 5. 未来预测 (2026-2030)
# ==========================================
print("\n" + "=" * 50)
print(f" 基于最佳模型 ({best_model_res['模型']}) 的未来预测")
print("=" * 50)
future_predictions = []
model_type = best_model_res['type']
instance = best_model_res['model_instance']
if model_type == 'arima':
future_pred = instance.forecast(steps=5).values
elif model_type == 'prophet':
future_df = instance.make_future_dataframe(periods=5, freq='YS')
future_pred = instance.predict(future_df)['yhat'].tail(5).values
else:
X_future_scaled = best_model_res['scaler'].transform(X_future)
future_pred = instance.predict(X_future_scaled)
for i, year in enumerate(future_years):
print(f"{year}年 预测均价: {future_pred[i]:,.2f} 元/㎡")
future_predictions.append(future_pred[i])
# ==========================================
# 6. 可视化展示
# ==========================================
plt.figure(figsize=(14, 8))
plt.plot(df['年份'], df['均价'], 'ko-', label='历史真实数据', markersize=5)
plt.plot(test_data['年份'], y_test, 'rs--', label='测试集真实值', markersize=6)
colors = ['blue', 'green', 'orange', 'purple', 'brown', 'pink']
for i, res in enumerate(results):
plt.plot(test_data['年份'], res['pred'], '--', color=colors[i % len(colors)], alpha=0.6,
label=f"{res['模型']} 预测")
plt.plot(future_years, future_predictions, 'g^-', linewidth=2, markersize=8, label='最佳模型未来预测')
plt.axvline(2020.5, color='gray', linestyle='--', alpha=0.5)
plt.text(2020.7, plt.ylim()[1] * 0.9, '训练/测试分割线', rotation=90, fontsize=10)
plt.title('深圳房价历史回顾与多模型未来预测 (2000-2030)', fontsize=16, pad=15)
plt.xlabel('年份', fontsize=12)
plt.ylabel('均价 (元/㎡)', fontsize=12)
plt.legend(loc='upper left', bbox_to_anchor=(1, 1))
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# ==========================================
# 7. ARIMA vs Prophet 深度对比分析 (终极兼容版)
# ==========================================
if HAS_ARIMA and HAS_PROPHET:
print("\n" + "=" * 60)
print("📊 ARIMA vs Prophet 核心预测效果对比")
print("=" * 60)
arima_res = next((r for r in results if r['模型'] == 'ARIMA'), None)
prophet_res = next((r for r in results if r['模型'] == 'Prophet'), None)
if arima_res and prophet_res:
print(f"\n【测试集 (2021-2025) 误差对比】")
print(f"{'指标':<15}{'ARIMA':<15}{'Prophet':<15}{'优胜者':<10}")
print("-" * 55)
winner_r2 = "Prophet" if prophet_res['R²'] > arima_res['R²'] else "ARIMA"
print(f"{'R² (决定系数)':<15}{arima_res['R²']:<15.4f}{prophet_res['R²']:<15.4f}{winner_r2:<10}")
winner_mape = "Prophet" if prophet_res['MAPE'] < arima_res['MAPE'] else "ARIMA"
print(f"{'MAPE (%)':<15}{arima_res['MAPE']:<15.2f}{prophet_res['MAPE']:<15.2f}{winner_mape:<10}")
print(f"\n【未来预测 (2026-2030) 趋势对比】")
print(f"{'年份':<10}{'ARIMA预测值':<15}{'Prophet预测值':<15}{'差异(元/㎡)':<12}")
print("-" * 55)
# 【终极修复点】使用 np.asarray() 兼容 Series 和 ndarray 两种返回类型
arima_forecast_raw = arima_res['model_instance'].forecast(steps=5)
arima_future = np.asarray(arima_forecast_raw) # 智能转换为 numpy 数组
prophet_future_df = prophet_res['model_instance'].make_future_dataframe(periods=5, freq='YS')
prophet_future = np.asarray(prophet_res['model_instance'].predict(prophet_future_df)['yhat'].tail(5))
for i, year in enumerate(future_years):
diff = prophet_future[i] - arima_future[i]
print(f"{year:<10}{arima_future[i]:<15,.0f}{prophet_future[i]:<15,.0f}{diff:<+12,.0f}")
# 可视化对比
plt.figure(figsize=(12, 6))
plt.plot(df['年份'], df['均价'], 'ko-', label='历史真实数据', markersize=4)
plt.plot(test_data['年份'], arima_res['pred'], 'b--o', label=f'ARIMA 回测 (R²={arima_res["R²"]:.2f})')
plt.plot(test_data['年份'], prophet_res['pred'], 'g--o', label=f'Prophet 回测 (R²={prophet_res["R²"]:.2f})')
plt.plot(future_years, arima_future, 'b^-', label='ARIMA 未来预测', alpha=0.7)
plt.plot(future_years, prophet_future, 'g^-', label='Prophet 未来预测', alpha=0.7)
plt.axvline(2020.5, color='gray', linestyle='--', alpha=0.5)
plt.title('ARIMA vs Prophet: 深圳房价预测深度对比', fontsize=14, pad=10)
plt.xlabel('年份')
plt.ylabel('均价 (元/㎡)')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
else:
print("⚠️ 缺少 ARIMA 或 Prophet 的训练结果,无法进行对比。")
else:
print("⚠️ 环境中未同时安装 statsmodels 和 prophet,无法进行对比分析。")