Skip to main content

What is Cross-validation?

Time series cross-validation is essential for validating machine learning models and ensuring accurate forecasts. Unlike traditional k-fold cross-validation, time series validation requires specialized rolling-window techniques that respect temporal order. This comprehensive tutorial shows you how to perform cross-validation in Python using TimeGPT, including prediction intervals, exogenous variables, and model performance evaluation. One of the primary challenges in time series forecasting is the inherent uncertainty and variability over time, making it crucial to validate the accuracy and reliability of the models employed. Cross-validation, a robust model validation technique, is particularly adapted for this task, as it provides insights into the expected performance of a model on unseen data, ensuring the forecasts are reliable and resilient before being deployed in real-world scenarios. TimeGPT incorporates the cross_validation method, designed to streamline the validation process for time series forecasting models. This functionality enables practitioners to rigorously test their forecasting models against historical data, with support for prediction intervals and exogenous variables. This tutorial will guide you through the nuanced process of conducting cross-validation within the NixtlaClient class, ensuring your time series forecasting models are not just well-constructed, but also validated for trustworthiness and precision.

Why Use Cross-Validation for Time Series?

Cross-validation provides several critical benefits for time series forecasting:
  • Prevent overfitting: Test model performance across multiple time periods
  • Validate generalization: Ensure forecasts work on unseen data
  • Quantify uncertainty: Generate prediction intervals for risk assessment
  • Compare models: Evaluate different forecasting approaches systematically
  • Optimize hyperparameters: Fine-tune model parameters with confidence

How to Perform Cross-validation with TimeGPT

Quick Summary: Learn time series cross-validation with TimeGPT in Python. This tutorial covers rolling-window validation, prediction intervals, model performance metrics, and advanced techniques with real-world examples using the Peyton Manning dataset.
Open In Colab

Step 1: Import Packages and Initialize NixtlaClient

First, we install and import the required packages and initialize the Nixtla client. We start off by initializing an instance of NixtlaClient.
import pandas as pd
from nixtla import NixtlaClient
from IPython.display import display

# Initialize TimeGPT client for cross-validation
nixtla_client = NixtlaClient(
    api_key='my_api_key_provided_by_nixtla'
)

Step 2: Load Example Data

Use the Peyton Manning dataset as an example. The dataset can be loaded directly from Nixtla’s S3 bucket:
pm_df = pd.read_csv(
    'https://datasets-nixtla.s3.amazonaws.com/peyton-manning.csv'
)
If you are using your own data, ensure your data is properly formatted: you must have a time column (e.g., ds), a target column (e.g., y), and, if necessary, an identifier column (e.g., unique_id) for multiple time series.

Step 3: Implement Rolling-Window Cross-Validation

The cross_validation method within the TimeGPT class is an advanced functionality crafted to perform systematic validation on time series forecasting models. This method necessitates a dataframe comprising time-ordered data and employs a rolling-window scheme to meticulously evaluate the model’s performance across different time periods, thereby ensuring the model’s reliability and stability over time. The animation below shows how TimeGPT performs cross-validation.
Rolling-window cross-validation

Rolling-window cross-validation conceptually splits your dataset into multiple training and validation sets over time.

Key parameters include:
  • freq: Frequency of your data (e.g., 'D' for daily). If not specified, it will be inferred.
  • id_col, time_col, target_col: Columns representing series ID, timestamps, and target values.
  • n_windows: Number of separate validation windows.
  • step_size: Step size between each validation window.
  • h: Forecast horizon (e.g., the number of days ahead to predict).
In execution, cross_validation assesses the model’s forecasting accuracy in each window, providing a robust view of the model’s performance variability over time and potential overfitting. This detailed evaluation ensures the forecasts generated are not only accurate but also consistent across diverse temporal contexts.
Key Concepts: Rolling-window cross-validation splits your dataset into multiple training and testing sets over time. Each window moves forward chronologically, training on historical data and validating on future periods. This approach mimics real-world forecasting scenarios where you predict forward in time.
Use cross_validation on the Peyton Manning dataset:
# Perform cross-validation with 5 windows and 7-day forecast horizon
timegpt_cv_df = nixtla_client.cross_validation(
    pm_df,
    h=7,  # Forecast 7 days ahead
    n_windows=5,  # Test across 5 different time periods
    freq='D'  # Daily frequency
)
timegpt_cv_df.head()
The logs below indicate successful cross-validation calls and data preprocessing.
INFO:nixtla.nixtla_client:Validating inputs...
INFO:nixtla.nixtla_client:Querying model metadata...
INFO:nixtla.nixtla_client:Preprocessing dataframes...
INFO:nixtla.nixtla_client:Restricting input...
INFO:nixtla.nixtla_client:Calling Cross Validation Endpoint...
Cross-validation output includes the forecasted values (TimeGPT) aligned with historical values (y).
unique_iddscutoffyTimeGPT
02015-12-172015-12-167.5918627.939553
02015-12-182015-12-167.5288697.887512
02015-12-192015-12-167.1716577.766617
02015-12-202015-12-167.8913317.931502
02015-12-212015-12-168.3600718.312632

