本教程提供了一个示例,说明如何使用 core 类的 predict_insample 函数生成训练集和验证集的预测。在此示例中,我们将在 AirPassengers 数据集上训练 NHITS 模型,并展示如何在模型拟合后恢复样本内预测。

样本内预测:生成训练集和验证集预测的过程。

使用案例:* 调试:生成样本内预测对于调试很有用。例如,检查模型是否能够拟合训练集。* 训练收敛性:检查模型是否已收敛。* 异常检测:样本内预测可用于检测训练集中的异常行为(例如, 离群值)。(注意:如果模型过于灵活,它可能能够完美预测离群值)

您可以使用 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

3. 模型训练

首先,我们在 AirPassengers 数据上训练 NHITS 模型。我们将使用 core 类的 fit 方法来训练模型。

import logging
import pandas as pd

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

# Try different hyperparmeters to improve accuracy.
models = [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
                mlp_units = 3 * [[1024, 1024]],
               ) # Number of units in each block.
          ]
nf = NeuralForecast(models=models, freq='ME')
nf.fit(df=Y_df, val_size=horizon)
Seed set to 1
Sanity Checking: |                                                                                            …
Training: |                                                                                                   …
Validation: |                                                                                                 …

4. 样本内预测

使用 NeuralForecast.predict_insample 方法,您可以在模型拟合后获得训练集和验证集的预测。该函数将始终使用在 fitcross_validation 方法中最后一次用于训练的数据集。

通过 step_size 参数,您可以指定连续窗口之间的步长来生成预测。在此示例中,我们将设置 step_size=horizon 来生成不重叠的预测。

下图显示了如何根据模型的 step_size 参数和 h(预测范围)生成预测。在图中,我们将 step_size 设置为 2,h 设置为 4。

Y_hat_insample = nf.predict_insample(step_size=horizon)
Predicting: |                                                                                                 …

predict_insample 函数返回一个包含以下列的 pandas DataFrame:* unique_id:时间序列的唯一标识符。* ds:每行的预测日期戳。* cutoff:进行预测的日期戳。* y:目标变量的实际值。* model_name:模型的预测值。在此示例中,为 NHITS

Y_hat_insample.head()
unique_iddscutoffNHITSy
01.01949-01-311948-12-310.057849112.0
11.01949-02-281948-12-310.061673118.0
21.01949-03-311948-12-310.044137132.0
31.01949-04-301948-12-310.121791129.0
41.01949-05-311948-12-310.135417121.0

重要提示

该函数将从时间序列的第一个时间戳开始生成预测。对于这些初始时间戳,由于模型用于生成预测的输入信息非常有限,预测可能不准确。

5. 绘制预测结果

最后,我们绘制训练集和验证集的预测结果。

from utilsforecast.plotting import plot_series
plot_series(forecasts_df=Y_hat_insample.drop(columns='cutoff'))

参考资料