假期和特殊日期

!pip install -Uqq nixtla
from nixtla.utils import in_colab
IN_COLAB = in_colab()
if not IN_COLAB:
    from nixtla.utils import colab_badge
    from dotenv import load_dotenv

日历变量和特殊日期是预测应用中最常用的附加变量之一。它们为时间序列的当前状态提供了额外的上下文,特别是对于基于窗口的模型,例如 TimeGPT-1。这些变量通常包括添加有关每个观察的月份、星期、日期或小时的信息。例如,在高频小时数据中,提供当前的月份比输入窗口中可用的有限历史更能提供上下文,从而改善预测。

在本教程中,我们将展示如何使用 date_features 函数自动向数据集添加日历变量。

if not IN_COLAB:
    load_dotenv()    
    colab_badge('docs/tutorials/02_holidays')

1. 导入包

首先,我们导入所需的包并初始化 Nixtla 客户端。

import pandas as pd
from nixtla import NixtlaClient
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="你的Azure AI端点", api_key="你的API密钥")

if not IN_COLAB:
    nixtla_client = NixtlaClient()

2. 加载数据

我们将使用一个关于巧克力的谷歌趋势数据集,该数据集包含每月的数据。

df = pd.read_csv('https://raw.githubusercontent.com/Nixtla/transfer-learning-time-series/main/datasets/google_trend_chocolate.csv')
df['month'] = pd.to_datetime(df['month']).dt.to_period('M').dt.to_timestamp('M')
df.head()
month chocolate
0 2004-01-31 35
1 2004-02-29 45
2 2004-03-31 28
3 2004-04-30 30
4 2004-05-31 29

3. 带有假期和特殊日期的预测

考虑到日历变量的广泛使用,我们在预测方法中添加了一个自动创建常见日历变量的预处理步骤。让我们创建一个包含即将到来的美国假期的未来数据框。

# 创建包含外生特征的未来数据框

start_date = '2024-05'
dates = pd.date_range(start=start_date, periods=14, freq='M')

dates = dates.to_period('M').to_timestamp('M')

future_df = pd.DataFrame(dates, columns=['month'])
from nixtla.date_features import CountryHolidays

us_holidays = CountryHolidays(countries=['US'])
dates = pd.date_range(start=future_df.iloc[0]['month'], end=future_df.iloc[-1]['month'], freq='D')
holidays_df = us_holidays(dates)
monthly_holidays = holidays_df.resample('M').max()

monthly_holidays = monthly_holidays.reset_index(names='month')

future_df = future_df.merge(monthly_holidays)

future_df.head()
month US_New Year's Day US_Memorial Day US_Juneteenth National Independence Day US_Independence Day US_Labor Day US_Veterans Day US_Thanksgiving US_Christmas Day US_Martin Luther King Jr. Day US_Washington's Birthday US_Columbus Day
0 2024-05-31 0 0 0 0 0 0 0 0 0 0 0
1 2024-06-30 0 0 1 0 0 0 0 0 0 0 0
2 2024-07-31 0 0 0 1 0 0 0 0 0 0 0
3 2024-08-31 0 0 0 0 0 0 0 0 0 0 0
4 2024-09-30 0 0 0 0 1 0 0 0 0 0 0

我们对输入数据框执行相同的步骤。

# 将外源特征添加到输入数据框

dates = pd.date_range(start=df.iloc[0]['month'], end=df.iloc[-1]['month'], freq='D')
holidays_df = us_holidays(dates)
monthly_holidays = holidays_df.resample('M').max()

monthly_holidays = monthly_holidays.reset_index(names='month')

df = df.merge(monthly_holidays)

df.tail()
month chocolate US_New Year's Day US_New Year's Day (observed) US_Memorial Day US_Independence Day US_Independence Day (observed) US_Labor Day US_Veterans Day US_Thanksgiving US_Christmas Day US_Christmas Day (observed) US_Martin Luther King Jr. Day US_Washington's Birthday US_Columbus Day US_Veterans Day (observed) US_Juneteenth National Independence Day US_Juneteenth National Independence Day (observed)
239 2023-12-31 90 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
240 2024-01-31 64 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0
241 2024-02-29 66 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
242 2024-03-31 59 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
243 2024-04-30 51 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

太好了!现在,TimeGPT将把假期视为外生变量,未来的假期将帮助它进行预测。

fcst_df = nixtla_client.forecast(
    df=df,
    h=14,
    freq='M',
    time_col='month',
    target_col='chocolate',
    X_df=future_df
)
INFO:nixtla.nixtla_client:Validating inputs...
INFO:nixtla.nixtla_client:Preprocessing dataframes...
INFO:nixtla.nixtla_client:Inferred freq: M
WARNING:nixtla.nixtla_client:The specified horizon "h" exceeds the model horizon. This may lead to less accurate forecasts. Please consider using a smaller horizon.
INFO:nixtla.nixtla_client:Using the following exogenous variables: US_New Year's Day, US_Memorial Day, US_Juneteenth National Independence Day, US_Independence Day, US_Labor Day, US_Veterans Day, US_Thanksgiving, US_Christmas Day, US_Martin Luther King Jr. Day, US_Washington's Birthday, US_Columbus Day
INFO:nixtla.nixtla_client:Calling Forecast Endpoint...

📘 Azure AI 中可用的模型

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

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

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

默认情况下,使用 timegpt-1。有关如何以及何时使用 timegpt-1-long-horizon 的信息,请参阅 本教程

nixtla_client.plot(
    df, 
    fcst_df, 
    time_col='month',
    target_col='chocolate',
)

我们可以绘制每个节日的权重,以查看哪些节日在预测对巧克力的兴趣方面更为重要。

nixtla_client.weights_x.plot.barh(x='features', y='weights', figsize=(10, 10))

以下是 date_features 参数如何工作的详细说明:

  • date_features(布尔值、字符串列表或可调用对象):此参数指定要考虑的日期属性。
    • 如果设置为 True,模型将自动添加与给定数据框(df)的频率相关的最常见日期特征。对于日频率,这可能包括周几、月份和年份等特征。
    • 如果提供一个字符串列表,则将考虑这些特定的日期属性。例如,date_features=['weekday', 'month'] 将仅添加周几和月份作为特征。
    • 如果提供一个可调用对象,它应该是一个接受日期作为输入并返回所需特征的函数。这为计算自定义日期特征提供了灵活性。
  • date_features_to_one_hot(布尔值或字符串列表):在确定了日期特征之后,可能希望对其进行独热编码,特别是当它们具有分类性质时(例如周几)。独热编码将这些分类特征转换为二进制矩阵,使其更适合许多机器学习算法。
    • 如果 date_features=True,则默认情况下,所有计算出的日期特征将进行独热编码。
    • 如果提供一个字符串列表,则只有那些特定的日期特征将进行独热编码。

通过利用 date_featuresdate_features_to_one_hot 参数,可以有效地将日期属性的时间效应纳入到预测模型中,从而潜在地提高其准确性和可解释性。

Give us a ⭐ on Github