1. 辅助函数

1.1 混合层

混合层由顺序的时间和特征多层感知机(MLP)组成。


源代码

带静态外部变量的混合层

 MixingLayerWithStaticExogenous (h, dropout, ff_dim, stat_input_size)

带静态外部变量的混合层


源代码

混合层

 MixingLayer (in_features, out_features, h, dropout, ff_dim)

混合层


源代码

特征混合

 FeatureMixing (in_features, out_features, h, dropout, ff_dim)

特征混合


源代码

时间混合

 TemporalMixing (num_features, h, dropout)

时间混合

1.2 可逆实例归一化

一种可逆的实例归一化层,基于此参考实现

2. 模型


源代码

TSMixerx

 TSMixerx (h, input_size, n_series, futr_exog_list=None,
           hist_exog_list=None, stat_exog_list=None,
           exclude_insample_y=False, n_block=2, ff_dim=64, dropout=0.0,
           revin=True, loss=MAE(), valid_loss=None, max_steps:int=1000,
           learning_rate:float=0.001, 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=32, inference_windows_batch_size=32,
           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)

*TSMixerx

时间序列外部变量混合器模型(TSMixerx)是一种基于 MLP 的多元时间序列预测模型,具有附加外部输入的处理能力。TSMixerx 通过使用堆叠的混合层重复组合时间和特征信息,共同学习时间序列的时间和截面表示。混合层由顺序的时间和特征多层感知机(MLP)组成。

参数
h: int, 预测范围。
input_size: int, 考虑的自回归输入(滞后),y=[1,2,3,4] input_size=2 -> lags=[1,2]。
n_series: int, 时间序列的数量。
futr_exog_list: str list, 未来外部变量列。
hist_exog_list: str list, 历史外部变量列。
stat_exog_list: str list, 静态外部变量列。
exclude_insample_y: bool=False, 如果为 True,则从模型中排除样本内 y 值。
n_block: int=2, 模型中的混合层数量。
ff_dim: int=64, 特征 MLP 中第二个前馈层的单元数量。
dropout: float=0.0, 介于 (0, 1) 之间的 dropout 率。
revin: bool=True, 如果为 True,则对 insample_y 使用逆实例归一化并将其应用于输出。

loss: PyTorch module, 从损失函数集合中实例化的训练损失类。
valid_loss: PyTorch module=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=32, 每个训练批次中采样的窗口数量。
inference_windows_batch_size: int=32, 每个推理批次中采样的窗口数量,-1 表示使用全部。
start_padding_enabled: bool=False, 如果为 True,模型将在时间序列的开头填充零,按输入大小进行。
step_size: int=1, 每个时间数据窗口之间的步长。
scaler_type: str=‘identity’, 用于时间输入归一化的缩放器类型,参见时间缩放器
random_seed: int=1, 用于 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 数据加载器的参数列表。
**trainer_kwargs: int, 继承自PyTorch Lighning 的 trainer 的关键字 trainer 参数。

参考文献
- Chen, Si-An, Chun-Liang Li, Nate Yoder, Sercan O. Arik 和 Tomas Pfister (2023). “TSMixer: An All-MLP Architecture for Time Series Forecasting.”*


TSMixerx.fit

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

*拟合。

fit 方法使用初始化参数(learning_rate, windows_batch_size, ...)和初始化时定义的 loss 函数来优化神经网络的权重。在 fit 方法中,我们使用 PyTorch Lightning Trainer,它继承了初始化的 self.trainer_kwargs,用于自定义其输入,参见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, 用于时间交叉验证的测试集大小。
*


TSMixerx.predict

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

# Unit tests for models
logging.getLogger("pytorch_lightning").setLevel(logging.ERROR)
logging.getLogger("lightning_fabric").setLevel(logging.ERROR)
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    check_model(TSMixerx, ["airpassengers"])

3. 使用示例

使用 predict 方法训练模型并预测未来值。

import pandas as pd
import matplotlib.pyplot as plt

from neuralforecast import NeuralForecast
from neuralforecast.models import TSMixerx
from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic
from neuralforecast.losses.pytorch import GMM

Y_train_df = AirPassengersPanel[AirPassengersPanel.ds<AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 132 train
Y_test_df = AirPassengersPanel[AirPassengersPanel.ds>=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test

model = TSMixerx(h=12,
                input_size=24,
                n_series=2,
                stat_exog_list=['airline1'],
                futr_exog_list=['trend'],
                n_block=4,
                ff_dim=4,
                revin=True,
                scaler_type='robust',
                max_steps=500,
                early_stop_patience_steps=-1,
                val_check_steps=5,
                learning_rate=1e-3,
                loss = GMM(n_components=10, weighted=True),
                batch_size=32
                )

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 predictions
fig, ax = plt.subplots(1, 1, figsize = (20, 7))
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['TSMixerx-median'], c='blue', label='median')
plt.fill_between(x=plot_df['ds'][-12:], 
                 y1=plot_df['TSMixerx-lo-90'][-12:].values,
                 y2=plot_df['TSMixerx-hi-90'][-12:].values,
                 alpha=0.4, label='level 90')
ax.set_title('AirPassengers Forecast', fontsize=22)
ax.set_ylabel('Monthly Passengers', fontsize=20)
ax.set_xlabel('Year', fontsize=20)
ax.legend(prop={'size': 15})
ax.grid()

使用 cross_validation 预测多个历史值。

fcst = NeuralForecast(models=[model], freq='M')
forecasts = fcst.cross_validation(df=AirPassengersPanel, static_df=AirPassengersStatic, n_windows=2, step_size=12)

# Plot predictions
fig, ax = plt.subplots(1, 1, figsize = (20, 7))
Y_hat_df = forecasts.loc['Airline1']
Y_df = AirPassengersPanel[AirPassengersPanel['unique_id']=='Airline1']

plt.plot(Y_df['ds'], Y_df['y'], c='black', label='True')
plt.plot(Y_hat_df['ds'], Y_hat_df['TSMixerx-median'], c='blue', label='Forecast')
ax.set_title('AirPassengers Forecast', fontsize=22)
ax.set_ylabel('Monthly Passengers', fontsize=20)
ax.set_xlabel('Year', fontsize=20)
ax.legend(prop={'size': 15})
ax.grid()