AutoGluon Time Series - Forecasting Quick Start#

Open In Colab Open In SageMaker Studio Lab

Via a simple fit() call, AutoGluon can train and tune

  • simple forecasting models (e.g., ARIMA, ETS, Theta),

  • powerful deep learning models (e.g., DeepAR, Temporal Fusion Transformer),

  • tree-based models (e.g., LightGBM),

  • an ensemble that combines predictions of other models

to produce multi-step ahead probabilistic forecasts for univariate time series data.

This tutorial demonstrates how to quickly start using AutoGluon to generate hourly forecasts for the M4 forecasting competition dataset.

Loading time series data as a TimeSeriesDataFrame#

First, we import some required modules

import pandas as pd
from autogluon.timeseries import TimeSeriesDataFrame, TimeSeriesPredictor

To use autogluon.timeseries, we will only need the following two classes:

  • TimeSeriesDataFrame stores a dataset consisting of multiple time series.

  • TimeSeriesPredictor takes care of fitting, tuning and selecting the best forecasting models, as well as generating new forecasts.

We load a subset of the M4 hourly dataset as a pandas.DataFrame

df = pd.read_csv("https://autogluon.s3.amazonaws.com/datasets/timeseries/m4_hourly_subset/train.csv")
df.head()
item_id timestamp target
0 H1 1750-01-01 00:00:00 605.0
1 H1 1750-01-01 01:00:00 586.0
2 H1 1750-01-01 02:00:00 586.0
3 H1 1750-01-01 03:00:00 559.0
4 H1 1750-01-01 04:00:00 511.0

AutoGluon expects time series data in long format. Each row of the data frame contains a single observation (timestep) of a single time series represented by

  • unique ID of the time series ("item_id") as int or str

  • timestamp of the observation ("timestamp") as a pandas.Timestamp or compatible format

  • numeric value of the time series ("target")

The raw dataset should always follow this format with at least three columns for unique ID, timestamp, and target value, but the names of these columns can be arbitrary. It is important, however, that we provide the names of the columns when constructing a TimeSeriesDataFrame that is used by AutoGluon. AutoGluon will raise an exception if the data doesn’t match the expected format.

train_data = TimeSeriesDataFrame.from_data_frame(
    df,
    id_column="item_id",
    timestamp_column="timestamp"
)
train_data.head()
target
item_id timestamp
H1 1750-01-01 00:00:00 605.0
1750-01-01 01:00:00 586.0
1750-01-01 02:00:00 586.0
1750-01-01 03:00:00 559.0
1750-01-01 04:00:00 511.0

We refer to each individual time series stored in a TimeSeriesDataFrame as an item. For example, items might correspond to different products in demand forecasting, or to different stocks in financial datasets. This setting is also referred to as a panel of time series. Note that this is not the same as multivariate forecasting — AutoGluon generates forecasts for each time series individually, without modeling interactions between different items (time series).

TimeSeriesDataFrame inherits from pandas.DataFrame, so all attributes and methods of pandas.DataFrame are available in a TimeSeriesDataFrame. It also provides other utility functions, such as loaders for different data formats (see TimeSeriesDataFrame for details).

Training time series models with TimeSeriesPredictor.fit#

To forecast future values of the time series, we need to create a TimeSeriesPredictor object.

Models in autogluon.timeseries forecast time series multiple steps into the future. We choose the number of these steps — the prediction length (also known as the forecast horizon) — depending on our task. For example, our dataset contains time series measured at hourly frequency, so we set prediction_length = 48 to train models that forecast up to 48 hours into the future.

We instruct AutoGluon to save trained models in the folder ./autogluon-m4-hourly. We also specify that AutoGluon should rank models according to mean absolute scaled error (MASE), and that data that we want to forecast is stored in the column "target" of the TimeSeriesDataFrame.

predictor = TimeSeriesPredictor(
    prediction_length=48,
    path="autogluon-m4-hourly",
    target="target",
    eval_metric="MASE",
)

predictor.fit(
    train_data,
    presets="medium_quality",
    time_limit=600,
)
Beginning AutoGluon training... Time limit = 600s
AutoGluon will save models to 'autogluon-m4-hourly'
=================== System Info ===================
AutoGluon Version:  1.0.0b20231228
Python Version:     3.10.8
Operating System:   Linux
Platform Machine:   x86_64
Platform Version:   #1 SMP Tue Nov 30 00:17:50 UTC 2021
CPU Count:          8
GPU Count:          1
Memory Avail:       28.81 GB / 30.96 GB (93.1%)
Disk Space Avail:   215.46 GB / 255.99 GB (84.2%)
===================================================
Setting presets to: medium_quality

