本教程基于能源消耗预测场景,我们将对区域内能源消耗进行为期 4 天的预测。

在此,我们使用 PJM 每小时能源消耗数据集 的一个子集,重点关注区域内消耗,即电力在同一输电区域内产生和消耗。该数据集包含从 2023 年 10 月 1 日到 2024 年 9 月 30 日的每小时数据,涵盖五个代表性区域,以捕捉每小时能源需求模式。

在此实验中,我们展示了仅用几行代码,TimeGPT 就比最先进的深度学习模型(如 N-HiTS)带来了显著的改进

  • TimeGPT 的 MAE 比 N-HiTS 提高了 18.6%
  • TimeGPT 的 sMAPE 比 N-HiTS 提高了 31.1%
  • TimeGPT 在 4.3 秒内生成了预测结果,比使用 N-HiTS 进行训练和预测快了 90%

以下教程详细探讨了重现这些结果的所有步骤,以便您可以在自己的项目中应用 TimeGPT。

初始设置

首先,我们加载本次实验所需的包。

import time
import requests
import pandas as pd

from nixtla import NixtlaClient

from utilsforecast.losses import mae, smape
from utilsforecast.evaluation import evaluate

当然,我们需要一个 NixtlaClient 实例来使用 TimeGPT。

nixtla_client = NixtlaClient(
    # defaults to os.environ.get("NIXTLA_API_KEY")
    api_key = 'my_api_key_provided_by_nixtla'
)

👍 使用 Azure AI 端点

要使用 Azure AI 端点,请记住同时设置 base_url 参数

nixtla_client = NixtlaClient(base_url="you azure ai endpoint", api_key="your api_key")

读取数据

在此,我们加载流入能源传输时间序列。

df = pd.read_csv('https://raw.githubusercontent.com/Nixtla/transfer-learning-time-series/refs/heads/main/datasets/pjm_in_zone.csv')
df['ds'] = pd.to_datetime(df['ds'])
df.groupby('unique_id').head(2)
unique_iddsy
0AP-AP2023-10-01 04:00:00+00:004042.513
1AP-AP2023-10-01 05:00:00+00:003850.067
8784DOM-DOM2023-10-01 04:00:00+00:0010732.435
8785DOM-DOM2023-10-01 05:00:00+00:0010314.211
17568JC-JC2023-10-01 04:00:00+00:001825.101
17569JC-JC2023-10-01 05:00:00+00:001729.590
26352PN-PN2023-10-01 04:00:00+00:001454.666
26353PN-PN2023-10-01 05:00:00+00:001416.688
35136RTO-RTO2023-10-01 04:00:00+00:0069139.393
35137RTO-RTO2023-10-01 05:00:00+00:0066207.416

让我们绘制我们的时间序列图,看看它是什么样子。

nixtla_client.plot(
    df, 
    max_insample_length=365, 
)

我们可以看到所有时间序列中都有明显的季节性模式。看看 TimeGPT 如何处理这类数据将很有趣。

使用 TimeGPT 进行预测

拆分数据

第一步是拆分我们的数据。在此,我们定义一个输入 DataFrame 以提供给模型。我们还为测试集预留了最后 96 个时间步长,以便我们可以根据实际值评估 TimeGPT 的性能。

对于这种情况,我们使用 96 个时间步长的预测范围,这代表四天,我们使用 362 天的输入序列,即 8688 个时间步长。

test_df = df.groupby('unique_id').tail(96)                                                             # 96 = 4 days (96 *  1 day/24h )

input_df = df.groupby('unique_id').apply(lambda group: group.iloc[-1104:-96]).reset_index(drop=True)   # 1008 = 42 days (1008 * 1 day/24h)

预测

然后,我们只需调用 forecast 方法。在此,我们使用微调,并将平均绝对误差 (MAE) 指定为微调损失。此外,我们使用 timegpt-1-long-horizon,因为我们正在预测未来两天,并且季节性周期是一天。

start = time.time()

