!pip install -Uqq nixtla datasetsforecast utilsforecast长期预测
from nixtla.utils import in_colabIN_COLAB = in_colab()if not IN_COLAB:
from nixtla.utils import colab_badge
from dotenv import load_dotenv长时间预测是指对未来较远的预测,通常超过两个季节周期。然而,“长时间”的确切定义可能会根据数据的频率而有所不同。例如,当处理小时数据时,三天后的预测被视为长时间预测,因为它涵盖了72个时间戳(计算为3天 × 24小时/天)。在每月数据的情况下,超过两年的时间段通常会被归类为长时间预测。同样,对于每日数据,跨越超过两周的预测则属于长时间预测类别。
当然,进行长时间预测会面临一些挑战。预测的时间范围越长,预测的不确定性就越大。长时间内可能会出现一些在预测时未预见的未知因素。
为了解决这些挑战,请在设置中指定 model='timegpt-1-long-horizon',以使用 TimeGPT 专门针对长时间预测的模型。
有关详细的逐步指南,请查看关于长时间预测的教程。
1. 导入包
首先,我们安装并导入所需的包,并初始化 Nixtla 客户端。
from nixtla import NixtlaClient
from datasetsforecast.long_horizon import LongHorizon
from utilsforecast.losses import maenixtla_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="你的 Azure AI 终端", api_key="你的 api_key")
if not IN_COLAB:
nixtla_client = NixtlaClient()2. 加载数据
让我们加载ETTh1数据集。这个数据集是用于评估模型在长时间预测能力方面的广泛使用的数据集。
ETTh1数据集监测了中国一个省份地区的电力变压器,包括油温和负载的变化(例如高有用负载和高无用负载),时间范围从2016年7月到2018年7月,数据频率为每小时。
对于本教程,我们只考虑油温随时间的变化。
Y_df, *_ = LongHorizon.load(directory='./', group='ETTh1')
Y_df.head()100%|██████████| 314M/314M [00:14<00:00, 21.3MiB/s]
INFO:datasetsforecast.utils:Successfully downloaded datasets.zip, 314116557, bytes.
INFO:datasetsforecast.utils:Decompressing zip file...
INFO:datasetsforecast.utils:Successfully decompressed longhorizon\datasets\datasets.zip
| unique_id | ds | y | |
|---|---|---|---|
| 0 | OT | 2016-07-01 00:00:00 | 1.460552 |
| 1 | OT | 2016-07-01 01:00:00 | 1.161527 |
| 2 | OT | 2016-07-01 02:00:00 | 1.161527 |
| 3 | OT | 2016-07-01 03:00:00 | 0.862611 |
| 4 | OT | 2016-07-01 04:00:00 | 0.525227 |
对于这个小实验,我们将时间范围设置为96个时间步(未来4天),并将以42天的序列输入给TimeGPT。
if not IN_COLAB:
Y_df = pd.read_parquet("../../assets/long_horizon_example_Y_df.parquet")test = Y_df[-96:] # 96 = 4天 × 24小时/天
input_seq = Y_df[-1104:-96] # 获取一个包含1008个观测值的序列(1008 = 42天 * 每24小时)3. 长期预测
现在,我们准备使用TimeGPT进行长时段预测。在这里,我们需要将model参数设置为"timegpt-1-long-horizon"。这是TimeGPT中专门处理此类任务的模型。
fcst_df = nixtla_client.forecast(
df=input_seq,
h=96,
level=[90],
finetune_steps=10,
finetune_loss='mae',
model='timegpt-1-long-horizon',
time_col='ds',
target_col='y'
)INFO:nixtla.nixtla_client:Validating inputs...
INFO:nixtla.nixtla_client:Preprocessing dataframes...
INFO:nixtla.nixtla_client:Inferred freq: H
INFO:nixtla.nixtla_client:Calling Forecast Endpoint...
📘 Azure AI 中可用的模型
如果您正在使用 Azure AI 端点,请确保设置
model="azureai":
nixtla_client.forecast(..., model="azureai")
nixtla_client.plot(Y_df[-168:], fcst_df, models=['TimeGPT'], level=[90], time_col='ds', target_col='y')
评估
现在让我们使用平均绝对误差(MAE)来评估TimeGPT的性能。
test = test.copy()
test.loc[:, 'TimeGPT'] = fcst_df['TimeGPT'].valuesevaluation = mae(test, models=['TimeGPT'], id_col='unique_id', target_col='y')
print(evaluation) unique_id TimeGPT
0 OT 0.145393
在这里,TimeGPT 达到的平均绝对误差(MAE)为 0.146。
Give us a ⭐ on Github