Step 4: Plot Cross-Validation Results

Visualize forecast performance for each cutoff period. Here’s an example plotting the last 100 rows of actual data along with cross-validation forecasts for each cutoff.
cutoffs = timegpt_cv_df['cutoff'].unique()

for cutoff in cutoffs:
    fig = nixtla_client.plot(
        pm_df.tail(100),
        timegpt_cv_df.query('cutoff == @cutoff').drop(columns=['cutoff', 'y']),
    )
    display(fig)
Cross-validation Example Cross-validation Example Cross-validation Example Cross-validation Example Cross-validation Example

An example visualization of predicted vs. actual values in the Peyton Manning dataset.

Step 5: Generate Prediction Intervals for Model Uncertainty

It is also possible to generate prediction intervals during cross-validation. To do so, we simply use the level argument.
timegpt_cv_df = nixtla_client.cross_validation(
    pm_df,
    h=7,
    n_windows=5,
    freq='D',
    level=[80, 90],
)
timegpt_cv_df.head()
unique_iddscutoffyTimeGPTTimeGPT-hi-80TimeGPT-hi-90TimeGPT-lo-80TimeGPT-lo-90
002015-12-172015-12-167.5918627.9395538.2014658.3149567.6776427.564151
102015-12-182015-12-167.5288697.8875128.1754148.2074707.5996097.567553
202015-12-192015-12-167.1716577.7666178.2673638.3866747.2658717.146560
302015-12-202015-12-167.8913317.9315028.2059298.3699837.6570757.493020
402015-12-212015-12-168.3600718.3126329.1848939.6257947.4403716.999469
Plot the prediction intervals for the cross-validation results.
cutoffs = timegpt_cv_df['cutoff'].unique()
for cutoff in cutoffs:
    fig = nixtla_client.plot(
        pm_df.tail(100), 
        timegpt_cv_df.query('cutoff == @cutoff').drop(columns=['cutoff', 'y']),
        level=[80, 90],
        models=['TimeGPT']
    )
    display(fig)
Cross-validation Example with Prediction Intervals Cross-validation Example with Prediction Intervals Cross-validation Example with Prediction Intervals Cross-validation Example with Prediction Intervals Cross-validation Example with Prediction Intervals

An example visualization of predicted vs. actual values in the Peyton Manning dataset with prediction intervals.

Step 6: Enhance Forecasts with Exogenous Variables

Time Features

It is possible to include exogenous variables when performing cross-validation. Here we use the date_features parameter to create labels for each month. These features are then used by the model to make predictions during cross-validation.
timegpt_cv_df = nixtla_client.cross_validation(
    pm_df,
    h=7,
    n_windows=5,
    freq='D',
    date_features=['month'],
)
timegpt_cv_df.head()
unique_iddscutoffyTimeGPTTimeGPT-hi-80TimeGPT-hi-90TimeGPT-lo-80TimeGPT-lo-90
002015-12-172015-12-167.5918628.4263208.7219968.8241018.1306448.028540
102015-12-182015-12-167.5288698.0499628.4520838.6586037.6478427.441321
202015-12-192015-12-167.1716577.5090987.9847888.1380177.0334096.880180
302015-12-202015-12-167.8913317.7395368.3069148.6413557.1721586.837718
402015-12-212015-12-168.3600718.0274718.7228289.1523067.3321136.902636
Plot the cross-validation results with the time features.
cutoffs = timegpt_cv_df['cutoff'].unique()
for cutoff in cutoffs:
    fig = nixtla_client.plot(
        pm_df.tail(100), 
        timegpt_cv_df.query('cutoff == @cutoff').drop(columns=['cutoff', 'y']),
        date_features=['month'],
        models=['TimeGPT']
    )
    display(fig)
