A normal regression model gives one number: “this trip will take 31 minutes”. But a customer would rather hear “usually 27 to 35 minutes”. Quantile regression predicts a chosen percentile instead of the average. Predicting a low and a high percentile together gives a prediction interval, a range that should contain most real outcomes.
In this lesson you will learn
- What a quantile is and why the average is not always enough
- Building an 80% prediction interval with gradient boosting
- Checking that the interval really covers 80% of new cases
- How the pinball loss makes a model aim at a quantile
- Fitting straight-line quantiles with
QuantileRegressor
You should know linear regression, regression metrics and gradient boosting.
Quantiles in One Minute
The 0.9 quantile (90th percentile) is the value that 90% of outcomes fall below. The 0.5 quantile is the median. A quantile model predicts that value for each input. For example, a 0.9 quantile model for delivery time says: “for this distance, 90% of trips take less than this.”
The average alone hides how uncertain a prediction is. Short trips are fairly predictable; long trips through traffic are not. Quantiles show that difference.
An 80% Interval With Gradient Boosting
We train three models on taxi trips: one for the 0.1 quantile, one for the median and one for the 0.9 quantile. The range from the 0.1 to the 0.9 prediction should hold about 80% of trips.
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import train_test_split
# Taxi trip time (minutes) by distance: longer trips are less predictable
rng = np.random.default_rng(2)
km = rng.uniform(1, 20, 2000)
minutes = 5 + 2.5 * km + rng.normal(0, 0.5 + 0.35 * km)
X_tr, X_te, y_tr, y_te = train_test_split(km.reshape(-1, 1), minutes, random_state=0)
models = {}
for q in [0.1, 0.5, 0.9]:
models[q] = GradientBoostingRegressor(loss="quantile", alpha=q, n_estimators=200,
max_depth=2, random_state=0).fit(X_tr, y_tr)
for d in [2, 10, 18]:
lo, mid, hi = (models[q].predict([[d]])[0] for q in [0.1, 0.5, 0.9])
print(f"{d:2} km: median {mid:5.1f} min, 80% range {lo:5.1f} to {hi:5.1f}")
lo, hi = models[0.1].predict(X_te), models[0.9].predict(X_te)
inside = ((y_te >= lo) & (y_te <= hi)).mean()
print(f"Test trips inside their 80% range: {inside:.1%}")
Output
2 km: median 9.9 min, 80% range 8.4 to 11.9
10 km: median 30.6 min, 80% range 26.5 to 35.3
18 km: median 49.3 min, 80% range 41.1 to 57.2
Test trips inside their 80% range: 79.0%
loss="quantile"withalpha=0.9tells gradient boosting to aim at the 90th percentile instead of the mean.- The interval widens with distance: about 3.5 minutes wide for 2 km, but about 16 minutes wide for 18 km. The data was built so that longer trips are less predictable, and the model picked that up without being told.
- On the test set, 79.0% of trips fall inside their interval, very close to the 80% target. This check, called coverage, is the most important test of a prediction interval.
Because the three models are trained separately, their predictions can occasionally cross, with the 0.1 prediction above the 0.9 prediction. If that happens in your data, sort the predictions for each row.
How the Model Aims at a Quantile: Pinball Loss
Mean squared error is smallest when you predict the average. The pinball loss is smallest when you predict a chosen quantile. For the 0.9 quantile, guessing too low costs 9 times as much as guessing too high by the same amount. So the best guess is pushed upward until only 10% of outcomes lie above it.
import numpy as np
from sklearn.linear_model import QuantileRegressor
from sklearn.metrics import mean_pinball_loss
# Pinball loss: which single guess is "best" for the 90th percentile?
rng = np.random.default_rng(0)
waits = rng.exponential(5, 1000) # 1,000 bus waits in minutes
print(f"90th percentile of waits: {np.percentile(waits, 90):.1f}")
for guess in [5, 8, 11, 14, 17]:
loss = mean_pinball_loss(waits, np.full(len(waits), guess), alpha=0.9)
print(f"guess {guess:2}: pinball loss {loss:.2f}")
# A straight-line quantile model
rng = np.random.default_rng(2)
km = rng.uniform(1, 20, 500)
minutes = 5 + 2.5 * km + rng.normal(0, 0.5 + 0.35 * km)
X = km.reshape(-1, 1)
for q in [0.1, 0.9]:
m = QuantileRegressor(quantile=q, alpha=0).fit(X, minutes)
print(f"q={q}: minutes = {m.intercept_:.2f} + {m.coef_[0]:.2f} * km")
Output
90th percentile of waits: 11.6
guess 5: pinball loss 1.85
guess 8: pinball loss 1.30
guess 11: pinball loss 1.14
guess 14: pinball loss 1.19
guess 17: pinball loss 1.35
q=0.1: minutes = 4.35 + 2.03 * km
q=0.9: minutes = 5.54 + 2.98 * km
- The 90th percentile of the waits is 11.6 minutes. Among the guesses tried, the pinball loss is lowest at 11, the guess nearest to it. Both lower and higher guesses score worse.
mean_pinball_lossis also how you should score a quantile model on test data. Use the samealphaas the model.QuantileRegressorfits a straight line for one quantile. The 0.9 line is steeper than the 0.1 line (2.98 versus 2.03 minutes per km), so the interval widens with distance, just as with gradient boosting.alpha=0inQuantileRegressorturns off its regularization penalty. Do not confuse it with thealphainGradientBoostingRegressor, which is the quantile.
Quantile Models in scikit-learn
| Model | How to set the quantile | Notes |
|---|---|---|
QuantileRegressor | quantile=0.9 | Straight-line model; slow on large data |
GradientBoostingRegressor | loss="quantile", alpha=0.9 | Flexible; one model per quantile |
HistGradientBoostingRegressor | loss="quantile", quantile=0.9 | Much faster on large datasets |
Common Mistakes
- Not checking coverage. An “80% interval” that holds only 60% of test cases misleads users. Always measure it on held-out data.
- Using mean ± a fixed amount when uncertainty changes with the input. Quantile models allow the width to vary.
- Mixing up the
alphaparameters of different scikit-learn models. - Expecting exact coverage on small test sets. With 100 test rows, 74% or 86% can happen by chance.
Practice Exercises
Exercise 1. Change qr1.py to produce a 90% interval. Which quantiles do you need?
Show answer
Use 0.05 and 0.95. The range between them leaves 5% of outcomes below and 5% above, so it covers 90%.
for q in [0.05, 0.5, 0.95]:
models[q] = GradientBoostingRegressor(loss="quantile", alpha=q, n_estimators=200,
max_depth=2, random_state=0).fit(X_tr, y_tr)
Exercise 2. Score the 0.9 model from qr1.py on the test set.
Show answer
from sklearn.metrics import mean_pinball_loss
print(mean_pinball_loss(y_te, models[0.9].predict(X_te), alpha=0.9))
Frequently Asked Questions
Is a prediction interval the same as a confidence interval?
No. A confidence interval describes uncertainty about an average or a model parameter. A prediction interval describes where a single new outcome is likely to fall, so it is wider.
Can I get intervals without training extra models?
Yes. Conformal prediction wraps any regression model and builds intervals from its errors on held-out data. It gives coverage guarantees under mild assumptions. The MAPIE library implements it for scikit-learn models.
Summary
- Quantile regression predicts a percentile, not the average.
- Two quantile models (such as 0.1 and 0.9) make a prediction interval.
- Always check coverage on test data.
- The pinball loss is what pulls a model toward its quantile.
