Sub topic 17
Prediction intervals with quantile loss
This chapter assumes you have built the lag, rolling and calendar features from earlier chapters. It also assumes you can fit a HistGradientBoostingRegressor and run a chronological split. The code below is self-contained, so you can run it as shown.
Why a point forecast is not enough
A point forecast gives one number, such as "120 units tomorrow". It doesn't say whether the real value could plausibly be 118 or 160. A planner who sets safety stock, staffing or capacity needs that range.
A prediction interval gives it. An 80% interval from 108 to 134 means you expect the actual value to land inside that range about 80% of the time. The interval is built from two quantiles of the predictive distribution: the 10th percentile as the lower bound and the 90th percentile as the upper bound.
A quantile is the value below which a given fraction of outcomes fall. The 0.9 quantile is the value that the target stays under 90% of the time.
Pinball loss: how a model learns a quantile
Squared error trains a model to predict the mean. Absolute error trains it to predict the median. To predict any other quantile, you use an asymmetric version of absolute error called pinball loss, or quantile loss. For a quantile level q, prediction ŷ and actual value y:
- If
y >= ŷ(the model under-predicted), the loss isq * (y - ŷ). - If
y < ŷ(the model over-predicted), the loss is(1 - q) * (ŷ - y).
The two penalties differ, and that difference is what pulls the prediction toward the quantile.
| Quantile `q` | Cost of under-predicting by 1 | Cost of over-predicting by 1 | What the model learns |
|---|---|---|---|
| 0.1 | 0.1 | 0.9 | A low estimate, exceeded about 90% of the time |
| 0.5 | 0.5 | 0.5 | The median (same as MAE up to a factor of 2) |
| 0.9 | 0.9 | 0.1 | A high estimate, exceeded about 10% of the time |
At q = 0.9, being too low is nine times more expensive than being too high. The best strategy under that loss is to predict a value that the target falls below 90% of the time. Gradient boosting works with this loss without changes, because it only needs a loss that it can differentiate (or approximate) on the residuals.
One model per quantile
Scikit-learn's HistGradientBoostingRegressor accepts loss="quantile" and a quantile argument (scikit-learn 1.1 or later). Each quantile needs its own model. The features are the same, and only the loss changes.
The script below builds a synthetic daily series whose noise is larger on weekends. It then trains the three models on the first 80% of rows and predicts the last 20%.
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_pinball_loss
# Synthetic daily series: weekly pattern, noisier on weekends
rng = np.random.default_rng(0)
idx = pd.date_range('2022-01-01', periods=900, freq='D')
weekly = 10 * np.sin(2 * np.pi * idx.dayofweek / 7)
noise = rng.normal(0, 3 + 4 * (idx.dayofweek >= 5), len(idx))
series = pd.Series(100 + weekly + noise, index=idx)
def make_features(s: pd.Series) -> pd.DataFrame:
df = pd.DataFrame({'y': s})
for lag in (1, 7, 14):
df[f'lag_{lag}'] = s.shift(lag)
past = s.shift(1)
df['roll_mean_7'] = past.rolling(7).mean()
df['roll_std_7'] = past.rolling(7).std()
df['dayofweek'] = s.index.dayofweek
return df.dropna()
data = make_features(series)
feature_cols = [c for c in data.columns if c != 'y']
cut = int(len(data) * 0.8)
train, test = data.iloc[:cut], data.iloc[cut:]
quantiles = (0.1, 0.5, 0.9)
models = {}
for q in quantiles:
m = HistGradientBoostingRegressor(
loss='quantile', quantile=q,
max_iter=300, learning_rate=0.05, random_state=0,
)
m.fit(train[feature_cols], train['y'])
models[q] = m
preds = pd.DataFrame(
{q: models[q].predict(test[feature_cols]) for q in quantiles},
index=test.index,
)
print(preds.head())Checking the intervals
Two checks tell you whether the intervals are usable.
- Coverage is the fraction of test actuals that fall between the lower and upper bounds. For an 80% interval, it should land near 0.80.
- Pinball loss at each quantile measures how good that quantile prediction is. Lower is better. Scikit-learn provides
mean_pinball_loss.
lower, upper = preds[0.1], preds[0.9]
inside = (test['y'] >= lower) & (test['y'] <= upper)
print('coverage of 80% interval:', inside.mean())
print('mean interval width :', (upper - lower).mean())
for q in quantiles:
loss = mean_pinball_loss(test['y'], preds[q], alpha=q)
print(f'pinball loss q={q}:', loss)Coverage alone can be gamed, because an absurdly wide interval always covers. Report coverage together with the mean width. Among intervals with similar coverage, the narrower one is better.
You can also check coverage by weekday. In this data the weekend noise is larger, so a good model should produce wider intervals on Saturdays and Sundays. Compare (upper - lower).groupby(test['dayofweek']).mean() across days. A quantile model has no fixed noise level built in, so it can adapt the width to the features.
Gotchas
Quantile crossing
The three models are trained independently, so nothing forces the 0.1 prediction to stay below the 0.9 prediction. On some rows they can cross, which gives a negative-width interval. The simplest fix is to sort the predictions for each row:
sorted_preds = np.sort(preds.to_numpy(), axis=1)
preds_fixed = pd.DataFrame(sorted_preds, index=preds.index, columns=preds.columns)
print((preds.to_numpy() != sorted_preds).any(axis=1).sum(), 'rows were reordered')If many rows need reordering, the models are too noisy. Use more regularization or more training data.
Under-coverage on future data
Intervals from quantile models are often too narrow on out-of-sample data, because the model fits the training residual spread, which is smaller than the spread of true future errors. Treat the coverage on the test block as the real number. Compute it with walk-forward validation, as in the validation chapter, so that you see its variation across folds and not a single value.
If coverage is consistently low, you have two common options. You can request wider quantiles, such as 0.05 and 0.95, and measure the coverage they actually deliver. Or you can widen the interval by an offset estimated from validation residuals (a simple form of conformal calibration).
Multi-step horizons
The quantile models above predict one step ahead from known lags. With the recursive strategy, feeding the 0.9 prediction back in as a lag pushes the error through every later step, and the resulting interval has no clear meaning. Two cleaner options exist:
- Use the direct strategy: train a separate quantile model for each horizon and quantile. This costs more models but keeps each interval honest.
- Feed the median (
q = 0.5) forecast back in recursively, and accept that the intervals for later steps will probably be too narrow. Check their coverage at each horizon.
Intervals should widen as the horizon grows. If yours stay the same width at step 1 and step 14, the coverage at step 14 is almost certainly too low.
Tree models and extrapolation
Quantile models share the limit from the trend chapter. Trees cannot predict outside the range of targets seen in training. If the series trends upward, both bounds will flatten at the training maximum. Model differences or ratios, or detrend first, and add the trend back to both bounds.
Other gotchas
- Tuning: Choose hyperparameters per quantile using pinball loss at that quantile, not MAE. Early stopping with a quantile loss also uses that loss.
- Data volume: Extreme quantiles such as 0.01 and 0.99 depend on a few rare observations. With a few hundred rows they will be unstable.
- Metrics: Do not describe the 0.5 model's pinball loss as MAE. It is half the MAE.
Exercise
You train quantile models at q=0.05 and q=0.95 and expect a 90% interval. On a walk-forward test block, the interval covers only 76% of actuals, and for 12 rows the lower bound is above the upper bound. Name one fix for each problem.
Show answer
For the crossed bounds, sort each row's predictions so the lower value is the smaller one (np.sort along axis 1), or reduce the noise of the models with more regularization. For the low coverage, the intervals are too narrow on unseen data. Widen them, either by moving to more extreme quantiles or by adding an offset estimated from validation residuals, and then re-measure coverage and mean width on walk-forward folds.