PatchTST 模型是一个高效的基于 Transformer 的多元时间序列预测模型。

它基于两个关键组成部分:- 将时间序列分割成窗口(patch),这些窗口作为 Transformer 的输入 token - 通道独立性,其中每个通道包含单个单变量时间序列。

参考文献
- Nie, Y., Nguyen, N. H., Sinthong, P., & Kalagnanam, J. (2022). “A Time Series is Worth 64 Words: Long-term Forecasting with Transformers”

1. 主干

辅助函数


source

get_activation_fn

 get_activation_fn (activation)

source

Transpose

 Transpose (*dims, contiguous=False)

Transpose

位置编码


source

positional_encoding

 positional_encoding (pe, learn_pe, q_len, hidden_size)

source

Coord1dPosEncoding

 Coord1dPosEncoding (q_len, exponential=False, normalize=True)

source

Coord2dPosEncoding

 Coord2dPosEncoding (q_len, hidden_size, exponential=False,
                     normalize=True, eps=0.001)

source

PositionalEncoding

 PositionalEncoding (q_len, hidden_size, normalize=True)

编码器


source

TSTEncoderLayer

 TSTEncoderLayer (q_len, hidden_size, n_heads, d_k=None, d_v=None,
                  linear_hidden_size=256, store_attn=False,
                  norm='BatchNorm', attn_dropout=0, dropout=0.0,
                  bias=True, activation='gelu', res_attention=False,
                  pre_norm=False)

TSTEncoderLayer


source

TSTEncoder

 TSTEncoder (q_len, hidden_size, n_heads, d_k=None, d_v=None,
             linear_hidden_size=None, norm='BatchNorm', attn_dropout=0.0,
             dropout=0.0, activation='gelu', res_attention=False,
             n_layers=1, pre_norm=False, store_attn=False)

TSTEncoder


source

TSTiEncoder

 TSTiEncoder (c_in, patch_num, patch_len, max_seq_len=1024, n_layers=3,
              hidden_size=128, n_heads=16, d_k=None, d_v=None,
              linear_hidden_size=256, norm='BatchNorm', attn_dropout=0.0,
              dropout=0.0, act='gelu', store_attn=False,
              key_padding_mask='auto', padding_var=None, attn_mask=None,
              res_attention=True, pre_norm=False, pe='zeros',
              learn_pe=True)

TSTiEncoder


source

Flatten_Head

 Flatten_Head (individual, n_vars, nf, h, c_out, head_dropout=0)

Flatten_Head


source

PatchTST_backbone

 PatchTST_backbone (c_in:int, c_out:int, input_size:int, h:int,
                    patch_len:int, stride:int,
                    max_seq_len:Optional[int]=1024, n_layers:int=3,
                    hidden_size=128, n_heads=16, d_k:Optional[int]=None,
                    d_v:Optional[int]=None, linear_hidden_size:int=256,
                    norm:str='BatchNorm', attn_dropout:float=0.0,
                    dropout:float=0.0, act:str='gelu',
                    key_padding_mask:str='auto',
                    padding_var:Optional[int]=None,
                    attn_mask:Optional[torch.Tensor]=None,
                    res_attention:bool=True, pre_norm:bool=False,
                    store_attn:bool=False, pe:str='zeros',
                    learn_pe:bool=True, fc_dropout:float=0.0,
                    head_dropout=0, padding_patch=None,
                    pretrain_head:bool=False, head_type='flatten',
                    individual=False, revin=True, affine=True,
                    subtract_last=False)

PatchTST_backbone

2. 模型


source

PatchTST

 PatchTST (h, input_size, stat_exog_list=None, hist_exog_list=None,
           futr_exog_list=None, exclude_insample_y=False,
           encoder_layers:int=3, n_heads:int=16, hidden_size:int=128,
           linear_hidden_size:int=256, dropout:float=0.2,
           fc_dropout:float=0.2, head_dropout:float=0.0,
           attn_dropout:float=0.0, patch_len:int=16, stride:int=8,
           revin:bool=True, revin_affine:bool=False,
           revin_subtract_last:bool=True, activation:str='gelu',
           res_attention:bool=True, batch_normalization:bool=False,
           learn_pos_embed: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:int=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)

