Prerequesites

This tutorial assumes basic familiarity with MLForecast. For a minimal example visit the Quick Start

Introduction

When we generate a forecast, we usually produce a single value known as the point forecast. This value, however, doesn’t tell us anything about the uncertainty associated with the forecast. To have a measure of this uncertainty, we need prediction intervals.

A prediction interval is a range of values that the forecast can take with a given probability. Hence, a 95% prediction interval should contain a range of values that include the actual future value with probability 95%. Probabilistic forecasting aims to generate the full forecast distribution. Point forecasting, on the other hand, usually returns the mean or the median or said distribution. However, in real-world scenarios, it is better to forecast not only the most probable future outcome, but many alternative outcomes as well.

With MLForecast you can train sklearn models to generate point forecasts. It also takes the advantages of ConformalPrediction to generate the same point forecasts and adds them prediction intervals. By the end of this tutorial, you’ll have a good understanding of how to add probabilistic intervals to sklearn models for time series forecasting. Furthermore, you’ll also learn how to generate plots with the historical data, the point forecasts, and the prediction intervals.

Important

Although the terms are often confused, prediction intervals are not the same as confidence intervals.

Warning

In practice, most prediction intervals are too narrow since models do not account for all sources of uncertainty. A discussion about this can be found here.

Outline:

  1. Install libraries
  2. Load and explore the data
  3. Train models
  4. Plot prediction intervals

Tip

You can use Colab to run this Notebook interactively

Open In Colab

Install libraries

Install the necessary packages using pip install mlforecast utilsforecast

Load and explore the data

For this example, we’ll use the hourly dataset from the M4 Competition. We first need to download the data from a URL and then load it as a pandas dataframe. Notice that we’ll load the train and the test data separately. We’ll also rename the y column of the test data as y_test.

import pandas as pd
from utilsforecast.plotting import plot_series
train = pd.read_csv('https://auto-arima-results.s3.amazonaws.com/M4-Hourly.csv')
test = pd.read_csv('https://auto-arima-results.s3.amazonaws.com/M4-Hourly-test.csv')
train.head()
unique_iddsy
0H11605.0
1H12586.0
2H13586.0
3H14559.0
4H15511.0
test.head()
unique_iddsy
0H1701619.0
1H1702565.0
2H1703532.0
3H1704495.0
4H1705481.0

Since the goal of this notebook is to generate prediction intervals, we’ll only use the first 8 series of the dataset to reduce the total computational time.

n_series = 8 
uids = train['unique_id'].unique()[:n_series] # select first n_series of the dataset
train = train.query('unique_id in @uids')
test = test.query('unique_id in @uids')

We can plot these series using the plot_series function from the utilsforecast library. This function has multiple parameters, and the required ones to generate the plots in this notebook are explained below.

  • df: A pandas dataframe with columns [unique_id, ds, y].
  • forecasts_df: A pandas dataframe with columns [unique_id, ds] and models.
  • plot_random: bool = True. Plots the time series randomly.
  • models: List[str]. A list with the models we want to plot.
  • level: List[float]. A list with the prediction intervals we want to plot.
  • engine: str = matplotlib. It can also be plotly. plotly generates interactive plots, while matplotlib generates static plots.
fig = plot_series(train, test.rename(columns={'y': 'y_test'}), models=['y_test'], plot_random=False)

Train models

MLForecast can train multiple models that follow the sklearn syntax (fit and predict) on different time series efficiently.

For this example, we’ll use the following sklearn baseline models:

To use these models, we first need to import them from sklearn and then we need to instantiate them.

from mlforecast import MLForecast
from mlforecast.target_transforms import Differences
from mlforecast.utils import PredictionIntervals
from sklearn.linear_model import Lasso, LinearRegression, Ridge
from sklearn.neighbors import KNeighborsRegressor
from sklearn.neural_network import MLPRegressor
# Create a list of models and instantiation parameters 
models = [
    KNeighborsRegressor(),
    Lasso(),
    LinearRegression(),
    MLPRegressor(),
    Ridge(),
]

To instantiate a new MLForecast object, we need the following parameters:

  • models: The list of models defined in the previous step.
  • target_transforms: Transformations to apply to the target before computing the features. These are restored at the forecasting step.
  • lags: Lags of the target to use as features.