Fitting with arguments:
{'enable_ensemble': True,
 'eval_metric': MASE,
 'hyperparameters': 'light',
 'known_covariates_names': [],
 'num_val_windows': 1,
 'prediction_length': 48,
 'quantile_levels': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9],
 'random_seed': 123,
 'refit_every_n_windows': 1,
 'refit_full': False,
 'target': 'target',
 'time_limit': 600,
 'verbosity': 2}

Inferred time series frequency: 'H'
Provided train_data has 148060 rows, 200 time series. Median time series length is 700 (min=700, max=960). 

Provided dataset contains following columns:
	target:           'target'

AutoGluon will gauge predictive performance using evaluation metric: 'MASE'
	This metric's sign has been flipped to adhere to being higher_is_better. The metric score can be multiplied by -1 to get the metric value.
===================================================

Starting training. Start time is 2023-12-28 19:37:10
Models that will be trained: ['Naive', 'SeasonalNaive', 'ETS', 'Theta', 'RecursiveTabular', 'DirectTabular', 'TemporalFusionTransformer']
Training timeseries model Naive. Training for up to 74.8s of the 598.6s of remaining time.
	-6.6629       = Validation score (-MASE)
	0.10    s     = Training runtime
	1.76    s     = Validation (prediction) runtime
Training timeseries model SeasonalNaive. Training for up to 85.2s of the 596.7s of remaining time.
	-1.2169       = Validation score (-MASE)
	0.09    s     = Training runtime
	0.18    s     = Validation (prediction) runtime
Training timeseries model ETS. Training for up to 99.4s of the 596.4s of remaining time.
	-1.9684       = Validation score (-MASE)
	0.09    s     = Training runtime
	79.16   s     = Validation (prediction) runtime
Training timeseries model Theta. Training for up to 103.4s of the 517.2s of remaining time.
	-2.1425       = Validation score (-MASE)
	0.09    s     = Training runtime
	16.89   s     = Validation (prediction) runtime
Training timeseries model RecursiveTabular. Training for up to 125.1s of the 500.2s of remaining time.
	-0.9339       = Validation score (-MASE)
	12.51   s     = Training runtime
	2.22    s     = Validation (prediction) runtime
Training timeseries model DirectTabular. Training for up to 161.8s of the 485.5s of remaining time.
	-1.3703       = Validation score (-MASE)
	5.73    s     = Training runtime
	0.38    s     = Validation (prediction) runtime
Training timeseries model TemporalFusionTransformer. Training for up to 239.7s of the 479.3s of remaining time.
	-2.2153       = Validation score (-MASE)
	69.11   s     = Training runtime
	0.27    s     = Validation (prediction) runtime
Fitting simple weighted ensemble.
	Ensemble weights: {'DirectTabular': 0.04, 'ETS': 0.06, 'RecursiveTabular': 0.87, 'SeasonalNaive': 0.03}
	-0.9143       = Validation score (-MASE)
	3.37    s     = Training runtime
	81.94   s     = Validation (prediction) runtime
Training complete. Models trained: ['Naive', 'SeasonalNaive', 'ETS', 'Theta', 'RecursiveTabular', 'DirectTabular', 'TemporalFusionTransformer', 'WeightedEnsemble']
Total runtime: 192.22 s
Best model: WeightedEnsemble
Best model score: -0.9143
<autogluon.timeseries.predictor.TimeSeriesPredictor at 0x7f62d14fdfc0>

Here we used the "medium_quality" presets and limited the training time to 10 minutes (600 seconds). The presets define which models AutoGluon will try to fit. For medium_quality presets, these are simple baselines (Naive, SeasonalNaive), statistical models (ETS, Theta), tree-based models based on LightGBM (RecursiveTabular, DirectTabular), a deep learning model TemporalFusionTransformer, and a weighted ensemble combining these. Other available presets for TimeSeriesPredictor are "fast_training", "high_quality" and "best_quality". Higher quality presets will usually produce more accurate forecasts but take longer to train.

Inside fit(), AutoGluon will train as many models as possible within the given time limit. Trained models are then ranked based on their performance on an internal validation set. By default, this validation set is constructed by holding out the last prediction_length timesteps of each time series in train_data.

Generating forecasts with TimeSeriesPredictor.predict#

