python:Lasso

python 复制代码
# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# 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/22 22:09 
# User      :  geovindu
# Product   : PyCharm
# Project   : Pysimple
# File      : Lasso.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import Lasso, LassoCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score
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. 真实深圳房价数据 (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 年做测试)
#    关键修正:保留 DataFrame 列名,不转 .values
# ==========================================
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. LassoCV 自动选择最佳 alpha(L1 强度)
# ==========================================
# 方法一:手动网格 + 交叉验证(透明可控)
alphas = np.logspace(0, 4, 40)   # Lasso 的 alpha 量级通常比 Ridge 大
cv_scores = []
for alpha in alphas:
    pipe = Pipeline([('scaler', StandardScaler()), ('lasso', Lasso(alpha=alpha, max_iter=50000))])
    scores = cross_val_score(pipe, X_train, y_train, cv=3, scoring='neg_mean_squared_error')
    cv_scores.append(-scores.mean())
best_alpha_manual = alphas[np.argmin(cv_scores)]

# 方法二:sklearn 内置 LassoCV(等价,更简洁)
lasso_cv = LassoCV(alphas=alphas, cv=3, max_iter=50000)
scaler = StandardScaler().fit(X_train)
lasso_cv.fit(scaler.transform(X_train), y_train)
best_alpha = lasso_cv.alpha_

print(f"手动 CV 最佳 alpha: {best_alpha_manual:.2f}")
print(f"LassoCV 最佳 alpha: {best_alpha:.2f}")

# ==========================================
# 5. 训练最终模型并评估
# ==========================================
model = Pipeline([
    ('scaler', StandardScaler()),
    ('lasso', Lasso(alpha=best_alpha, max_iter=50000))
])
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. L1 稀疏化效果:哪些特征被保留、哪些被剔除
# ==========================================
coef = model[-1].coef_
print(f"\n=== Lasso 系数(标准化后,0 表示被剔除)===")
for name, c in sorted(zip(feature_cols, coef), key=lambda x: -abs(x[1])):
    flag = "保留" if abs(c) > 1e-6 else "剔除"
    print(f"{name:<18} 系数: {c:>10.2f}  [{flag}]")
n_selected = np.sum(np.abs(coef) > 1e-6)
print(f"\n共 {len(feature_cols)} 个特征,Lasso 保留了 {n_selected} 个")

# ==========================================
# 7. 递归外推预测未来 5 年 (2026-2030)
#    关键修正:字典补全 + 列顺序对齐 feature_cols
# ==========================================
history = df['y'].tolist()
future_preds = []
print(f"\n=== 未来 5 年预测 ===")
for year in range(2026, 2031):
    lag1, lag2, lag3 = history[-1], history[-2], history[-3]
    roll3_mean = np.mean(history[-3:])
    roll3_std = np.std(history[-3:])
    diff1 = history[-1] - history[-2]

    X_future = pd.DataFrame({
        '滞后_1年': [lag1],
        '滞后_2年': [lag2],
        '滞后_3年': [lag3],
        '滚动_3年均价': [roll3_mean],
        '滚动_3年波动率': [roll3_std],
        '同比变化量': [diff1]
    }, columns=feature_cols)   # columns 保证列顺序与训练一致

    pred = model.predict(X_future)[0]
    future_preds.append(pred)
    history.append(pred)  # 回填,供下一年递归使用
    print(f"{year} 年预测均价: {pred:.0f} 元/㎡")

# ==========================================
# 8. 可视化
# ==========================================
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='Lasso 回测预测', color='green', linestyle='--', marker='x')

future_years = pd.to_datetime(range(2026, 2031), format='%Y')
plt.plot(future_years, future_preds, label='Lasso 未来外推', color='red', linestyle=':', marker='D', linewidth=2)

plt.title('深圳房价:Lasso 回归(L1 正则)拟合与未来 5 年预测', fontsize=16)
plt.xlabel('年份', fontsize=12)
plt.ylabel('均价 (元/㎡)', fontsize=12)
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()

输出:

、

相关推荐
Csvn25 分钟前
Nginx HTTPS 与安全加固:会话复用、OCSP、mTLS 与限流取舍
后端·nginx
多加点辣也没关系1 小时前
JavaScript|第42章:安全与最佳实践
开发语言·javascript·安全
码云社区1 小时前
Spring Boot上门按摩服务系统源码:上门到店服务目录与门店协同方案
java·spring boot·后端·上门服务·上门按摩·上门小程序
3095566661 小时前
股票数据落库前的去重与主键设计:一次 SQLite 写入实录
java·开发语言·jvm·数据库·redis·python·sqlite
AAA修煤气灶刘哥1 小时前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
Cosolar1 小时前
LoopForge:把团队的交付经验变成可执行的工程资产
人工智能·后端·agent
CyrusYiVPP1 小时前
决策树背答案背到 24 片叶子?剪枝三刀砍回 5 片,测试集从 0.749 涨回 0.845,ML数学基础第13期
人工智能·python
tong_li1 小时前
给娃做个 AI 陪写作业助手:LangChain4j 入门(四):向量库搬进 Qdrant(向量数据库入门)
后端
Rain的Java大神之路1 小时前
大表 JOIN 不必靠堆内存:Dojao 的跨源 SQL、减量溢写与 Python UDF 实战
java·大数据·后端