Transformer 模型最初应用于自然语言处理领域,现已在时间序列预测领域得到越来越多的采用。这些模型的变革性力量在于其新颖的架构,该架构高度依赖于自注意力机制,这有助于模型专注于输入序列的不同部分进行预测,同时捕获数据中的长期依赖关系。在时间序列预测的背景下,Transformer 模型利用这种自注意力机制来识别时间序列中不同时期之间的相关信息,使其在预测复杂和噪声序列的未来值方面异常有效。

长周期预测涉及预测大量时间戳。由于预测的波动性计算复杂性,这是一项具有挑战性的任务。为了解决这个问题,最近的研究提出了各种基于 Transformer 的模型。

Neuralforecast 库包含了以下流行的最新模型的实现:Informer (Zhou, H. et al. 2021)、Autoformer (Wu et al. 2021)、FEDformer (Zhou, T. et al. 2022) 和 PatchTST (Nie et al. 2023)。

我们对所有这些模型的实现都是单变量的,这意味着只使用每个特征的自回归值进行预测。我们观察到,这些单变量模型比它们的多变量对应模型更准确、更快

在本 Notebook 中,我们将展示如何: * 加载学术文献中使用的 ETTm2 基准数据集。 * 训练模型 * 预测测试集

在本 Notebook 中取得的结果优于各自原始论文中自我报告的原始结果,且计算成本仅为一小部分。此外,所有模型都使用默认推荐参数进行训练,使用我们的自动模型进行自动超参数选择可以进一步改进结果。

您可以使用 Google Colab 的 GPU 运行这些实验。

1. 安装库

!pip install neuralforecast datasetsforecast

2. 加载 ETTm2 数据

LongHorizon 类将自动下载完整的 ETTm2 数据集并进行处理。

它返回三个 Dataframes:Y_df 包含目标变量的值,X_df 包含外部日历特征,S_df 包含每个时间序列的静态特征(ETTm2 没有)。对于本例,我们将只使用 Y_df

如果您想使用自己的数据,只需替换 Y_df。请确保使用长格式并与我们的数据集结构相似。

import pandas as pd

from datasetsforecast.long_horizon import LongHorizon
# Change this to your own data to try the model
Y_df, _, _ = LongHorizon.load(directory='./', group='ETTm2')
Y_df['ds'] = pd.to_datetime(Y_df['ds'])

n_time = len(Y_df.ds.unique())
val_size = int(.2 * n_time)
test_size = int(.2 * n_time)

Y_df.groupby('unique_id').head(2)
unique_iddsy
0HUFL2016-07-01 00:00:00-0.041413
1HUFL2016-07-01 00:15:00-0.185467
57600HULL2016-07-01 00:00:000.040104
57601HULL2016-07-01 00:15:00-0.214450
115200LUFL2016-07-01 00:00:000.695804
115201LUFL2016-07-01 00:15:000.434685
172800LULL2016-07-01 00:00:000.434430
172801LULL2016-07-01 00:15:000.428168
230400MUFL2016-07-01 00:00:00-0.599211
230401MUFL2016-07-01 00:15:00-0.658068
288000MULL2016-07-01 00:00:00-0.393536
288001MULL2016-07-01 00:15:00-0.659338
345600OT2016-07-01 00:00:001.018032
345601OT2016-07-01 00:15:000.980124

3. 训练模型

我们将使用 cross_validation 方法训练模型,该方法允许用户自动模拟多个历史预测(在测试集中)。

cross_validation 方法将使用验证集进行超参数选择和早期停止,然后生成测试集的预测结果。

首先,实例化 models 列表中的每个模型,指定 horizoninput_size 和训练迭代次数。

(注意:由于训练时间过长,FEDformer 模型被排除。)

from neuralforecast.core import NeuralForecast
from neuralforecast.models import Informer, Autoformer, FEDformer, PatchTST
INFO:torch.distributed.nn.jit.instantiator:Created a temporary directory at /tmp/tmpopb2vyyt
INFO:torch.distributed.nn.jit.instantiator:Writing /tmp/tmpopb2vyyt/_remote_module_non_scriptable.py
horizon = 96 # 24hrs = 4 * 15 min.
models = [Informer(h=horizon,                 # Forecasting horizon
                input_size=horizon,           # Input size
                max_steps=1000,               # Number of training iterations
                val_check_steps=100,          # Compute validation loss every 100 steps
                early_stop_patience_steps=3), # Stop training if validation loss does not improve
          Autoformer(h=horizon,
                input_size=horizon,
                max_steps=1000,
                val_check_steps=100,
                early_stop_patience_steps=3),
          PatchTST(h=horizon,
                input_size=horizon,
                max_steps=1000,
                val_check_steps=100,
                early_stop_patience_steps=3),
         ]