We can now use the fitted TimeSeriesPredictor to forecast the future time series values. By default, AutoGluon will make forecasts using the model that had the best score on the internal validation set. The forecast always includes predictions for the next prediction_length timesteps, starting from the end of each time series in train_data.

predictions = predictor.predict(train_data)
predictions.head()
Model not specified in predict, will default to the model with the best validation score: WeightedEnsemble
mean 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9
item_id timestamp
H1 1750-01-30 04:00:00 628.266367 608.160742 615.062590 620.039308 624.291730 628.266367 632.241003 636.493425 641.470143 648.371991
1750-01-30 05:00:00 558.064668 531.817389 540.827541 547.324495 552.875902 558.064668 563.253435 568.804842 575.301796 584.311947
1750-01-30 06:00:00 515.703113 484.740065 495.369043 503.033285 509.582096 515.703113 521.824130 528.372942 536.037183 546.666162
1750-01-30 07:00:00 484.100765 449.160071 461.154494 469.803316 477.193416 484.100765 491.008113 498.398213 507.047036 519.041458
1750-01-30 08:00:00 460.626424 422.179810 435.377743 444.894381 453.025997 460.626424 468.226850 476.358466 485.875104 499.073037

AutoGluon produces a probabilistic forecast: in addition to predicting the mean (expected value) of the time series in the future, models also provide the quantiles of the forecast distribution. The quantile forecasts give us an idea about the range of possible outcomes. For example, if the "0.1" quantile is equal to 500.0, it means that the model predicts a 10% chance that the target value will be below 500.0.

We will now visualize the forecast and the actually observed values for one of the time series in the dataset. We plot the mean forecast, as well as the 10% and 90% quantiles to show the range of potential outcomes.

import matplotlib.pyplot as plt

# TimeSeriesDataFrame can also be loaded directly from a file
test_data = TimeSeriesDataFrame.from_path("https://autogluon.s3.amazonaws.com/datasets/timeseries/m4_hourly_subset/test.csv")

plt.figure(figsize=(20, 3))

item_id = "H1"
y_past = train_data.loc[item_id]["target"]
y_pred = predictions.loc[item_id]
y_test = test_data.loc[item_id]["target"][-48:]

plt.plot(y_past[-200:], label="Past time series values")
plt.plot(y_pred["mean"], label="Mean forecast")
plt.plot(y_test, label="Future time series values")

plt.fill_between(
    y_pred.index, y_pred["0.1"], y_pred["0.9"], color="red", alpha=0.1, label=f"10%-90% confidence interval"
)
plt.legend();
../../_images/052e49053fd7a1ddd6313bb4c8b6513ecf795cc425c64cf2aba35dcbec5cbbe0.png

Evaluating the performance of different models#

We can view the performance of each model AutoGluon has trained via the leaderboard() method. We provide the test data set to the leaderboard function to see how well our fitted models are doing on the unseen test data. The leaderboard also includes the validation scores computed on the internal validation dataset.

In AutoGluon leaderboards, higher scores always correspond to better predictive performance. Therefore our MASE scores are multiplied by -1, such that higher “negative MASE”s correspond to more accurate forecasts.

# The test score is computed using the last
# prediction_length=48 timesteps of each time series in test_data
predictor.leaderboard(test_data)
Additional data provided, testing on additional data. Resulting leaderboard will be sorted according to test score (`score_test`).
model score_test score_val pred_time_test pred_time_val fit_time_marginal fit_order
0 WeightedEnsemble -0.855041 -0.914341 89.225726 81.940227 3.367113 8
1 RecursiveTabular -0.862797 -0.933874 1.510481 2.221190 12.510008 5
2 SeasonalNaive -1.022854 -1.216909 2.635685 0.179098 0.089895 2
3 DirectTabular -1.683834 -1.370318 0.709869 0.384454 5.733180 6
4 ETS -1.805637 -1.968375 84.359420 79.155484 0.085204 3
5 Theta -1.905365 -2.142531 17.206429 16.885453 0.088165 4
6 TemporalFusionTransformer -1.963280 -2.215312 0.344150 0.273029 69.108186 7
7 Naive -6.696079 -6.662942 0.184447 1.759177 0.098984 1

Summary#

We used autogluon.timeseries to make probabilistic multi-step forecasts on the M4 Hourly dataset. Check out Forecasting Time Series - In Depth to learn about the advanced capabilities of AutoGluon for time series forecasting.