机器学习模型
机器学习模型在时序分析中通过将时间序列问题转化为监督学习问题来进行预测,相比时序分析-传统统计模型能更好地处理非线性关系和融合外部特征。
问题转化方法
将时序预测转化为监督学习问题的关键是构建特征与目标的映射关系:
# 创建滞后特征
for lag in range(1, 8):
df[f'lag_{lag}'] = df['value'].shift(lag)
# 创建滑动窗口统计特征
df['rolling_mean_7d'] = df['value'].rolling(window=7).mean().shift(1)
df['rolling_std_7d'] = df['value'].rolling(window=7).std().shift(1)
# 加入外部特征
df = df.merge(calendar_df[['date', 'is_holiday']], on='date', how='left')
df = df.merge(weather_df[['date', 'temperature']], on='date', how='left')
# 准备模型输入
X = df.dropna().drop(['date', 'value'], axis=1)
y = df.dropna()['value']
XGBoost/LGBM模型
树集成模型在时序预测中表现出色,能自动处理特征间的非线性关系。
from xgboost import XGBRegressor
from lightgbm import LGBMRegressor
# XGBoost模型
xgb_model = XGBRegressor(
n_estimators=100,
learning_rate=0.1,
max_depth=5,
random_state=42
)
xgb_model.fit(X_train, y_train)
# LightGBM模型
lgb_model = LGBMRegressor(
n_estimators=100,
learning_rate=0.1,
max_depth=5,
random_state=42
)
lgb_model.fit(X_train, y_train)
SVR/随机森林回归
支持向量回归(SVR)和随机森林也是时序预测的有效选择:
from sklearn.ensemble import RandomForestRegressor
from sklearn.svm import SVR
# 随机森林模型
rf_model = RandomForestRegressor(
n_estimators=100,
max_depth=10,
random_state=42
)
rf_model.fit(X_train, y_train)
# SVR模型
svr_model = SVR(kernel='rbf', C=100, gamma=0.1, epsilon=0.1)
svr_model.fit(X_train, y_train)
特征重要性分析
机器学习模型的优势之一是可以分析特征重要性,了解哪些因素对预测最关键:
# XGBoost特征重要性
importance = pd.DataFrame({
'feature': X.columns,
'importance': xgb_model.feature_importances_
}).sort_values('importance', ascending=False)
# 绘制重要性图
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.barh(importance['feature'][:10], importance['importance'][:10])
plt.title('Feature Importance')
plt.xlabel('Importance')
plt.gca().invert_yaxis()
plt.show()
优缺点与适用场景
优点
- 能够处理非线性关系
- 可融合多种外部特征
- 处理缺失值能力较强
- 模型可解释性较好(特征重要性)
缺点
- 需要大量特征工程
- 可能忽略时序数据的内在时间依赖结构
- 训练数据需求较大
适用场景
- 具有多维度外部因素的业务指标
- 存在非线性关系的指标
- 需要可解释性的预测结果
与其他模块的关系
机器学习模型的效果高度依赖于时序分析-特征构建与变量增强的质量。与时序分析-传统统计模型相比,机器学习模型能更好处理非线性和外部变量,但可能需要更多的特征工程。对于复杂时序问题,可能需要与时序分析-混合方法结合使用,或在需要捕捉长期依赖关系时转向时序分析-深度学习模型。通过时序分析-评估指标与误差分析可以确定模型的实际效果。