python案例如何利用历史大数据建模预测?

wen python案例 1

Python 利用历史大数据建模预测完整案例

下面用一个完整的实战案例演示:如何用历史销售大数据,构建预测未来销量的模型,涵盖数据处理 → 特征工程 → 建模 → 评估 → 预测全流程。

python案例如何利用历史大数据建模预测?


整体流程

历史数据采集 → 数据清洗 → 特征工程 → 模型训练 → 效果评估 → 上线预测

完整代码案例(销售预测)

环境准备

pip install pandas numpy scikit-learn xgboost matplotlib

数据加载与探索

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 假设历史数据:日期、门店、商品、销量、促销、天气
df = pd.read_csv("sales_history.csv", parse_dates=["date"])
print(df.head())
print(df.info())
print(df.describe())
# 检查缺失
print(df.isnull().sum())
# 时间范围
print(df["date"].min(), df["date"].max())

数据清洗

# 缺失值处理
df["sales"] = df["sales"].fillna(df["sales"].median())
df["weather"] = df["weather"].fillna("unknown")
# 去除异常值(3σ原则)
mean, std = df["sales"].mean(), df["sales"].std()
df = df[(df["sales"] > mean - 3*std) & (df["sales"] < mean + 3*std)]
# 去重
df = df.drop_duplicates(subset=["date", "store", "product"])

特征工程(关键步骤)

# 时间特征
df["year"] = df["date"].dt.year
df["month"] = df["date"].dt.month
df["day"] = df["date"].dt.day
df["weekday"] = df["date"].dt.weekday
df["is_weekend"] = (df["weekday"] >= 5).astype(int)
# 滑窗统计特征(历史滞后特征)
df = df.sort_values(["store", "product", "date"])
df["lag_1"] = df.groupby(["store","product"])["sales"].shift(1)   # 昨日销量
df["lag_7"] = df.groupby(["store","product"])["sales"].shift(7)   # 上周同日
df["lag_30"] = df.groupby(["store","product"])["sales"].shift(30) # 上月同日
# 滚动均值
df["rolling_mean_7"] = df.groupby(["store","product"])["sales"]\
                        .transform(lambda x: x.rolling(7).mean())
df["rolling_mean_30"] = df.groupby(["store","product"])["sales"]\
                        .transform(lambda x: x.rolling(30).mean())
# 类别编码
df = pd.get_dummies(df, columns=["store","product","weather"], drop_first=True)
df = df.dropna()  # 去掉因 shift 产生的 NaN

时间序列切分(避免数据泄露)

# 按时间切分:前80%训练,后20%测试
split_date = df["date"].quantile(0.8)
train = df[df["date"] <= split_date]
test  = df[df["date"] >  split_date]
feature_cols = [c for c in df.columns 
                if c not in ["date","sales"]]
X_train, y_train = train[feature_cols], train["sales"]
X_test,  y_test  = test[feature_cols],  test["sales"]

模型训练(对比多模型)

from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from xgboost import XGBRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
models = {
    "LinearRegression": LinearRegression(),
    "RandomForest": RandomForestRegressor(n_estimators=200, max_depth=10, n_jobs=-1, random_state=42),
    "XGBoost": XGBRegressor(n_estimators=300, learning_rate=0.05, max_depth=6, random_state=42)
}
results = {}
for name, model in models.items():
    model.fit(X_train, y_train)
    pred = model.predict(X_test)
    mae  = mean_absolute_error(y_test, pred)
    rmse = np.sqrt(mean_squared_error(y_test, pred))
    r2   = r2_score(y_test, pred)
    results[name] = (mae, rmse, r2)
    print(f"{name}: MAE={mae:.2f}, RMSE={rmse:.2f}, R²={r2:.3f}")

超参数调优(GridSearch 示例)

from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
param_grid = {
    "n_estimators": [200, 400],
    "max_depth": [4, 6, 8],
    "learning_rate": [0.03, 0.05, 0.1]
}
tscv = TimeSeriesSplit(n_splits=5)
grid = GridSearchCV(XGBRegressor(random_state=42), param_grid,
                    cv=tscv, scoring="neg_mean_absolute_error", n_jobs=-1)
grid.fit(X_train, y_train)
best_model = grid.best_estimator_
print("最佳参数:", grid.best_params_)

特征重要性分析

importances = pd.Series(best_model.feature_importances_, index=feature_cols)
print(importances.sort_values(ascending=False).head(15))
importances.sort_values().tail(15).plot(kind="barh", figsize=(8,6))"Top Feature Importance")
plt.tight_layout()
plt.show()

可视化预测结果

test = test.copy()
test["pred"] = best_model.predict(X_test)
# 按日期聚合真实 vs 预测
daily = test.groupby("date")[["sales","pred"]].sum()
plt.figure(figsize=(12,5))
plt.plot(daily.index, daily["sales"], label="真实", linewidth=2)
plt.plot(daily.index, daily["pred"],  label="预测", linestyle="--")
plt.legend(); plt.title("销量预测 vs 真实")
plt.show()

未来预测(滚动预测)

# 用最新数据构造未来特征
latest = df.sort_values("date").groupby(["store","product"]).tail(1).copy()
latest["date"] = latest["date"] + pd.Timedelta(days=1)
# 更新 lag/rolling 特征(此处简化示意)
latest["lag_1"] = latest["sales"]
latest["lag_7"] = latest["rolling_mean_7"]
future_pred = best_model.predict(latest[feature_cols])
print("明日各门店商品预测销量:")
print(pd.DataFrame({"store": latest.index, "pred_sales": future_pred}))

几个关键要点

环节 关键点
数据切分 时间序列必须按时间切,不能随机 split,否则数据泄露
特征工程 滞后特征(lag)、滚动统计、时间字段是核心
防泄露 任何使用未来信息的特征都不能进训练集
评估指标 回归用 MAE/RMSE/R²;预测偏差关注 MAPE
模型选择 线性模型可解释;树模型(XGBoost/LightGBM)精度更高
业务验证 预测结果要结合业务常识审查

进阶方向

  • 时序专用模型:Prophet、ARIMA、LSTM/Transformer
  • 自动化特征:tsfresh、featuretools
  • 超参优化:Optuna、Hyperopt
  • 上线部署:Flask/FastAPI + 定时任务,或 MLflow 管理模型
  • 概率预测:Quantile Regression、贝叶斯模型给出置信区间

如果你有具体场景(比如股票、流量、用户流失、设备故障预测),告诉我,我可以给出更匹配的特征工程与模型方案。

抱歉,评论功能暂时关闭!