python:Ridge
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:岭回归 Ridge(L2正则)
# 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/21 20:39
# User : geovindu
# Product : PyCharm
# Project : Pysimple
# File : Ridge.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_percentage_error
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'SimSun']
plt.rcParams['axes.unicode_minus'] = False
# ==========================================
# 1. 真实深圳房价数据 (2005-2025)
# ==========================================
data = {
'年份': list(range(2005, 2026)),
'均价': [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)
df['ds'] = pd.to_datetime(df['年份'], format='%Y')
df = df.rename(columns={'均价': 'y'})
# ==========================================
# 2. 时间序列特征工程(防数据穿越)
# ==========================================
def create_features(df, target_col, lags=[1, 2, 3]):
df_feat = df.copy()
for lag in lags:
df_feat[f'滞后_{lag}年'] = df_feat[target_col].shift(lag)
df_feat['滚动_3年均价'] = df_feat[target_col].shift(1).rolling(window=3).mean()
df_feat['滚动_3年波动率'] = df_feat[target_col].shift(1).rolling(window=3).std()
df_feat['同比变化量'] = df_feat[target_col].diff(1)
return df_feat.dropna().reset_index(drop=True)
df_features = create_features(df, 'y', lags=[1, 2, 3])
feature_cols = [c for c in df_features.columns if c not in ['ds', 'y', '年份']]
# ==========================================
# 3. 划分训练/测试集(最后 5 年做测试)
# ==========================================
split_idx = len(df_features) - 5
train_feat = df_features.iloc[:split_idx]
test_feat = df_features.iloc[split_idx:]
X_train, y_train = train_feat[feature_cols], train_feat['y']
X_test, y_test = test_feat[feature_cols], test_feat['y']
# ==========================================
# 4. 交叉验证选择最佳 alpha
# ==========================================
alphas = np.logspace(-3, 3, 30)
cv_scores = []
for alpha in alphas:
pipeline = Pipeline([
('scaler', StandardScaler()),
('ridge', Ridge(alpha=alpha))
])
scores = cross_val_score(pipeline, X_train, y_train, cv=3, scoring='neg_mean_squared_error')
cv_scores.append(-scores.mean())
best_alpha = alphas[np.argmin(cv_scores)]
print(f"交叉验证选出的最佳 alpha: {best_alpha:.4f}")
# ==========================================
# 5. 训练最终模型并评估
# ==========================================
model = Pipeline([
('scaler', StandardScaler()),
('ridge', Ridge(alpha=best_alpha))
])
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(f"\n=== 测试集评估 (2021-2025) ===")
print(f"R²: {r2_score(y_test, y_pred):.4f}")
print(f"MSE: {mean_squared_error(y_test, y_pred):.2f}")
print(f"MAPE: {mean_absolute_percentage_error(y_test, y_pred) * 100:.2f}%")
# 打印每年预测明细
print(f"\n{'年份':<8}{'真实值':>10}{'预测值':>10}{'误差率':>10}")
for i, row in enumerate(test_feat.itertuples()):
err = abs(y_pred[i] - row.y) / row.y * 100
print(f"{row.年份:<8}{row.y:>10.0f}{y_pred[i]:>10.0f}{err:>9.2f}%")
# ==========================================
# 6. 递归外推预测未来 5 年 (2026-2030)
# ==========================================
history = df['y'].tolist() # 完整历史序列
future_preds = []
for year in range(2026, 2031):
# 用最近的历史构造滞后特征
lag1 = history[-1]
lag2 = history[-2]
lag3 = history[-3]
roll3_mean = np.mean(history[-3:])
roll3_std = np.std(history[-3:])
diff1 = history[-1] - history[-2]
X_future = pd.DataFrame([[lag1, lag2, lag3, roll3_mean, roll3_std, diff1]], columns=feature_cols)
pred = model.predict(X_future)[0]
future_preds.append(pred)
history.append(pred) # 回填,供下一年递归使用
print(f"{year} 年预测均价: {pred:.0f} 元/㎡")
# ==========================================
# 7. 可视化
# ==========================================
plt.figure(figsize=(14, 7))
plt.plot(df['ds'], df['y'], label='历史真实房价', color='black', linewidth=2.5, zorder=10)
plt.plot(test_feat['ds'], y_test, label='测试集真实值', color='blue', marker='o', markersize=8)
plt.plot(test_feat['ds'], y_pred, label='Ridge 回测预测', color='orange', linestyle='--', marker='x')
future_years = pd.to_datetime(range(2026, 2031), format='%Y')
plt.plot(future_years, future_preds, label='Ridge 未来外推', color='red', linestyle=':', marker='D', linewidth=2)
plt.title('深圳房价:Ridge 回归拟合与未来 5 年预测', fontsize=16)
plt.xlabel('年份', fontsize=12)
plt.ylabel('均价 (元/㎡)', fontsize=12)
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()


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