DeepAR 模型基于自回归循环神经网络,利用交叉学习在面板数据上进行优化,生成概率预测。DeepAR 使用马尔可夫链蒙特卡洛采样器获取其预测分布,其条件概率如下所示:P(y[t+1:t+H]  y[:t],  x[:t+H](f),  x(s))\mathbb{P}(\mathbf{y}_{[t+1:t+H]}|\;\mathbf{y}_{[:t]},\; \mathbf{x}^{(f)}_{[:t+H]},\; \mathbf{x}^{(s)})

其中 x(s)\mathbf{x}^{(s)} 是静态外生输入,x[:t+H](f)\mathbf{x}^{(f)}_{[:t+H]} 是预测时可用的未来外生输入。通过将隐藏状态 ht\mathbf{h}_{t} 转换为预测分布参数 θt\theta_{t},然后通过蒙特卡洛采样轨迹生成样本 y^[t+1:t+H]\mathbf{\hat{y}}_{[t+1:t+H]} 来获得预测结果。

ht=RNN([yt,xt+1(f),x(s)],ht1)θt=Linear(ht)y^t+1=sample(  P(yt+1    θt)  ) \begin{align} \mathbf{h}_{t} &= \textrm{RNN}([\mathbf{y}_{t},\mathbf{x}^{(f)}_{t+1},\mathbf{x}^{(s)}], \mathbf{h}_{t-1})\\ \mathbf{\theta}_{t}&=\textrm{Linear}(\mathbf{h}_{t}) \\ \hat{y}_{t+1}&=\textrm{sample}(\;\mathrm{P}(y_{t+1}\;|\;\mathbf{\theta}_{t})\;) \end{align}

参考文献
- David Salinas, Valentin Flunkert, Jan Gasthaus, Tim Januschowski (2020). “DeepAR:使用自回归循环网络的概率预测”。International Journal of Forecasting.
- Alexander Alexandrov 等 (2020). “GluonTS:Python 中的概率和神经时间序列建模”。Journal of Machine Learning Research.

外生变量、损失函数和参数可用性

鉴于推理过程中的采样程序,DeepAR 仅支持 DistributionLoss 作为训练损失函数。

请注意,DeepAR 使用蒙特卡洛方法生成非参数预测分布。我们在验证期间也使用此采样程序,使其更接近推理过程。因此,验证时仅提供 MQLoss

此外,蒙特卡洛意味着历史外生变量对模型不可用。


来源

解码器

 Decoder (in_features, out_features, hidden_size, hidden_layers)

*多层感知机解码器

参数
in_features: int,输入维度。
out_features: int,输出维度。
hidden_size: int,隐藏层维度。
num_layers: int,隐藏层数量。
*


来源

DeepAR

 DeepAR (h, input_size:int=-1, lstm_n_layers:int=2,
         lstm_hidden_size:int=128, lstm_dropout:float=0.1,
         decoder_hidden_layers:int=0, decoder_hidden_size:int=0,
         trajectory_samples:int=100, stat_exog_list=None,
         hist_exog_list=None, futr_exog_list=None,
         exclude_insample_y=False, loss=DistributionLoss(),
         valid_loss=MAE(), max_steps:int=1000, learning_rate:float=0.001,
         num_lr_decays:int=3, early_stop_patience_steps:int=-1,
         val_check_steps:int=100, batch_size:int=32,
         valid_batch_size:Optional[int]=None, windows_batch_size:int=1024,
         inference_windows_batch_size:int=-1, start_padding_enabled=False,
         step_size:int=1, scaler_type:str='identity', random_seed:int=1,
         drop_last_loader=False, alias:Optional[str]=None, optimizer=None,
         optimizer_kwargs=None, lr_scheduler=None,
         lr_scheduler_kwargs=None, dataloader_kwargs=None,
         **trainer_kwargs)

*DeepAR

参数
h: int,预测范围。
input_size: int,截断训练反向传播的最大序列长度。默认 -1 使用 3 * 预测范围
lstm_n_layers: int=2,LSTM 层数。
lstm_hidden_size: int=128,LSTM 隐藏层大小。
lstm_dropout: float=0.1,LSTM dropout。
decoder_hidden_layers: int=0,解码器 MLP 隐藏层数。默认:0 表示线性层。
decoder_hidden_size: int=0,解码器 MLP 隐藏层大小。默认:0 表示线性层。
trajectory_samples: int=100,推理过程中的蒙特卡洛轨迹数量。
stat_exog_list: str list,静态外生变量列。
hist_exog_list: str list,历史外生变量列。
futr_exog_list: str list,未来外生变量列。
exclude_insample_y: bool=False,如果为 True,模型将跳过自回归特征 y[t-input_size:t]。
loss: PyTorch 模块,从 损失函数集合 实例化训练损失类。
valid_loss: PyTorch 模块=loss,从 损失函数集合 实例化验证损失类。
max_steps: int=1000,最大训练步数。
learning_rate: float=1e-3,学习率,范围为 (0, 1)。
num_lr_decays: int=-1,学习率衰减次数,均匀分布在最大步数中。
early_stop_patience_steps: int=-1,早停前验证迭代次数。
val_check_steps: int=100,每次验证损失检查之间的训练步数。
batch_size: int=32,每个批次中不同序列的数量。
valid_batch_size: int=None,每个验证和测试批次中不同序列的数量,如果为 None 则使用 batch_size。
windows_batch_size: int=1024,每个训练批次中采样的窗口数量,默认使用全部。
inference_windows_batch_size: int=-1,每个推理批次中采样的窗口数量,-1 使用全部。
start_padding_enabled: bool=False,如果为 True,模型将在时间序列开头填充零,填充量等于输入大小。
step_size: int=1,每个时间数据窗口之间的步长。
scaler_type: str=‘identity’,时间输入归一化的缩放器类型,详见 时间缩放器
random_seed: int,用于 pytorch 初始化器和 numpy 生成器的随机种子。
drop_last_loader: bool=False,如果为 True,TimeSeriesDataLoader 将丢弃最后一个非完整批次。
alias: str,可选,模型的自定义名称。
optimizer: ‘torch.optim.Optimizer’ 的子类,可选,用户指定的优化器而非默认选择 (Adam)。
optimizer_kwargs: dict,可选,用户指定的 optimizer 使用的参数列表。
lr_scheduler: ‘torch.optim.lr_scheduler.LRScheduler’ 的子类,可选,用户指定的 lr_scheduler 而非默认选择 (StepLR)。
lr_scheduler_kwargs: dict,可选,用户指定的 lr_scheduler 使用的参数列表。
dataloader_kwargs: dict,可选,由 TimeSeriesDataLoader 传递给 PyTorch Lightning dataloader 的参数列表。
**trainer_kwargs: int,继承自 PyTorch Lightning Trainer 的关键字 trainer 参数。

