本 notebook 提供了一个示例,展示了如何开始使用 NeuralForecast 库的主要功能。NeuralForecast 类允许用户轻松地与 NeuralForecast.models 中的 PyTorch 模型交互。在本例中,我们将使用经典的 LSTM 和最新的 NHITS 模型来预测 AirPassengers 数据。可用模型的完整列表可在此处找到

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

1. 安装 NeuralForecast

!pip install neuralforecast

2. 加载 AirPassengers 数据

core.NeuralForecast 类包含共享的 fitpredict 和其他方法,这些方法接受包含 ['unique_id', 'ds', 'y'] 列的 pandas DataFrame 作为输入,其中 unique_id 标识数据集中的各个时间序列,ds 是日期,y 是目标变量。

在本例中,数据集包含单个序列,但您可以轻松地将模型拟合到长格式的更大数据集。

from neuralforecast.utils import AirPassengersDF
Y_df = AirPassengersDF
Y_df.head()
unique_iddsy
01.01949-01-31112.0
11.01949-02-28118.0
21.01949-03-31132.0
31.01949-04-30129.0
41.01949-05-31121.0

重要提示

DataFrame 必须包含所有 ['unique_id', 'ds', 'y'] 列。确保 y 列没有缺失值或非数字值。

3. 模型训练

拟合模型

使用 NeuralForecast.fit 方法,您可以训练一组模型来适应您的数据集。您可以定义预测 horizon(本例中为 12),并修改模型的超参数。例如,对于 LSTM,我们更改了编码器和解码器的默认隐藏大小。

import logging

from neuralforecast import NeuralForecast
from neuralforecast.models import LSTM, NHITS, RNN
logging.getLogger('pytorch_lightning').setLevel(logging.ERROR)
horizon = 12

# Try different hyperparmeters to improve accuracy.
models = [LSTM(input_size=2 * horizon,
               h=horizon,                    # Forecast horizon
               max_steps=500,                # Number of steps to train
               scaler_type='standard',       # Type of scaler to normalize data
               encoder_hidden_size=64,       # Defines the size of the hidden state of the LSTM
               decoder_hidden_size=64,),     # Defines the number of hidden units of each layer of the MLP decoder
          NHITS(h=horizon,                   # Forecast horizon
                input_size=2 * horizon,      # Length of input sequence
                max_steps=100,               # Number of steps to train
                n_freq_downsample=[2, 1, 1]) # Downsampling factors for each stack output
          ]
nf = NeuralForecast(models=models, freq='ME')
nf.fit(df=Y_df)

提示

深度学习模型的性能对超参数的选择非常敏感。调整正确的超参数是获得最佳预测的重要步骤。这些模型的 Auto 版本,即 AutoLSTMAutoNHITS,已经自动执行超参数选择。

使用拟合模型进行预测

使用 NeuralForecast.predict 方法,您可以在训练数据 Y_df 之后获得 h 个预测值。

Y_hat_df = nf.predict()

NeuralForecast.predict 方法返回一个 DataFrame,其中包含每个 unique_idds 和模型的预测值。

Y_hat_df = Y_hat_df
Y_hat_df.head()
unique_iddsLSTMNHITS
01.01961-01-31445.602112447.531281
11.01961-02-28431.253510439.081024
21.01961-03-31456.301270481.924194
31.01961-04-30508.149750501.501343
41.01961-05-31524.903870514.664551

4. 绘制预测结果

最后,我们绘制了两个模型的预测结果与实际值进行对比。

from utilsforecast.plotting import plot_series
plot_series(Y_df, Y_hat_df)

提示

在本指南中,我们使用了简单的 LSTM 模型。更先进的模型,如 TSMixerTFTNHITS,在大多数情况下都比 LSTM 具有更高的准确性。可用模型的完整列表可在此处找到

参考文献