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,
)
================ TimeSeriesPredictor ================
TimeSeriesPredictor.fit() called
Setting presets to: medium_quality
Fitting with arguments:
{'enable_ensemble': True,
 'evaluation_metric': 'MASE',
 'excluded_model_types': None,
 'hyperparameter_tune_kwargs': None,
 'hyperparameters': 'medium_quality',
 'num_val_windows': 1,
 'prediction_length': 48,
 'random_seed': None,
 'target': 'target',
 'time_limit': 600,
 'verbosity': 2}
Provided training data set with 148060 rows, 200 items (item = single time series). Average time series length is 740.3. Data frequency is 'H'.
=====================================================
AutoGluon will save models to autogluon-m4-hourly/
AutoGluon will gauge predictive performance using evaluation metric: 'MASE'
	This metric's sign has been flipped to adhere to being 'higher is better'. The reported score can be multiplied by -1 to get the metric value.

Provided dataset contains following columns:
	target:           'target'

Starting training. Start time is 2023-06-29 22:42:13
Models that will be trained: ['Naive', 'SeasonalNaive', 'Theta', 'AutoETS', 'RecursiveTabular', 'DeepAR']
Training timeseries model Naive. Training for up to 599.65s of the 599.65s of remaining time.
	-6.6629       = Validation score (-MASE)
	0.12    s     = Training runtime
	4.23    s     = Validation (prediction) runtime
Training timeseries model SeasonalNaive. Training for up to 595.30s of the 595.30s of remaining time.
	-1.2169       = Validation score (-MASE)
	0.11    s     = Training runtime
	0.22    s     = Validation (prediction) runtime
Training timeseries model Theta. Training for up to 594.96s of the 594.96s of remaining time.
	-2.1425       = Validation score (-MASE)
	0.11    s     = Training runtime
	28.13   s     = Validation (prediction) runtime
Training timeseries model AutoETS. Training for up to 566.70s of the 566.70s of remaining time.
	-1.9399       = Validation score (-MASE)
	0.11    s     = Training runtime
	101.97  s     = Validation (prediction) runtime
Training timeseries model RecursiveTabular. Training for up to 464.62s of the 464.62s of remaining time.
	-0.8988       = Validation score (-MASE)
	14.27   s     = Training runtime
	2.44    s     = Validation (prediction) runtime
Training timeseries model DeepAR. Training for up to 447.88s of the 447.88s of remaining time.
	-1.8848       = Validation score (-MASE)
	94.43   s     = Training runtime
	2.04    s     = Validation (prediction) runtime
Fitting simple weighted ensemble.
	-0.8850       = Validation score (-MASE)
	6.11    s     = Training runtime
	106.67  s     = Validation (prediction) runtime
Training complete. Models trained: ['Naive', 'SeasonalNaive', 'Theta', 'AutoETS', 'RecursiveTabular', 'DeepAR', 'WeightedEnsemble']
Total runtime: 254.80 s
Best model: WeightedEnsemble
Best model score: -0.8850
<autogluon.timeseries.predictor.TimeSeriesPredictor at 0x7fbf2e8788e0>

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 (AutoETS, Theta), tree-based model LightGBM wrapped by RecursiveTabular, a deep learning model DeepAR, 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()
Global seed set to 123
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 623.826478 592.187364 603.071471 610.896354 617.586165 623.839536 630.088389 636.772222 644.605014 655.454230
1750-01-30 05:00:00 557.547544 514.678373 529.443829 540.037456 549.108091 557.563545 566.026309 575.078872 585.677181 600.402671
1750-01-30 06:00:00 514.927764 463.480392 481.166716 493.907031 504.765269 514.936364 525.100682 535.968523 548.697259 566.357110
1750-01-30 07:00:00 480.985158 422.308391 442.465546 457.012861 469.396393 480.990611 492.562915 504.980224 519.509260 539.677283
1750-01-30 08:00:00 458.342474 393.299979 415.597355 431.712749 445.475217 458.345099 471.220778 484.969452 501.030328 523.435727

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/b28eaab2f3c52364bbdea28367bf7bbf8f04e1c8081fdf4dbbad820b4e4f9194.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, silent=True)
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.850541 -0.885005 100.841253 106.672521 6.112758 7
1 RecursiveTabular -0.870271 -0.898770 1.789228 2.443860 14.273363 5
2 SeasonalNaive -1.022854 -1.216909 0.237972 0.218211 0.114915 2
3 AutoETS -1.778531 -1.939939 96.717588 101.967237 0.113186 4
4 DeepAR -1.819948 -1.884837 2.049753 2.043213 94.428325 6
5 Theta -1.905365 -2.142531 2.995191 28.133277 0.114513 3
6 Naive -6.696079 -6.662942 0.224626 4.226221 0.118196 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.