Informer 模型解决了传统 Transformer 在长序列预测中面临的计算复杂性挑战。

该架构具有三个独特的特征:- ProbSparse 自注意力机制,时间复杂度为 O(Llog(L)),内存复杂度也为 O(Llog(L))。- 自注意力蒸馏过程,优先处理关键注意力并有效处理长输入序列。- MLP 多步解码器,可通过一次前向操作预测长时序序列,而非逐步预测。

Informer 模型采用三部分方法来定义其嵌入:- 它使用从卷积网络获得的编码自回归特征。- 它使用源自谐波函数的窗口相对位置嵌入。- 它使用从日历特征获得的绝对位置嵌入。

参考文献
- Haoyi Zhou, Shanghang Zhang, Jieqi Peng, Shuai Zhang, Jianxin Li, Hui Xiong, Wancai Zhang。《Informer:超越高效 Transformer 的长序列时间序列预测》

1. 辅助函数


源代码

ConvLayer

 ConvLayer (c_in)

ConvLayer


源代码

ProbAttention

 ProbAttention (mask_flag=True, factor=5, scale=None,
                attention_dropout=0.1, output_attention=False)

ProbAttention


源代码

ProbMask

 ProbMask (B, H, L, index, scores, device='cpu')

ProbMask

2. Informer


源代码

Informer

 Informer (h:int, input_size:int, futr_exog_list=None,
           hist_exog_list=None, stat_exog_list=None,
           exclude_insample_y=False,
           decoder_input_size_multiplier:float=0.5, hidden_size:int=128,
           dropout:float=0.05, factor:int=3, n_head:int=4,
           conv_hidden_size:int=32, activation:str='gelu',
           encoder_layers:int=2, decoder_layers:int=1, distil:bool=True,
           loss=MAE(), valid_loss=None, max_steps:int=5000,
           learning_rate:float=0.0001, num_lr_decays:int=-1,
           early_stop_patience_steps:int=-1, val_check_steps:int=100,
           batch_size:int=32, valid_batch_size:Optional[int]=None,
           windows_batch_size=1024, inference_windows_batch_size=1024,
           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)

*Informer

The Informer model tackles the vanilla Transformer computational complexity challenges for long-horizon forecasting. 
The architecture has three distinctive features:
1) A ProbSparse self-attention mechanism with an O time and memory complexity Llog(L).
2) A self-attention distilling process that prioritizes attention and efficiently handles long input sequences.
3) An MLP multi-step decoder that predicts long time-series sequences in a single forward operation rather than step-by-step.

Informer 模型采用三部分方法来定义其嵌入:1) 它使用从卷积网络获得的编码自回归特征。2) 它使用源自谐波函数的窗口相对位置嵌入。3) 它使用从日历特征获得的绝对位置嵌入。

参数
h: int,预测范围(forecast horizon)。
input_size: int,用于截断训练反向传播的最大序列长度。
futr_exog_list: str list,未来外部变量列。
hist_exog_list: str list,历史外部变量列。
stat_exog_list: str list,静态外部变量列。
exclude_insample_y: bool=False,如果为 True,模型会跳过自回归特征 y[t-input_size:t]。
decoder_input_size_multiplier: float = 0.5。
hidden_size: int=128,嵌入和编码器的单元数。
dropout: float (0, 1),Informer 架构中的 dropout 率。
factor: int=3,Probsparse 注意力因子。
n_head: int=4,控制多头注意力机制的头数。
conv_hidden_size: int=32,卷积编码器的通道数。
activation: str=GELU,激活函数,可选项为 [‘ReLU’, ‘Softplus’, ‘Tanh’, ‘SELU’, ‘LeakyReLU’, ‘PReLU’, ‘Sigmoid’, ‘GELU’]。
encoder_layers: int=2,TCN 编码器的层数。
decoder_layers: int=1,MLP 解码器的层数。
distil: bool = True,Informer 解码器是否使用瓶颈层。
loss: PyTorch module,实例化后的训练损失类,来自损失集合
valid_loss: PyTorch module=loss,实例化后的验证损失类,来自损失集合

max_steps: int=1000,最大训练步数。
learning_rate: float=1e-3,学习率,取值范围为 (0, 1)。
num_lr_decays: int=-1,学习率衰减次数,均匀分布在 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=1024,每个推理批次中采样的窗口数量。
start_padding_enabled: bool=False,如果为 True,模型将在时间序列开头(根据 input size)用零进行填充。
step_size: int=1,每个时间数据窗口之间的步长。
scaler_type: str=‘robust’,时间输入归一化的缩放器类型,参见 temporal scalers
random_seed: int=1,用于 pytorch 初始化器和 numpy 生成器的随机种子。
drop_last_loader: bool=False,如果为 True,TimeSeriesDataLoader 会丢弃最后一个不满的批次。
alias: str,可选,模型的自定义名称。
optimizer: Subclass of ‘torch.optim.Optimizer’,可选,用户指定的优化器,替代默认选择(Adam)。
optimizer_kwargs: dict,可选,用户指定的 optimizer 使用的参数列表。
lr_scheduler: Subclass of ‘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 的关键字训练器参数。

*References*<br/>
- [Haoyi Zhou, Shanghang Zhang, Jieqi Peng, Shuai Zhang, Jianxin Li, Hui Xiong, Wancai Zhang. "Informer: Beyond Efficient Transformer for Long Sequence Time-Series Forecasting"](https://arxiv.org/abs/2012.07436)<br/>*

Informer.fit

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

*训练(Fit)。

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

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

默认情况下,模型不保存训练检查点以保护磁盘内存,要保存检查点,请在 __init__ 中将 enable_checkpointing 更改为 True

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


Informer.predict

 Informer.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 Informer
from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic, augment_calendar_df

AirPassengersPanel, calendar_cols = augment_calendar_df(df=AirPassengersPanel, freq='M')

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 = Informer(h=12,
                 input_size=24,
                 hidden_size = 16,
                 conv_hidden_size = 32,
                 n_head = 2,
                 loss=MAE(),
                 futr_exog_list=calendar_cols,
                 scaler_type='robust',
                 learning_rate=1e-3,
                 max_steps=200,
                 val_check_steps=50,
                 early_stop_patience_steps=2)

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

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])

if model.loss.is_distribution_output:
    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['Informer-median'], c='blue', label='median')
    plt.fill_between(x=plot_df['ds'][-12:], 
                    y1=plot_df['Informer-lo-90'][-12:].values, 
                    y2=plot_df['Informer-hi-90'][-12:].values,
                    alpha=0.4, label='level 90')
    plt.grid()
    plt.legend()
    plt.plot()
else:
    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['Informer'], c='blue', label='Forecast')
    plt.legend()
    plt.grid()