Cross-validation Example with Time Features Cross-validation Example with Time Features Cross-validation Example with Time Features Cross-validation Example with Time Features Cross-validation Example with Time Features

An example visualization of predicted vs. actual values in the Peyton Manning dataset with time features.

Dynamic Features

Additionally you can pass dynamic exogenous variables to better inform TimeGPT about the data. You just simply have to add the exogenous regressors after the target column.
Y_df = pd.read_csv('https://raw.githubusercontent.com/Nixtla/transfer-learning-time-series/main/datasets/electricity.csv')
X_df = pd.read_csv('https://raw.githubusercontent.com/Nixtla/transfer-learning-time-series/main/datasets/exogenous-vars-electricity.csv')
df = Y_df.merge(X_df)
Now let’s cross validate TimeGPT considering this information
timegpt_cv_df_x = nixtla_client.cross_validation(
    df.groupby('unique_id').tail(100 * 48), 
    h=48, 
    n_windows=2,
    level=[80, 90]
)
cutoffs = timegpt_cv_df_x.query('unique_id == "BE"')['cutoff'].unique()
for cutoff in cutoffs:
    fig = nixtla_client.plot(
        df.query('unique_id == "BE"').tail(24 * 7), 
        timegpt_cv_df_x.query('cutoff == @cutoff & unique_id == "BE"').drop(columns=['cutoff', 'y']),
        models=['TimeGPT'],
        level=[80, 90],
    )
    display(fig)
Cross-validation Example with Dynamic Exogenous Variables Cross-validation Example with Dynamic Exogenous Variables

An example visualization of predicted vs. actual values in the electricity dataset with dynamic exogenous variables.

Step 7: Long-Horizon Forecasting with TimeGPT

Also, you can generate cross validation for different instances of TimeGPT using the model argument. Here we use the base model and the model for long-horizon forecasting.
timegpt_cv_df_x_long_horizon = nixtla_client.cross_validation(
    df.groupby('unique_id').tail(100 * 48), 
    h=48, 
    n_windows=2,
    level=[80, 90],
    model='timegpt-1-long-horizon',
)
timegpt_cv_df_x_long_horizon.columns = timegpt_cv_df_x_long_horizon.columns.str.replace('TimeGPT', 'TimeGPT-LongHorizon')
timegpt_cv_df_x_models = timegpt_cv_df_x_long_horizon.merge(timegpt_cv_df_x)
cutoffs = timegpt_cv_df_x_models.query('unique_id == "BE"')['cutoff'].unique()
for cutoff in cutoffs:
    fig = nixtla_client.plot(
        df.query('unique_id == "BE"').tail(24 * 7), 
        timegpt_cv_df_x_models.query('cutoff == @cutoff & unique_id == "BE"').drop(columns=['cutoff', 'y']),
        models=['TimeGPT', 'TimeGPT-LongHorizon'],
        level=[80, 90],
    )
    display(fig)
Cross-validation Example with Long Horizon Forecasting Cross-validation Example with Long Horizon Forecasting

An example visualization of predicted vs. actual values in the electricity dataset with dynamic exogenous variables and long horizon forecasting.

Frequently Asked Questions

What is time series cross-validation? Time series cross-validation is a model validation technique that uses rolling windows to evaluate forecasting accuracy while preserving temporal order, ensuring reliable predictions on unseen data. How is time series cross-validation different from k-fold cross-validation? Unlike k-fold cross-validation which randomly shuffles data, time series cross-validation maintains temporal order using techniques like walk-forward validation and expanding windows to prevent data leakage. What are the key parameters for cross-validation in TimeGPT? Key parameters include h (forecast horizon), n_windows (number of validation windows), step_size (window increment), and level (prediction interval confidence levels). How do you evaluate cross-validation results? Evaluate results by comparing forecasted values against actual values across multiple time windows, analyzing prediction intervals, and calculating metrics like MAE, RMSE, and MAPE.

Conclusion

You’ve mastered time series cross-validation with TimeGPT, including rolling-window validation, prediction intervals, exogenous variables, and long-horizon forecasting. These model validation techniques ensure your forecasts are accurate, reliable, and production-ready.

Next Steps in Model Validation

Ready to validate your forecasts at scale? Start your TimeGPT trial and implement robust cross-validation today.
I