Skip to main content

What Are Categorical Variables?

Categorical variables are external factors that take on a limited range of discrete values, grouping observations by categories. For example, “Sporting” or “Cultural” events in a dataset describing product demand. By capturing unique external conditions, categorical variables enhance the predictive power of your model and can reduce forecasting error. They are easy to incorporate by merging each time series data point with its corresponding categorical data. This tutorial demonstrates how to incorporate categorical (discrete) variables into TimeGPT forecasts.

How to Use Categorical Variables in TimeGPT

Open In Colab

Step 1: Import Packages and Initialize the Nixtla Client

Make sure you have the necessary libraries installed: pandas, nixtla, and datasetsforecast.
import pandas as pd
import os

from nixtla import NixtlaClient
from datasetsforecast.m5 import M5
from utilsforecast.losses import smape

# Initialize the Nixtla Client
nixtla_client = NixtlaClient(
    api_key='my_api_key_provided_by_nixtla'
)

Step 2: Load M5 Data

We use the M5 dataset — a collection of daily product sales demands across 10 US stores — to showcase how categorical variables can improve forecasts. Start by loading the M5 dataset and converting the date columns to datetime objects.
Y_df, X_df, _ = M5.load(directory=os.getcwd())

Y_df['ds'] = pd.to_datetime(Y_df['ds'])
X_df['ds'] = pd.to_datetime(X_df['ds'])

Y_df.head(10)
unique_iddsy
FOODS_1_001_CA_12011-01-293.0
FOODS_1_001_CA_12011-01-300.0
FOODS_1_001_CA_12011-01-310.0
FOODS_1_001_CA_12011-02-011.0
FOODS_1_001_CA_12011-02-024.0
FOODS_1_001_CA_12011-02-032.0
FOODS_1_001_CA_12011-02-040.0
FOODS_1_001_CA_12011-02-052.0
FOODS_1_001_CA_12011-02-060.0
FOODS_1_001_CA_12011-02-070.0
Extract the categorical columns from the X_df dataframe.
X_df = X_df[['unique_id', 'ds', 'event_type_1']]
X_df.head(10)
unique_iddsevent_type_1
FOODS_1_001_CA_12011-01-29nan
FOODS_1_001_CA_12011-01-30nan
FOODS_1_001_CA_12011-01-31nan
FOODS_1_001_CA_12011-02-01nan
FOODS_1_001_CA_12011-02-02nan
FOODS_1_001_CA_12011-02-03nan
FOODS_1_001_CA_12011-02-04nan
FOODS_1_001_CA_12011-02-05nan
FOODS_1_001_CA_12011-02-06Sporting
FOODS_1_001_CA_12011-02-07nan
Notice that there is a Sporting event on February 6, 2011, listed under event_type_1.

Step 3: Prepare Data for Forecasting

We’ll select a specific product to demonstrate how to incorporate categorical features into TimeGPT forecasts.

Select a High-Selling Product and Merge Data

Start by selecting a high-selling product and merging the data.
product = 'FOODS_3_090_CA_3'

Y_df_product = Y_df.query('unique_id == @product')
X_df_product = X_df.query('unique_id == @product')

df = Y_df_product.merge(X_df_product)
df.head(10)
unique_iddsyevent_type_1
FOODS_3_090_CA_32011-01-29108.0nan
FOODS_3_090_CA_32011-01-30132.0nan
FOODS_3_090_CA_32011-01-31102.0nan
FOODS_3_090_CA_32011-02-01120.0nan
FOODS_3_090_CA_32011-02-02106.0nan
FOODS_3_090_CA_32011-02-03123.0nan
FOODS_3_090_CA_32011-02-04279.0nan
FOODS_3_090_CA_32011-02-05175.0nan
FOODS_3_090_CA_32011-02-06186.0Sporting
FOODS_3_090_CA_32011-02-07120.0nan

Prepare Future External Variables

Select future external variables for Feb 1-7, 2016.
future_ex_vars_df = df.drop(columns=['y']).query("ds >= '2016-02-01' & ds <= '2016-02-07'")
Separate training data before Feb 1, 2016.
df_train = df.query("ds < '2016-02-01'")
df_train.tail(10)
unique_iddsyevent_type_1
FOODS_3_090_CA_32016-01-2294.0nan
FOODS_3_090_CA_32016-01-23144.0nan
FOODS_3_090_CA_32016-01-24146.0nan
FOODS_3_090_CA_32016-01-2587.0nan
FOODS_3_090_CA_32016-01-2673.0nan
FOODS_3_090_CA_32016-01-2762.0nan
FOODS_3_090_CA_32016-01-2864.0nan
FOODS_3_090_CA_32016-01-29102.0nan
FOODS_3_090_CA_32016-01-30113.0nan
FOODS_3_090_CA_32016-01-3198.0nan