参考文献
- David Salinas, Valentin Flunkert, Jan Gasthaus, Tim Januschowski (2020). “DeepAR:使用自回归循环网络的概率预测”。International Journal of Forecasting.
- Alexander Alexandrov 等 (2020). “GluonTS:Python 中的概率和神经时间序列建模”。Journal of Machine Learning Research.
*


DeepAR.fit

 DeepAR.fit (dataset, val_size=0, test_size=0, random_seed=None,
             distributed_config=None)

*拟合。

fit 方法使用初始化参数(learning_ratewindows_batch_size 等)和初始化期间定义的 loss 函数来优化神经网络的权重。在 fit 方法中,我们使用继承了初始化时的 self.trainer_kwargs 的 PyTorch Lightning Trainer 来定制其输入,详见 PL 的 trainer 参数

该方法旨在与 SKLearn 类兼容,尤其是与 StatsForecast 库兼容。

默认情况下,model 不保存训练检查点以保护磁盘内存,要获取它们,请在 __init__ 中将 enable_checkpointing=True

参数
dataset: NeuralForecast 的 TimeSeriesDataset,详见 文档
val_size: int,时间交叉验证的验证集大小。
random_seed: int=None,用于 pytorch 初始化器和 numpy 生成器的随机种子,会覆盖 model.__init__ 中的设置。
test_size: int,时间交叉验证的测试集大小。
*


DeepAR.predict

 DeepAR.predict (dataset, test_size=None, step_size=1, random_seed=None,
                 quantiles=None, **data_module_kwargs)

*预测。

使用 PL 的 Trainer 执行 predict_step 进行神经网络预测。

参数
dataset: NeuralForecast 的 TimeSeriesDataset,详见 文档
test_size: int=None,时间交叉验证的测试集大小。
step_size: int=1,每个窗口之间的步长。
random_seed: int=None,用于 pytorch 初始化器和 numpy 生成器的随机种子,会覆盖 model.__init__ 中的设置。
quantiles: list of floats,可选 (default=None),要预测的目标分位数。
**data_module_kwargs: PL 的 TimeSeriesDataModule 参数,详见 文档。*

使用示例

import pandas as pd
import matplotlib.pyplot as plt

from neuralforecast import NeuralForecast
from neuralforecast.models import DeepAR
from neuralforecast.losses.pytorch import DistributionLoss, MQLoss
from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic
Y_train_df = AirPassengersPanel[AirPassengersPanel.ds<AirPassengersPanel['ds'].values[-12]] # 132 train
Y_test_df = AirPassengersPanel[AirPassengersPanel.ds>=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test

nf = NeuralForecast(
    models=[DeepAR(h=12,
                   input_size=24,
                   lstm_n_layers=1,
                   trajectory_samples=100,
                   loss=DistributionLoss(distribution='StudentT', level=[80, 90], return_params=True),
                   valid_loss=MQLoss(level=[80, 90]),
                   learning_rate=0.005,
                   stat_exog_list=['airline1'],
                   futr_exog_list=['trend'],
                   max_steps=100,
                   val_check_steps=10,
                   early_stop_patience_steps=-1,
                   scaler_type='standard',
                   enable_progress_bar=True,
                   ),
    ],
    freq='ME'
)
nf.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12)
Y_hat_df = nf.predict(futr_df=Y_test_df)

# Plot quantile predictions
Y_hat_df = Y_hat_df.reset_index(drop=False).drop(columns=['unique_id','ds'])
plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1)
plot_df = pd.concat([Y_train_df, plot_df])

plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1)
plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True')
plt.plot(plot_df['ds'], plot_df['DeepAR-median'], c='blue', label='median')
plt.fill_between(x=plot_df['ds'][-12:], 
                 y1=plot_df['DeepAR-lo-90'][-12:].values, 
                 y2=plot_df['DeepAR-hi-90'][-12:].values,
                 alpha=0.4, label='level 90')
plt.legend()
plt.grid()
plt.plot()