Prediction Intervals for Gradient Boosting Regression
This example shows how quantile regression can be used to create prediction
intervals. See Features in Histogram Gradient Boosting Trees
for an example showcasing some other features of
HistGradientBoostingRegressor.
# Authors: The scikit-learn developers# SPDX-License-Identifier: BSD-3-Clause
Generate some data for a synthetic regression problem by applying the
function f to uniformly sampled random inputs.
To make the problem interesting, we generate observations of the target y as
the sum of a deterministic term computed by the function f and a random noise
term that follows a centered log-normal. To make this even
more interesting we consider the case where the amplitude of the noise
depends on the input variable x (heteroscedastic noise).
The lognormal distribution is non-symmetric and long tailed: observing large
outliers is likely but it is impossible to observe small outliers.
Fitting non-linear quantile and least squares regressors
Fit gradient boosting models trained with the quantile loss and alpha=0.05,
alpha=0.5, alpha=0.95.
The models obtained for alpha=0.05 and alpha=0.95 produce a 90% coverage
interval (95% - 5% = 90%).
The model trained with alpha=0.5 produces a regression of the median: on
average, there should be the same number of target observations above and
below the predicted values.
Plot the true conditional mean function f, the predictions of the conditional
mean (loss equals squared error), the conditional median and the conditional
90% interval (from 5th to 95th conditional percentiles).
Comparing the predicted median with the predicted mean, we note that the
median is on average below the mean as the noise is skewed towards high
values (large outliers). The median estimate also seems to be smoother
because of its natural robustness to outliers.
Also observe that the inductive bias of gradient boosting trees is
unfortunately preventing our 0.05 quantile to fully capture the sinoisoidal
shape of the signal, in particular around x=8. Tuning hyper-parameters can
reduce this effect as shown in the last part of this notebook.
One column shows all models evaluated by the same metric. The minimum number
on a column should be obtained when the model is trained and measured with
the same metric. This should be always the case on the training set if the
training converged.
Note that because the target distribution is asymmetric, the expected
conditional mean and conditional median are significantly different and
therefore one could not use the squared error model get a good estimation of
the conditional median nor the converse.
If the target distribution were symmetric and had no outliers (e.g. with a
Gaussian noise), then median estimator and the least squares estimator would
have yielded similar predictions.
Errors are higher meaning the models slightly overfitted the data. It still
shows that the best test metric is obtained when the model is trained by
minimizing this same metric.
Note that the conditional median estimator is competitive with the squared
error estimator in terms of MSE on the test set: this can be explained by
the fact the squared error estimator is very sensitive to large outliers
which can cause significant overfitting. This can be seen on the right hand
side of the previous plot. The conditional median estimator is biased
(underestimation for this asymmetric noise) but is also naturally robust to
outliers and overfits less.
Tuning the hyper-parameters of the quantile regressors
In the plot above, we observed that the 5th percentile regressor seems to
underfit and could not adapt to sinusoidal shape of the signal.
The hyper-parameters of the model were approximately hand-tuned for the
median regressor and there is no reason that the same hyper-parameters are
suitable for the 5th percentile regressor.
To confirm this hypothesis, we tune the hyper-parameters of a new regressor
of the 5th percentile by selecting the best model parameters by
cross-validation on the pinball loss with alpha=0.05:
frompprintimportpprintfromsklearn.experimentalimportenable_halving_search_cv# noqa: F401fromsklearn.metricsimportmake_scorerfromsklearn.model_selectionimportHalvingRandomSearchCVparam_grid=dict(learning_rate=[0.05,0.1,0.2],max_depth=[2,5,10],min_samples_leaf=[1,5,10,20],min_samples_split=[5,10,20,30,50],)neg_mean_pinball_loss_05p_scorer=make_scorer(mean_pinball_loss,alpha=0.05,greater_is_better=False,# maximize the negative loss)gbr=GradientBoostingRegressor(loss="quantile",alpha=0.05,random_state=0)search_05p=HalvingRandomSearchCV(gbr,param_grid,resource="n_estimators",max_resources=250,min_resources=50,scoring=neg_mean_pinball_loss_05p_scorer,n_jobs=2,random_state=0,).fit(X_train,y_train)pprint(search_05p.best_params_)
We observe that the hyper-parameters that were hand-tuned for the median
regressor are in the same range as the hyper-parameters suitable for the 5th
percentile regressor.
Let’s now tune the hyper-parameters for the 95th percentile regressor. We
need to redefine the scoring metric used to select the best model, along
with adjusting the alpha parameter of the inner gradient boosting estimator
itself:
fromsklearn.baseimportcloneneg_mean_pinball_loss_95p_scorer=make_scorer(mean_pinball_loss,alpha=0.95,greater_is_better=False,# maximize the negative loss)search_95p=clone(search_05p).
The result shows that the hyper-parameters for the 95th percentile regressor
identified by the search procedure are roughly in the same range as the hand-tuned
hyper-parameters for the median regressor and the hyper-parameters
identified by the search procedure for the 5th percentile regressor. However,
the hyper-parameter searches did lead to an improved 90% coverage interval
that is comprised by the predictions of those two tuned quantile regressors.
Note that the prediction of the upper 95th percentile has a much coarser shape
than the prediction of the lower 5th percentile because of the outliers:
The plot looks qualitatively better than for the untuned models, especially
for the shape of the of lower quantile.
Calibration of the confidence interval
We can also evaluate the ability of the two extreme quantile estimators at
producing well-calibrated predictions of the 90%-coverage interval
(conditional on X), meaning that on average 90% of the observations should
lie within this interval.
To do this we can compute the coverage fraction, i.e. the proportion of
observations that fall within the prediction intervals:
On the test set, the estimated interval is too narrow to cover 90% of the test
points, but it may still hit the right coverage within reasonable statistical
uncertainty. We can use scipy.stats.bootstrap to measure the
variability of the coverage fraction at prediction time, without retraining
the models. We use a 95% confidence level for the estimated (bootstrapped)
interval of coverage; this is not to be confused with the 90% coverage
stemming from our 5% and 95% quantile predictions:
Test-set coverage lies between 73.8% and 84.4%, based on a 95% bootstrap confidence interval.
The quantile estimates from the tuned models are sadly not well-calibrated on
the test set: the width of the estimated confidence interval is too narrow
even when taking it’s variations into account.
Total running time of the script: (0 minutes 10.924 seconds)