Step 4: Forecast Product Demand

To evaluate the impact of categorical variables, we’ll forecast product demand with and without them.

Forecast Without Categorical Variables

timegpt_fcst_without_cat_vars_df = nixtla_client.forecast(
    df=df_train,
    h=7,
    level=[80, 90]
)

timegpt_fcst_without_cat_vars_df.head()
unique_iddsTimeGPTTimeGPT-hi-80TimeGPT-hi-90TimeGPT-lo-80TimeGPT-lo-90
FOODS_3_090_CA_32016-02-0173.30409095.88738098.25088050.72080248.357307
FOODS_3_090_CA_32016-02-0266.33552075.42966076.66370457.24137556.007330
FOODS_3_090_CA_32016-02-0365.88163086.63648087.50281045.12677844.260456
FOODS_3_090_CA_32016-02-0472.37186492.36269096.37861052.38103548.365116
FOODS_3_090_CA_32016-02-0595.141045111.439224114.11549078.84286576.166595
Visualize the forecast without categorical variables.
nixtla_client.plot(
    df[['unique_id', 'ds', 'y']].query("ds <= '2016-02-07'"),
    timegpt_fcst_without_cat_vars_df,
    max_insample_length=28,
)
Forecast with categorical variables TimeGPT already provides a reasonable forecast, but it seems to somewhat underforecast the peak on the 6th of February 2016 - the day before the Super Bowl.

Forecast With Categorical Variables

To forecast with categorical variables, simply provide the list of column names containing categorical features in the categorical_exog_list argument.
timegpt_fcst_with_cat_vars_df = nixtla_client.forecast(
    df=df_train,
    X_df=future_ex_vars_df,
    h=7,
    level=[80, 90],
    categorical_exog_list=["event_type_1"]
)

timegpt_fcst_with_cat_vars_df.head()
unique_iddsTimeGPTTimeGPT-hi-80TimeGPT-hi-90TimeGPT-lo-80TimeGPT-lo-90
FOODS_3_090_CA_32016-02-0173.839455100.905910104.4415146.77300643.237396
FOODS_3_090_CA_32016-02-0266.54875075.29497076.6282257.80254056.469284
FOODS_3_090_CA_32016-02-0366.69443587.77795488.6392245.61091244.749650
FOODS_3_090_CA_32016-02-0474.24953094.81328698.8847353.68577049.614326
FOODS_3_090_CA_32016-02-0596.052414112.402090115.2234179.70273676.881420
Visualize the forecast with categorical variables.
# Visualize the forecast with categorical variables
nixtla_client.plot(
    df[['unique_id', 'ds', 'y']].query("ds <= '2016-02-07'"),
    timegpt_fcst_with_cat_vars_df,
    max_insample_length=28,
)
Forecast with categorical variables

5. Evaluate Forecast Accuracy

Finally, we calculate the Symmetric Mean Absolute Percentage Error (sMAPE) for the forecasts with and without categorical variables.
# Create target dataframe
df_target = df[['unique_id', 'ds', 'y']].query("ds >= '2016-02-01' & ds <= '2016-02-07'")

# Rename forecast columns
timegpt_fcst_without_cat_vars_df = timegpt_fcst_without_cat_vars_df.rename(columns={'TimeGPT': 'TimeGPT-without-cat-vars'})
timegpt_fcst_with_cat_vars_df = timegpt_fcst_with_cat_vars_df.rename(columns={'TimeGPT': 'TimeGPT-with-cat-vars'})

# Merge forecasts with target dataframe
df_target = df_target.merge(timegpt_fcst_without_cat_vars_df[['unique_id', 'ds', 'TimeGPT-without-cat-vars']])
df_target = df_target.merge(timegpt_fcst_with_cat_vars_df[['unique_id', 'ds', 'TimeGPT-with-cat-vars']])

# Compute errors
smape_errors = smape(df_target, ['TimeGPT-without-cat-vars', 'TimeGPT-with-cat-vars'])
unique_idTimeGPT-without-cat-varsTimeGPT-with-cat-vars
FOODS_3_090_CA_30.1092410.108666
Including categorical variables improves forecast accuracy as it achieves a lower sMAPE.

Conclusion

Categorical variables are powerful additions to TimeGPT forecasts, helping capture valuable external factors. By simply passing them to the categorical_exog_list parameter, you can significantly enhance predictive performance. Continue exploring more advanced techniques or different datasets to further improve your TimeGPT forecasting models.