python:ElasticNet
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:ElasticNet 弹性网 回归算法
# 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/23 20:55
# User : geovindu
# Product : PyCharm
# Project : Pysimple
# File : ElasticNet.py
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import ElasticNet, ElasticNetCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import TimeSeriesSplit
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_percentage_error
plt.rcParams['font.sans-serif'] = ["SimHei", "Microsoft YaHei", "WenQuanYi Micro Hei",
"WenQuanYi Zen Hei", "Noto Sans CJK SC", "Arial Unicode MS"]
plt.rcParams['axes.unicode_minus'] = False
# ==========================================
# 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)
print("=== 原始数据 ===")
print(df.to_string(index=False))
# ==========================================
# 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)
df_feat['同比变化率'] = df_feat[target_col].pct_change(1)
return df_feat.dropna().reset_index(drop=True)
df_features = create_features(df, '均价', lags=[1, 2, 3])
feature_cols = [c for c in df_features.columns if c not in ['年份', '均价']]
print(f"\n=== 特征列表 ({len(feature_cols)}个) ===")
for i, col in enumerate(feature_cols, 1):
print(f" {i}. {col}")
# ==========================================
# 3. 划分训练/测试集(时序数据不能随机打乱)
# ==========================================
split_idx = len(df_features) - 5 # 最后5年做测试
train_feat = df_features.iloc[:split_idx]
test_feat = df_features.iloc[split_idx:]
X_train = train_feat[feature_cols]
y_train = train_feat['均价']
X_test = test_feat[feature_cols]
y_test = test_feat['均价']
print(f"\n=== 数据划分 ===")
print(f"训练集: {train_feat['年份'].min()}-{train_feat['年份'].max()} ({len(train_feat)}条)")
print(f"测试集: {test_feat['年份'].min()}-{test_feat['年份'].max()} ({len(test_feat)}条)")
# ==========================================
# 4. ElasticNet 建模
# 用 ElasticNetCV 同时搜索 alpha 和 l1_ratio
# ==========================================
# alpha 控制正则化强度,l1_ratio 控制 L1/L2 混合比例
# l1_ratio=1 退化为 Lasso,l1_ratio=0 退化为 Ridge
alphas = np.logspace(-2, 3, 50)
l1_ratios = [0.1, 0.3, 0.5, 0.7, 0.9, 1.0]
# 用 TimeSeriesSplit 做时序交叉验证,避免未来信息泄露
tscv = TimeSeriesSplit(n_splits=4)
elastic_net_cv = ElasticNetCV(
l1_ratio=l1_ratios,
alphas=alphas,
cv=tscv,
max_iter=50000,
random_state=42,
n_jobs=-1
)
# 标准化 + ElasticNet 管道
pipeline = Pipeline([
('scaler', StandardScaler()),
('elasticnet', elastic_net_cv)
])
pipeline.fit(X_train, y_train)
# 提取最优参数
best_alpha = pipeline.named_steps['elasticnet'].alpha_
best_l1_ratio = pipeline.named_steps['elasticnet'].l1_ratio_
print(f"\n=== ElasticNet 最优参数 ===")
print(f"alpha (正则化强度): {best_alpha:.4f}")
print(f"l1_ratio (L1占比): {best_l1_ratio:.2f}")
if best_l1_ratio == 1.0:
print("→ 等价于 Lasso 回归")
elif best_l1_ratio == 0.0:
print("→ 等价于 Ridge 回归")
else:
print(f"→ L1:L2 比例约为 {best_l1_ratio:.0%}:{1-best_l1_ratio:.0%}")
# ==========================================
# 5. 模型评估
# ==========================================
y_train_pred = pipeline.predict(X_train)
y_test_pred = pipeline.predict(X_test)
print(f"\n=== 模型评估 ===")
print(f"{'指标':<12}{'训练集':>12}{'测试集':>12}")
print(f"{'R²':<12}{r2_score(y_train, y_train_pred):>12.4f}{r2_score(y_test, y_test_pred):>12.4f}")
print(f"{'MSE':<12}{mean_squared_error(y_train, y_train_pred):>12.0f}{mean_squared_error(y_test, y_test_pred):>12.0f}")
print(f"{'MAPE':<12}{mean_absolute_percentage_error(y_train, y_train_pred)*100:>11.2f}%"
f"{mean_absolute_percentage_error(y_test, y_test_pred)*100:>11.2f}%")
# 测试集逐年对比
print(f"\n=== 测试集逐年预测 (2021-2025) ===")
print(f"{'年份':<8}{'真实值':>10}{'预测值':>10}{'误差':>10}{'误差率':>10}")
for i, row in enumerate(test_feat.itertuples()):
pred = y_test_pred[i]
error = pred - row.均价
error_pct = error / row.均价 * 100
print(f"{row.年份:<8}{row.均价:>10.0f}{pred:>10.0f}{error:>10.0f}{error_pct:>9.2f}%")
# ==========================================
# 6. 特征重要性分析
# ==========================================
coef = pipeline.named_steps['elasticnet'].coef_
feature_importance = pd.DataFrame({
'特征': feature_cols,
'系数': coef,
'绝对值': np.abs(coef)
}).sort_values('绝对值', ascending=False)
print(f"\n=== 特征重要性 (按系数绝对值排序) ===")
print(f"{'特征':<18}{'系数':>12}{'方向':>8}")
for _, row in feature_importance.iterrows():
direction = '正向' if row['系数'] > 0 else '负向'
if abs(row['系数']) < 1e-6:
direction = '被筛除'
print(f"{row['特征']:<18}{row['系数']:>12.2f}{direction:>8}")
# ==========================================
# 7. 未来 5 年预测 (2026-2030)
# ==========================================
future_years = list(range(2026, 2031))
history = df['均价'].tolist()
future_preds = []
print(f"\n=== 未来 5 年预测 (2026-2030) ===")
for year in future_years:
# 构造预测特征(递归回填)
X_future = pd.DataFrame({
'滞后_1年': [history[-1]],
'滞后_2年': [history[-2]],
'滞后_3年': [history[-3]],
'滚动_3年均价': [np.mean(history[-3:])],
'滚动_3年波动率': [np.std(history[-3:])],
'同比变化量': [history[-1] - history[-2]],
'同比变化率': [(history[-1] - history[-2]) / history[-2]]
}, columns=feature_cols)
pred = pipeline.predict(X_future)[0]
future_preds.append(pred)
history.append(pred)
change = (pred - history[-2]) / history[-2] * 100 if len(history) > 1 else 0
print(f"{year}年: {pred:>8.0f} 元/㎡ (同比 {change:>+.2f}%)")
# ==========================================
# 8. 可视化
# ==========================================
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
# --- 图1: 历史拟合 + 未来预测 ---
ax = axes[0, 0]
ax.plot(df['年份'], df['均价'], 'ko-', label='历史真实房价', markersize=4, linewidth=2)
# 训练集拟合
train_years = train_feat['年份'].values
ax.plot(train_years, y_train_pred, 'b--', label='训练集拟合', alpha=0.7)
# 测试集预测
test_years = test_feat['年份'].values
ax.plot(test_years, y_test_pred, 'gs--', label='测试集预测', markersize=8, alpha=0.8)
# 未来预测
ax.plot(future_years, future_preds, 'r:^', label='未来预测', markersize=10, linewidth=2.5)
ax.axvline(2025.5, color='gray', linestyle='--', alpha=0.5)
ax.text(2025.7, ax.get_ylim()[1]*0.9, '预测起点', fontsize=10, color='gray', rotation=90)
ax.set_title('ElasticNet 回归:历史拟合与未来预测', fontsize=14)
ax.set_xlabel('年份', fontsize=12)
ax.set_ylabel('均价 (元/㎡)', fontsize=12)
ax.legend(fontsize=10)
ax.grid(True, alpha=0.3)
# --- 图2: 特征重要性 ---
ax = axes[0, 1]
colors = ['#2ecc71' if x > 0 else '#e74c3c' for x in feature_importance['系数']]
ax.barh(feature_importance['特征'], feature_importance['系数'], color=colors)
ax.set_title('特征重要性(系数大小与方向)', fontsize=14)
ax.set_xlabel('回归系数', fontsize=12)
ax.axvline(0, color='black', linewidth=0.8)
ax.grid(True, alpha=0.3, axis='x')
ax.invert_yaxis()
# --- 图3: 预测误差分布 ---
ax = axes[1, 0]
errors = y_test_pred - y_test
bars = ax.bar(test_years, errors, color=['#e74c3c' if e > 0 else '#3498db' for e in errors])
ax.axhline(0, color='black', linewidth=0.8)
ax.set_title('测试集预测误差 (预测值 - 真实值)', fontsize=14)
ax.set_xlabel('年份', fontsize=12)
ax.set_ylabel('误差 (元/㎡)', fontsize=12)
ax.grid(True, alpha=0.3, axis='y')
for bar, err in zip(bars, errors):
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + (500 if err > 0 else -1500),
f'{err:.0f}', ha='center', fontsize=9)
# --- 图4: 正则化路径(alpha 对系数的影响)---
ax = axes[1, 1]
# 手动计算不同 alpha 下的系数
alphas_plot = np.logspace(-1, 3, 30)
coefs_plot = []
for alpha in alphas_plot:
pipe_tmp = Pipeline([('scaler', StandardScaler()),
('en', ElasticNet(alpha=alpha, l1_ratio=best_l1_ratio, max_iter=50000))])
pipe_tmp.fit(X_train, y_train)
coefs_plot.append(pipe_tmp.named_steps['en'].coef_)
coefs_plot = np.array(coefs_plot)
for i, col in enumerate(feature_cols):
ax.plot(alphas_plot, coefs_plot[:, i], label=col, linewidth=1.5)
ax.axvline(best_alpha, color='red', linestyle='--', label=f'最优 alpha={best_alpha:.2f}')
ax.set_title('正则化路径(alpha 增大时系数变化)', fontsize=14)
ax.set_xlabel('alpha (正则化强度)', fontsize=12)
ax.set_ylabel('回归系数', fontsize=12)
ax.set_xscale('log')
ax.legend(fontsize=8, loc='best')
ax.grid(True, alpha=0.3)
ax.axhline(0, color='black', linewidth=0.5)
plt.tight_layout()
plt.show()
# ==========================================
# 9. 与 Lasso / Ridge 对比
# ==========================================
from sklearn.linear_model import Lasso, Ridge
models = {
'Ridge (L2)': Ridge(alpha=best_alpha, max_iter=50000),
'Lasso (L1)': Lasso(alpha=best_alpha, max_iter=50000),
'ElasticNet': ElasticNet(alpha=best_alpha, l1_ratio=best_l1_ratio, max_iter=50000)
}
print(f"\n=== 三种正则化方法对比 (alpha={best_alpha:.2f}) ===")
print(f"{'模型':<16}{'测试R²':>10}{'测试MAPE':>12}{'非零特征数':>12}")
for name, model in models.items():
pipe_cmp = Pipeline([('scaler', StandardScaler()), ('model', model)])
pipe_cmp.fit(X_train, y_train)
pred_cmp = pipe_cmp.predict(X_test)
n_nonzero = np.sum(np.abs(pipe_cmp.named_steps['model'].coef_) > 1e-6)
print(f"{name:<16}{r2_score(y_test, pred_cmp):>10.4f}"
f"{mean_absolute_percentage_error(y_test, pred_cmp)*100:>11.2f}%"
f"{n_nonzero:>10}/{len(feature_cols)}")


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