mlf = MLForecast(
    models=[Ridge(), Lasso(), LinearRegression(), KNeighborsRegressor(), MLPRegressor(random_state=0)],
    freq=1,
    target_transforms=[Differences([1])],
    lags=[24 * (i+1) for i in range(7)],
)

Now we’re ready to generate the point forecasts and the prediction intervals. To do this, we’ll use the fit method, which takes the following arguments:

  • data: Series data in long format.
  • id_col: Column that identifies each series. In our case, unique_id.
  • time_col: Column that identifies each timestep, its values can be timestamps or integers. In our case, ds.
  • target_col: Column that contains the target. In our case, y.
  • prediction_intervals: A PredicitonIntervals class. The class takes two parameters: n_windows and h. n_windows represents the number of cross-validation windows used to calibrate the intervals and h is the forecast horizon. The strategy will adjust the intervals for each horizon step, resulting in different widths for each step.
mlf.fit(
    train,
    prediction_intervals=PredictionIntervals(n_windows=10, h=48),
);

After fitting the models, we will call the predict method to generate forecasts with prediction intervals. The method takes the following arguments:

  • horizon: An integer that represent the forecasting horizon. In this case, we’ll forecast the next 48 hours.
  • level: A list of floats with the confidence levels of the prediction intervals. For example, level=[95] means that the range of values should include the actual future value with probability 95%.
levels = [50, 80, 95]
forecasts = mlf.predict(48, level=levels)
forecasts.head()
unique_iddsRidgeLassoLinearRegressionKNeighborsRegressorMLPRegressorRidge-lo-95Ridge-lo-80Ridge-lo-50KNeighborsRegressor-lo-50KNeighborsRegressor-hi-50KNeighborsRegressor-hi-80KNeighborsRegressor-hi-95MLPRegressor-lo-95MLPRegressor-lo-80MLPRegressor-lo-50MLPRegressor-hi-50MLPRegressor-hi-80MLPRegressor-hi-95
0H1701612.418170612.418079612.418170615.2612.651532590.473256594.326570603.409944609.45620.95627.20631.310584.736193591.084898597.462107627.840957634.218166640.566870
1H1702552.309298552.308073552.309298551.6548.791801498.721501518.433843532.710850535.85567.35569.16597.525497.308756500.417799515.452396582.131207597.165804600.274847
2H1703494.943384494.943367494.943384509.6490.226796448.253304463.266064475.006125492.70526.50530.92544.180424.587658436.042788448.682502531.771091544.410804555.865935
3H1704462.815779462.815363462.815779474.6459.619069409.975219422.243593436.128272451.80497.40510.26525.500379.291083392.580306413.353178505.884959526.657832539.947054
4H1705440.141034440.140586440.141034451.6438.091712377.999588392.523016413.474795427.40475.80488.96503.945348.618034362.503767386.303325489.880099513.679657527.565389
test = test.merge(forecasts, how='left', on=['unique_id', 'ds'])

Plot prediction intervals

To plot the point and the prediction intervals, we’ll use the plot_series function again. Notice that now we also need to specify the model and the levels that we want to plot.

KNeighborsRegressor

fig = plot_series(
    train, 
    test, 
    plot_random=False, 
    models=['KNeighborsRegressor'], 
    level=levels, 
    max_insample_length=48
)

Lasso

fig = plot_series(
    train, 
    test, 
    plot_random=False, 
    models=['Lasso'],
    level=levels, 
    max_insample_length=48
)

LineaRegression

fig = plot_series(
    train, 
    test, 
    plot_random=False, 
    models=['LinearRegression'],
    level=levels, 
    max_insample_length=48
)

MLPRegressor

fig = plot_series(
    train, 
    test, 
    plot_random=False, 
    models=['MLPRegressor'],
    level=levels, 
    max_insample_length=48
)

Ridge

fig = plot_series(
    train, 
    test, 
    plot_random=False, 
    models=['Ridge'],
    level=levels, 
    max_insample_length=48
)

From these plots, we can conclude that the uncertainty around each forecast varies according to the model that is being used. For the same time series, one model can predict a wider range of possible future values than others.

References