TimesNet 单变量模型解决了对多个周期内和周期间时间变化进行建模的挑战。

该架构具有以下独特特点:- 一个将输入序列映射到潜在空间的嵌入层。- 基于 FFT 找到的周期,将一维时间序列转换为二维张量。- 一个卷积 Inception 块,用于捕获不同尺度和周期之间的时间变化。

参考文献
- Haixu Wu and Tengge Hu and Yong Liu and Hang Zhou and Jianmin Wang and Mingsheng Long. TimesNet: Temporal 2D-Variation Modeling for General Time Series Analysis - 基于以下实现: https://github.com/thuml/Time-Series-Library (license: https://github.com/thuml/Time-Series-Library/blob/main/LICENSE)

1. 辅助函数


Inception_Block_V1

 Inception_Block_V1 (in_channels, out_channels, num_kernels=6,
                     init_weight=True)

Inception_Block_V1


TimesBlock

 TimesBlock (input_size, h, k, hidden_size, conv_hidden_size, num_kernels)

TimesBlock


FFT_for_Period

 FFT_for_Period (x, k=2)

2. TimesNet


TimesNet

 TimesNet (h:int, input_size:int, stat_exog_list=None,
           hist_exog_list=None, futr_exog_list=None,
           exclude_insample_y=False, hidden_size:int=64,
           dropout:float=0.1, conv_hidden_size:int=64, top_k:int=5,
           num_kernels:int=6, encoder_layers:int=2, loss=MAE(),
           valid_loss=None, max_steps:int=1000,
           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=64, inference_windows_batch_size=256,
           start_padding_enabled=False, step_size:int=1,
           scaler_type:str='standard', 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)

*TimesNet

TimesNet 单变量模型解决了对多个周期内和周期间时间变化进行建模的挑战。

参数
h : int, 预测范围。
input_size : int, 输入窗口长度(滞后)。
stat_exog_list : list of str, 可选 (默认=None), 静态外部变量列。
hist_exog_list : list of str, 可选 (默认=None), 历史外部变量列。
futr_exog_list : list of str, 可选 (默认=None), 未来外部变量列。
exclude_insample_y : bool (默认=False), 如果为 True,模型将跳过自回归特征 y[t-input_size:t]。
hidden_size : int (默认=64), 嵌入层和编码器的嵌入大小。
dropout : float, 范围 [0, 1) (默认=0.1), 嵌入层的 Dropout。
conv_hidden_size: int (默认=64), Inception 块的通道数。
top_k: int (默认=5), 周期数。
num_kernels: int (默认=6), Inception 块的核数。
encoder_layers : int, (默认=2), 编码器层数。
loss: PyTorch module (默认=MAE()), 从 损失函数集合中实例化的训练损失函数类。valid_loss: PyTorch module (默认=None, 使用 loss), 从 损失函数集合中实例化的验证损失函数类。
max_steps: int (默认=1000), 最大训练步数。
learning_rate : float (默认=1e-4), 学习率。
num_lr_decays: int (默认=-1), 学习率衰减次数,在 max_steps 中均匀分布。如果为 -1,则不执行学习率衰减。
early_stop_patience_steps : int (默认=-1), 早停前验证迭代次数。如果为 -1,则不执行早停。
val_check_steps : int (默认=100), 每次验证损失检查之间的训练步数。
batch_size : int (默认=32), 每个批次中不同序列的数量。
valid_batch_size : int (默认=None), 每个验证和测试批次中不同序列的数量,如果为 None,则使用 batch_size。
windows_batch_size : int (默认=64), 每个训练批次中采样的窗口数量。
inference_windows_batch_size : int (默认=256), 每个推理批次中采样的窗口数量。
start_padding_enabled : bool (默认=False), 如果为 True,模型将在时间序列开头填充 input size 数量的零。
step_size : int (默认=1), 每个时间数据窗口之间的步长。
scaler_type : str (默认=‘standard’), 时间输入归一化的缩放器类型,参见 时间缩放器
random_seed : int (默认=1), 用于 pytorch 初始化器和 numpy 生成器的随机种子。
drop_last_loader : bool (默认=False), 如果为 True,TimeSeriesDataLoader 将丢弃最后一个非完整批次。
alias : str, 可选 (默认=None), 模型的自定义名称。
optimizer: ‘torch.optim.Optimizer’ 的子类, 可选 (默认=None), 用户指定的优化器,而非默认选择 (Adam)。
optimizer_kwargs: dict, 可选 (默认=None), 用户指定的 optimizer 所使用的参数列表。
lr_scheduler: ‘torch.optim.lr_scheduler.LRScheduler’ 的子类, 可选, 用户指定的 lr_scheduler,而非默认选择 (StepLR)。
lr_scheduler_kwargs: dict, 可选, 用户指定的 lr_scheduler 所使用的参数列表。

dataloader_kwargs: dict, 可选 (默认=None), 由 TimeSeriesDataLoader 传递给 PyTorch Lightning dataloader 的参数列表。
**trainer_kwargs: 继承自 PyTorch Lighning 的 trainer 的关键字 trainer 参数*


TimesNet.fit

 TimesNet.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-like 类兼容,特别是与 StatsForecast 库兼容。

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

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


TimesNet.predict

 TimesNet.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 参数,参见 文档。*

使用示例

import pandas as pd
import matplotlib.pyplot as plt

from neuralforecast import NeuralForecast
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 = TimesNet(h=12,
                 input_size=24,
                 hidden_size = 16,
                 conv_hidden_size = 32,
                 loss=DistributionLoss(distribution='Normal', level=[80, 90]),
                 scaler_type='standard',
                 learning_rate=1e-3,
                 max_steps=100,
                 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['TimesNet-median'], c='blue', label='median')
    plt.fill_between(x=plot_df['ds'][-12:], 
                    y1=plot_df['TimesNet-lo-90'][-12:].values, 
                    y2=plot_df['TimesNet-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['TimesNet'], c='blue', label='Forecast')
    plt.legend()
    plt.grid()