This example demonstrates how Polars-engineered lagged features can be used
for time series forecasting with
HistGradientBoostingRegressor on the Bike Sharing
Demand dataset.
See the example on
Time-related feature engineering
for some data exploration on this dataset and a demo on periodic feature
engineering.
# Authors: The scikit-learn developers# SPDX-License-Identifier: BSD-3-Clause
Analyzing the Bike Sharing Demand dataset
We start by loading the data from the OpenML repository as a raw parquet file
to illustrate how to work with an arbitrary parquet file instead of hiding this
step in a convenience tool such as .
We load the parquet file with Polars for feature engineering. Polars
automatically caches common subexpressions which are reused in multiple
expressions (like pl.col("count").shift(1) below). See
https://docs.pola.rs/user-guide/lazy/optimizations/ for more information.
df=pl.read_parquet(bike_sharing_data_file)
Next, we take a look at the statistical summary of the dataset
so that we can better understand the data that we are working with.
Let’s consider the problem of predicting the demand at the
next hour given past demands. Since the demand is a continuous
variable, one could intuitively use any regression model. However, we do
not have the usual (X_train,y_train) dataset. Instead, we just have
the y_train demand data sequentially organized by time.
Naive evaluation of the next hour bike demand regression
Let’s randomly split our tabularized dataset to train a gradient
boosting regression tree (GBRT) model and evaluate it using Mean
Absolute Percentage Error (MAPE). If our model is aimed at forecasting
(i.e., predicting future data from past data), we should not use training
data that are ulterior to the testing data. In time series machine learning
the “i.i.d” (independent and identically distributed) assumption does not
hold true as the data points are not independent and have a temporal
relationship.
Let’s use a proper evaluation splitting strategies that takes into account
the temporal structure of the dataset to evaluate our model’s ability to
predict data points in the future (to avoid cheating by reading values from
the lagged features in the training set).
fromsklearn.model_selectionimportTimeSeriesSplitts_cv=TimeSeriesSplit(n_splits=3,# to keep the notebook fast enough on common laptopsgap=48,# 2 days data gap between train and testmax_train_size=10000,# keep train sets of comparable sizestest_size=3000,# for 2 or 3 digits of precision in scores)all_splits=list(ts_cv.split(X,y))
Training the model and evaluating its performance based on MAPE.
The generalization error measured via a shuffled trained test split
is too optimistic. The generalization via a time-based split is likely to
be more representative of the true performance of the regression model.
Let’s assess this variability of our error evaluation with proper
cross-validation:
The variability across splits is quite large! In a real life setting
it would be advised to use more splits to better assess the variability.
Let’s report the mean CV scores and their standard deviation from now on.
Modeling predictive uncertainty via quantile regression
Instead of modeling the expected value of the distribution of
Y∣X like the least squares and Poisson losses do, one could try to
estimate quantiles of the conditional distribution.
Y∣X=xi is expected to be a random variable for a given data point
xi because we expect that the number of rentals cannot be 100%
accurately predicted from the features. It can be influenced by other
variables not properly captured by the existing lagged features. For
instance whether or not it will rain in the next hour cannot be fully
anticipated from the past hours bike rental data. This is what we
call aleatoric uncertainty.
Quantile regression makes it possible to give a finer description of that
distribution without making strong assumptions on its shape.
Even if the score distributions overlap due to the variance in the dataset,
it is true that the average RMSE is lower when loss="squared_error", whereas
the average MAPE is lower when loss="absolute_error" as expected. That is
also the case for the Mean Pinball Loss with the quantiles 5 and 95. The score
corresponding to the 50 quantile loss is overlapping with the score obtained
by minimizing other loss functions, which is also the case for the MAE.
A qualitative look at the predictions
We can now visualize the performance of the model with regards
to the 5th percentile, median and the 95th percentile:
We can now take a look at the predictions made by the regression models:
last_hours=slice(-96,None)fig,ax=plt.subplots(figsize=(15,7))plt.title("Predictions by regression models")ax.
Here it’s interesting to notice that the blue area between the 5% and 95%
percentile estimators has a width that varies with the time of the day:
At night, the blue band is much narrower: the pair of models is quite
certain that there will be a small number of bike rentals. And furthermore
these seem correct in the sense that the actual demand stays in that blue
band.
During the day, the blue band is much wider: the uncertainty grows, probably
because of the variability of the weather that can have a very large impact,
especially on week-ends.
We can also see that during week-days, the commute pattern is still visible in
the 5% and 95% estimations.
Finally, it is expected that 10% of the time, the actual demand does not lie
between the 5% and 95% percentile estimates. On this test span, the actual
demand seems to be higher, especially during the rush hours. It might reveal that
our 95% percentile estimator underestimates the demand peaks. This could be be
quantitatively confirmed by computing empirical coverage numbers as done in
the calibration of confidence intervals.
Looking at the performance of non-linear regression models vs
the best models:
Through this example we explored time series forecasting using lagged
features. We compared a naive regression (using the standardized
train_test_split) with a proper time
series evaluation strategy using
TimeSeriesSplit. We observed that the
model trained using train_test_split,
having a default value of shuffle set to True produced an overly
optimistic Mean Average Percentage Error (MAPE). The results
produced from the time-based split better represent the performance
of our time-series regression model. We also analyzed the predictive uncertainty
of our model via Quantile Regression. Predictions based on the 5th and
95th percentile using loss="quantile" provide us with a quantitative estimate
of the uncertainty of the forecasts made by our time series regression model.
Uncertainty estimation can also be performed
using MAPIE,
that provides an implementation based on recent work on conformal prediction
methods and estimates both aleatoric and epistemic uncertainty at the same time.
Furthermore, functionalities provided
by sktime
can be used to extend scikit-learn estimators by making use of recursive time
series forecasting, that enables dynamic predictions of future values.
Total running time of the script: (0 minutes 8.186 seconds)