INFO:lightning_fabric.utilities.seed:Global seed set to 1
INFO:lightning_fabric.utilities.seed:Global seed set to 1
INFO:lightning_fabric.utilities.seed:Global seed set to 1

提示

查看我们的自动模型以进行自动超参数优化。

使用以下必需参数实例化一个 NeuralForecast 对象

  • models:模型列表。

  • freq:一个字符串,表示数据的频率。(参见 panda 可用的频率。)

其次,使用 cross_validation 方法,指定数据集 (Y_df)、验证集大小和测试集大小。

nf = NeuralForecast(
    models=models,
    freq='15min')

Y_hat_df = nf.cross_validation(df=Y_df,
                               val_size=val_size,
                               test_size=test_size,
                               n_windows=None)

cross_validation 方法将返回测试集上每个模型的预测结果。

Y_hat_df.head()
unique_idds截止点InformerAutoformerPatchTSTy
0HUFL2017-10-24 00:00:002017-10-23 23:45:00-1.055062-0.861487-0.860189-0.977673
1HUFL2017-10-24 00:15:002017-10-23 23:45:00-1.021247-0.873399-0.865730-0.865620
2HUFL2017-10-24 00:30:002017-10-23 23:45:00-1.057297-0.900345-0.944296-0.961624
3HUFL2017-10-24 00:45:002017-10-23 23:45:00-0.886652-0.867466-0.974849-1.049700
4HUFL2017-10-24 01:00:002017-10-23 23:45:00-1.000431-0.887454-1.008530-0.953600

4. 评估结果

接下来,我们绘制测试集上所有模型的 OT 变量的预测结果。

import matplotlib.pyplot as plt
Y_plot = Y_hat_df[Y_hat_df['unique_id']=='OT'] # OT dataset
cutoffs = Y_hat_df['cutoff'].unique()[::horizon]
Y_plot = Y_plot[Y_hat_df['cutoff'].isin(cutoffs)]

plt.figure(figsize=(20,5))
plt.plot(Y_plot['ds'], Y_plot['y'], label='True')
plt.plot(Y_plot['ds'], Y_plot['Informer'], label='Informer')
plt.plot(Y_plot['ds'], Y_plot['Autoformer'], label='Autoformer')
plt.plot(Y_plot['ds'], Y_plot['PatchTST'], label='PatchTST')
plt.xlabel('Datestamp')
plt.ylabel('OT')
plt.grid()
plt.legend()

最后,我们使用平均绝对误差 (MAE) 计算测试误差

MAE=1WindowsHorizonτyτy^τ\qquad MAE = \frac{1}{Windows * Horizon} \sum_{\tau} |y_{\tau} - \hat{y}_{\tau}| \qquad

from neuralforecast.losses.numpy import mae
mae_informer = mae(Y_hat_df['y'], Y_hat_df['Informer'])
mae_autoformer = mae(Y_hat_df['y'], Y_hat_df['Autoformer'])
mae_patchtst = mae(Y_hat_df['y'], Y_hat_df['PatchTST'])

print(f'Informer: {mae_informer:.3f}')
print(f'Autoformer: {mae_autoformer:.3f}')
print(f'PatchTST: {mae_patchtst:.3f}')
Informer: 0.339
Autoformer: 0.316
PatchTST: 0.251

作为参考,我们可以将其性能与各自论文中自我报告的性能进行比较。

预测期PatchTSTAutoFormerInformerARIMA
960.2560.3390.4530.301
1920.2960.3400.5630.345
3360.3290.3720.8870.386
7200.3850.4191.3880.445

后续步骤

我们提出了一种用于长周期预测的替代模型 NHITS,该模型基于 (Challu et al. 2023) 中的前馈网络。它实现了与 PatchTST 不相上下的性能,而计算成本仅为一小部分。NHITS 教程可在此处获取 here

参考文献

Zhou, H., Zhang, S., Peng, J., Zhang, S., Li, J., Xiong, H., & Zhang, W. (2021, May). Informer: Beyond efficient transformer for long sequence time-series forecasting. In Proceedings of the AAAI conference on artificial intelligence (Vol. 35, No. 12, pp. 11106-11115)

Wu, H., Xu, J., Wang, J., & Long, M. (2021). Autoformer: Decomposition transformers with auto-correlation for long-term series forecasting. Advances in Neural Information Processing Systems, 34, 22419-22430.

Zhou, T., Ma, Z., Wen, Q., Wang, X., Sun, L., & Jin, R. (2022, June). Fedformer: Frequency enhanced decomposed transformer for long-term series forecasting. In International Conference on Machine Learning (pp. 27268-27286). PMLR.

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

Cristian Challu, Kin G. Olivares, Boris N. Oreshkin, Federico Garza, Max Mergenthaler-Canseco, Artur Dubrawski (2021). NHITS: Neural Hierarchical Interpolation for Time Series Forecasting. Accepted at AAAI 2023.