*PatchTST

PatchTST 模型是一个高效的基于 Transformer 的多元时间序列预测模型。

它基于两个关键组成部分:- 将时间序列分割成窗口(patch),这些窗口作为 Transformer 的输入 token - 通道独立性,其中每个通道包含单个单变量时间序列。

参数
h: int, 预测范围。
input_size: int, 自回归输入大小, y=[1,2,3,4] input_size=2 -> y_[t-2:t]=[1,2]。
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]。
encoder_layers: int, 编码器层数。
n_heads: int=16, 多头注意力数量。
hidden_size: int=128, 嵌入和编码器的单元数。
linear_hidden_size: int=256, 线性层的单元数。
dropout: float=0.1, 残差连接的 dropout 率。
fc_dropout: float=0.1, 线性层的 dropout 率。
head_dropout: float=0.1, Flatten head 层的 dropout 率。
attn_dropout: float=0.1, 注意力层的 dropout 率。
patch_len: int=32, patch 长度。注意:patch_len = min(patch_len, input_size + stride)。
stride: int=16, patch 的步长。
revin: bool=True, 是否使用 RevIn 的布尔值。
revin_affine: bool=False, 是否在 RevIn 中使用仿射变换的布尔值。
revin_subtract_last: bool=False, 是否在 RevIn 中减去最后一个值的布尔值。
activation: str=‘ReLU’, 激活函数,可选 [‘gelu’,‘relu’]。
res_attention: bool=False, 是否使用残差注意力的布尔值。
batch_normalization: bool=False, 是否使用批量归一化的布尔值。
learn_pos_embed: bool=True, 是否学习位置嵌入的布尔值。
loss: PyTorch module, 从 losses collection 实例化的训练损失类。
valid_loss: PyTorch module=loss, 从 losses collection 实例化的验证损失类。
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, 每个 batch 中不同时间序列的数量。
valid_batch_size: int=None, 每个验证和测试 batch 中不同时间序列的数量,如果为 None,则使用 batch_size。
windows_batch_size: int=1024, 每个训练 batch 中采样的窗口数量,默认为全部。
inference_windows_batch_size: int=1024, 每个推理 batch 中采样的窗口数量。
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 将丢弃最后一个非完整 batch。
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 数据加载器的参数列表。
**trainer_kwargs: int, 继承自 PyTorch Lighning 的 trainer 的关键字 trainer 参数。

参考文献
-Nie, Y., Nguyen, N. H., Sinthong, P., & Kalagnanam, J. (2022). “A Time Series is Worth 64 Words: Long-term Forecasting with Transformers”*


PatchTST.fit

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

*拟合。

fit 方法使用初始化参数 (learning_rate, windows_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, 用于时间序列交叉验证的测试集大小。
*


PatchTST.predict

 PatchTST.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: float 列表,可选 (默认=None),要预测的目标分位数。
**data_module_kwargs: PL 的 TimeSeriesDataModule 参数,参见 文档。*

使用示例

import pandas as pd
import matplotlib.pyplot as plt

from neuralforecast import NeuralForecast
from neuralforecast.models import PatchTST
from neuralforecast.losses.pytorch import DistributionLoss
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 = PatchTST(h=12,
                 input_size=104,
                 patch_len=24,
                 stride=24,
                 revin=False,
                 hidden_size=16,
                 n_heads=4,
                 scaler_type='robust',
                 loss=DistributionLoss(distribution='StudentT', level=[80, 90]),
                 learning_rate=1e-3,
                 max_steps=500,
                 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['PatchTST-median'], c='blue', label='median')
    plt.fill_between(x=plot_df['ds'][-12:], 
                    y1=plot_df['PatchTST-lo-90'][-12:].values, 
                    y2=plot_df['PatchTST-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['PatchTST'], c='blue', label='Forecast')
    plt.legend()
    plt.grid()