fcst_df = nixtla_client.forecast(
    df=input_df,
    h=96,                            
    level=[90],                        # Generate a 90% confidence interval
    finetune_steps=10,                 # Specify the number of steps for fine-tuning
    finetune_loss='mae',               # Use the MAE as the loss function for fine-tuning
    model='timegpt-1-long-horizon',    # Use the model for long-horizon forecasting
    time_col='ds',
    target_col='y',
    id_col='unique_id'
)

end = time.time()

timegpt_duration = end - start

print(f"Time (TimeGPT): {timegpt_duration}")

📘 Azure AI 中可用的模型

如果您正在使用 Azure AI 端点,请务必设置 model="azureai"

nixtla_client.forecast(..., model="azureai")

对于公共 API,我们支持两种模型:timegpt-1timegpt-1-long-horizon

默认情况下,使用 timegpt-1。请参阅 本教程,了解如何以及何时使用 timegpt-1-long-horizon

TimeGPT 在 4.3 秒内完成!我们现在可以绘制预测结果与测试集实际值对比图。

nixtla_client.plot(test_df, fcst_df, models=['TimeGPT'], level=[90], time_col='ds', target_col='y')

评估

现在我们有了预测结果,让我们评估一下模型的性能。

fcst_df['ds'] = pd.to_datetime(fcst_df['ds'])

test_df = pd.merge(test_df, fcst_df, 'left', ['unique_id', 'ds'])
evaluation = evaluate(
    test_df,
    metrics=[mae, smape],
    models=["TimeGPT"],
    target_col="y",
    id_col='unique_id'
)

average_metrics = evaluation.groupby('metric')['TimeGPT'].mean()
average_metrics
metric
mae      882.693979
smape      0.019974
Name: TimeGPT, dtype: float64

我们可以看到 TimeGPT 的 MAE 为 882.6,sMAPE 为 2%。

太好了!现在,让我们看看数据特定模型是否能做得更好。

使用 N-HiTS 进行预测

在此,我们使用 N-HiTS 模型,因为它训练速度非常快,并且在长序列预测任务上表现良好。要重现这些结果,请确保安装库 neuralforecast

from neuralforecast.core import NeuralForecast
from neuralforecast.models import NHITS

定义训练集

训练集与 TimeGPT 的输入 DataFrame 不同,因为我们需要更多数据来训练数据特定模型。

请注意,数据集非常大,因此我们使用训练集的最后 362 天数据来拟合我们的模型。

train_df = df.groupby('unique_id').apply(lambda group: group.iloc[:-96]).reset_index(drop=True)

使用 N-HiTS 进行预测

我们现在可以在训练集上拟合模型并进行预测。

horizon = 96

models = [NHITS(h=horizon, input_size = 5*horizon, scaler_type='robust', batch_size=16, valid_batch_size=8)]

nf = NeuralForecast(models=models, freq='H')

start = time.time()

nf.fit(df=train_df)
nhits_preds = nf.predict()

end = time.time()

nhits_duration = end - start

print(f"Time (N-HiTS): {nhits_duration}")

太好了!请注意,N-HiTS 花费了 44 秒来执行训练和预测过程。现在,让我们评估一下该模型的性能。

评估

preds_df = pd.merge(test_df, nhits_preds, 'left', ['unique_id', 'ds'])

evaluation = evaluate(
    preds_df,
    metrics=[mae, smape],
    models=["NHITS"],
    target_col="y",
    id_col='unique_id'
)


average_metrics = evaluation.groupby('metric')['NHITS'].mean()
print(average_metrics)

结论

TimeGPT 的 MAE 为 882.6,而 N-HiTS 的 MAE 为 1084.7,这意味着使用 TimeGPT 比我们的数据特定 N-HiTS 模型提高了 18.6%。TimeGPT 的 sMAPE 也提高了 31.1%。

此外,TimeGPT 花费 4.3 秒生成预测,而 N-HiTS 花费 44 秒拟合和预测。因此,在此场景下,TimeGPT 比使用 N-HiTS 快 90%