神经基扩展分析 (NBEATS) 是一种基于 MLP 的深度神经网络架构,具有前后残差连接。该网络有两种变体:(1) 在其可解释配置中,NBEATS 将信号按顺序投影到多项式和调和基上,以学习趋势和季节性成分;(2) 在其通用配置中,它用恒等基代替多项式和调和基,并增加网络深度。包含外生变量的神经基扩展分析 (NBEATSx) 结合了对预测时可用的外生时间变量的投影。

该方法在 M3、M4 和旅游竞赛数据集上展现了最先进的性能,相比于 M4 竞赛冠军 ESRNN,其准确率提高了 3%。

参考文献
-Boris N. Oreshkin, Dmitri Carpov, Nicolas Chapados, Yoshua Bengio (2019). “N-BEATS: Neural basis expansion analysis for interpretable time series forecasting”.


来源

NBEATS

 NBEATS (h, input_size, n_harmonics:int=2, n_polynomials:int=2,
         stack_types:list=['identity', 'trend', 'seasonality'],
         n_blocks:list=[1, 1, 1], mlp_units:list=[[512, 512], [512, 512],
         [512, 512]], dropout_prob_theta:float=0.0, activation:str='ReLU',
         shared_weights:bool=False, loss=MAE(), valid_loss=None,
         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:bool=False, alias:Optional[str]=None,
         optimizer=None, optimizer_kwargs=None, lr_scheduler=None,
         lr_scheduler_kwargs=None, dataloader_kwargs=None,
         **trainer_kwargs)

*NBEATS

时间序列神经基扩展分析 (NBEATS) 是一种简单而有效的架构,它由带有双重残差连接的深度 MLP 堆栈构建而成。根据其使用的块,它具有通用和可解释的架构。对于数据稀缺的场景,推荐使用其可解释架构,因为它通过投影到非常适合大多数预测任务的调和和趋势基上,来对其预测进行正则化。

参数
h: int, 预测范围。
input_size: int, 考虑的自回归输入(滞后),y=[1,2,3,4] input_size=2 -> lags=[1,2]。
n_harmonics: int, 季节性堆栈类型的调和项数量。请注意,len(n_harmonics) = len(stack_types)。请注意,仅在使用季节性堆栈时才会使用此参数。
n_polynomials: int, 趋势堆栈的多项式次数。请注意,len(n_polynomials) = len(stack_types)。请注意,仅在使用趋势堆栈时才会使用此参数。
stack_types: List[str], 堆栈类型列表。取值范围 [‘seasonality’, ‘trend’, ‘identity’]。
n_blocks: List[int], 每个堆栈的块数量。请注意,len(n_blocks) = len(stack_types)。
mlp_units: List[List[int]], 每种堆栈类型的隐藏层结构。每个内部列表应包含每个隐藏层的单元数量。请注意,len(隐藏层数量) = len(stack_types)。
dropout_prob_theta: float, (0, 1) 之间的浮点数。N-BEATS 基的 Dropout。
activation: str, 激活函数,取值范围 [‘ReLU’, ‘Softplus’, ‘Tanh’, ‘SELU’, ‘LeakyReLU’, ‘PReLU’, ‘Sigmoid’]。
shared_weights: bool, 如果为 True,则每个堆栈内的所有块将共享参数。
loss: PyTorch module, 从 损失函数集合 实例化的训练损失类。
valid_loss: PyTorch module=loss, 从 损失函数集合 实例化的验证损失类。
max_steps: int=1000, 最大训练步数。
learning_rate: float=1e-3, (0, 1) 之间的学习率。
num_lr_decays: int=3, 学习率衰减次数,在 max_steps 内均匀分布。
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,模型将在时间序列的开头填充 input size 个零。
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’ 的子类,可选,用户指定的学习率调度器,而非默认选项 (StepLR)。
lr_scheduler_kwargs: dict, 可选,用户指定的 lr_scheduler 使用的参数列表。
dataloader_kwargs: dict, 可选,由 TimeSeriesDataLoader 传递给 PyTorch Lightning dataloader 的参数列表。
**trainer_kwargs: int, 继承自 PyTorch Lighning trainer 的关键字 trainer 参数。

参考文献
-Boris N. Oreshkin, Dmitri Carpov, Nicolas Chapados, Yoshua Bengio (2019). “N-BEATS: Neural basis expansion analysis for interpretable time series forecasting”.*


NBEATS.fit

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

*Fit.

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

该方法设计为与类似 SKLearn 的类兼容,特别是与 StatsForecast 库兼容。

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

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


NBEATS.predict

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

*Predict.

使用 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, 可选 (默认为 None),要预测的目标分位数。
**data_module_kwargs: PL 的 TimeSeriesDataModule 参数,详见 文档。*

使用示例

import pandas as pd
import matplotlib.pyplot as plt

from neuralforecast import NeuralForecast
from neuralforecast.models import NBEATS
from neuralforecast.losses.pytorch import DistributionLoss
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

model = NBEATS(h=12, input_size=24,
               loss=DistributionLoss(distribution='Poisson', level=[80, 90]),
               stack_types = ['identity', 'trend', 'seasonality'],
               max_steps=100,
               val_check_steps=10,
               early_stop_patience_steps=2)

fcst = NeuralForecast(
    models=[model],
    freq='ME'
)
fcst.fit(df=Y_train_df, static_df=AirPassengersStatic, val_size=12)
forecasts = fcst.predict(futr_df=Y_test_df)

# Plot quantile predictions
Y_hat_df = forecasts.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['NBEATS-median'], c='blue', label='median')
plt.fill_between(x=plot_df['ds'][-12:], 
                 y1=plot_df['NBEATS-lo-90'][-12:].values, 
                 y2=plot_df['NBEATS-hi-90'][-12:].values,
                 alpha=0.4, label='level 90')
plt.grid()
plt.legend()
plt.plot()