You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SARIMA模型中融入多特征实现日提前样本内预测?

多特征SARIMAX模型实现方案

修改后的完整代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm

# 提取特征和目标变量
data = allmerged[['lagged_actual_total_load_MW', 'DA_total_load_MW', 'DA_onshore_wind_MW', 'DA_offshore_wind_MW', 'DA_solar_MW', 'lagged_actual_wind_offshore_MW', 'lagged_actual_wind_onshore_MW', 'lagged_actual_solar_MW', 'DA_price']]
y = allmerged['imbalance_MW']

# 拆分训练集和测试集(目标变量+外生特征)
size = int(len(allmerged) - 96)
train_y, test_y = y[0:size], y[size:]
train_exog, test_exog = data.iloc[0:size], data.iloc[size:]

print('\t SARIMAX MODEL : Multi-Feature Day-Ahead Forecasting \n')

# 维护目标变量和外生特征的历史数据
history_y = [x for x in train_y]
history_exog = train_exog.values.tolist()  # 转换为列表方便逐行追加
predictions = []

for t in range(len(test_y)):
    # 传入历史目标变量+历史外生特征训练模型
    model = sm.tsa.statespace.SARIMAX(history_y, 
                                      exog=history_exog,
                                      order=(1,0,1),
                                      seasonal_order=(1,1,1,4))
    model_fit = model.fit(disp=0)
    
    # 预测时传入当前测试样本的外生特征
    output = model_fit.forecast(exog=[test_exog.iloc[t]])
    
    yhat = output[0]
    predictions.append(float(yhat))
    
    # 更新历史数据:追加当前测试样本的真实值和对应的外生特征
    obs_y = test_y.iloc[t]
    obs_exog = test_exog.iloc[t].values.tolist()
    history_y.append(obs_y)
    history_exog.append(obs_exog)
    
    print('predicted = %f, expected = %f' % (np.exp(yhat), np.exp(obs_y)))

# 可视化结果
predictions_series = pd.Series(predictions, index=test_y.index)
fig, ax = plt.subplots(figsize=(15,5))
plt.plot(y, label='Expected Values')
plt.plot(np.exp(predictions_series), label='Predicted Values')
plt.legend(loc="upper left")
plt.show()

关键改动说明

  • 拆分外生特征的训练/测试集:同步拆分目标变量y和特征集data,保证时序严格对齐。
  • 传入外生特征到模型:初始化SARIMAX时通过exog参数传入历史外生特征,让模型训练时能利用多维度信息。
  • 预测时传入对应外生特征:调用forecast()必须传入当前测试样本的外生特征,否则模型无法基于多特征生成预测结果。
  • 维护外生特征的历史数据:和目标变量的历史列表同步更新,每次迭代后追加当前测试样本的真实特征,保证下一轮训练的历史数据完整性。

额外注意事项

  • 确保所有外生特征与目标变量的时序完全匹配,避免索引错位导致模型报错。
  • 提前处理特征的缺失值、异常值,否则会干扰模型拟合效果。
  • 原代码中使用np.exp(),推测目标变量y经过了对数转换,需保证预测值的逆变换逻辑与真实值处理一致。

内容的提问来源于stack exchange,提问作者J1999

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 12:50:33