Say a grocery chain orders bread for each store every evening. Running out of bread at 5 p.m. costs more than throwing away a few unsold loaves, so the planner does not want the average forecast. She wants a number that covers demand on 9 days out of 10. Mean squared error cannot tell her whether a model does that job well. Quantile loss can.
Quantile loss, also called pinball loss, is the error measure for forecasts of a percentile. It charges a different price for predicting too low and predicting too high, and the ratio between the two prices is set by the quantile you are aiming for. A model that minimizes the 0.9 quantile loss learns to predict the 90th percentile. This article gives the formula, works through it by hand, and shows how to compute it and train models with it in NumPy and scikit-learn.
Key Takeaways
- Quantile loss scores a prediction of the tau-th quantile. Under-predictions cost tau per unit of error and over-predictions cost (1 – tau) per unit.
- At tau = 0.9, being 10 units too low costs 9, while being 10 units too high costs 1. That asymmetry pushes the model up to the 90th percentile.
- At tau = 0.5, quantile loss is exactly half the mean absolute error, so the best prediction is the median.
- Always compare models with the loss at the same tau they were trained for. A median model scored at tau = 0.9 looks much worse than a model trained for 0.9.
- Check coverage too: about 90% of actual values should fall below a good 0.9 quantile forecast.
What Is Quantile Loss?
A quantile is the value below which a given share of outcomes falls. The 0.9 quantile of daily bread demand is the number of loaves that demand stays at or below on 90% of days. Quantile regression predicts that value instead of the mean.
Quantile loss is the loss function that makes quantile regression work. For one observation with actual value y, prediction q and quantile level tau between 0 and 1:
L_tau(y, q) = tau * (y - q) if y >= q (prediction too low)
L_tau(y, q) = (1 - tau) * (q - y) if y < q (prediction too high) The same thing written in one line is max(tau * (y - q), (tau - 1) * (y - q)). Across a dataset you average the per-row losses. That average is what scikit-learn reports as the mean pinball loss. The name comes from the shape of the loss when you plot it against the error: two straight lines meeting at zero, with different slopes, like the path of a ball bouncing off a pinball flipper.
The idea goes back to Roger Koenker and Gilbert Bassett, who introduced regression quantiles in 1978. It is now standard in demand forecasting, energy load forecasting and any setting where you need a range rather than a single number.
A Worked Example by Hand
Take the bread planner’s model. It predicts 100 loaves for four different days, and it is a 0.9 quantile model, so tau = 0.9. Here is what actually sold and what each day costs under quantile loss:
| Day | Actual (y) | Prediction (q) | Error y – q | Loss at tau = 0.9 |
|---|---|---|---|---|
| 1 | 110 | 100 | +10 (too low) | 0.9 x 10 = 9.0 |
| 2 | 90 | 100 | -10 (too high) | 0.1 x 10 = 1.0 |
| 3 | 100 | 100 | 0 | 0.0 |
| 4 | 130 | 100 | +30 (too low) | 0.9 x 30 = 27.0 |
The mean quantile loss is (9 + 1 + 0 + 27) / 4 = 9.25. Look at days 1 and 2. Both predictions are off by 10 loaves, but running short costs nine times as much as baking too many. The only way for a model to keep this loss low is to aim high enough that shortfalls are rare, which is exactly what a 90th percentile forecast should do.
Now set tau = 0.5. Both directions cost 0.5 per unit, so the four losses are 5, 5, 0 and 15, and the mean is 6.25. That is half of the mean absolute error (25 / 4 = 6.25). This is why a model trained with quantile loss at tau = 0.5 predicts the median.
Computing Quantile Loss in Python
The formula takes one line in NumPy. scikit-learn ships the same metric as mean_pinball_loss, where the quantile level is called alpha (default 0.5). The code below checks both against the hand calculation:
import numpy as np
from sklearn.metrics import mean_pinball_loss
def pinball_loss(y_true, y_pred, tau):
"""Average quantile (pinball) loss for quantile level tau."""
diff = np.asarray(y_true) - np.asarray(y_pred)
return np.mean(np.maximum(tau * diff, (tau - 1) * diff))
y_true = np.array([110, 90, 100, 130])
y_pred = np.array([100, 100, 100, 100])
print("NumPy tau=0.9:", pinball_loss(y_true, y_pred, 0.9))
print("sklearn tau=0.9:", mean_pinball_loss(y_true, y_pred, alpha=0.9))
print("NumPy tau=0.5:", pinball_loss(y_true, y_pred, 0.5))
print("MAE / 2 :", np.mean(np.abs(y_true - y_pred)) / 2) Output:
NumPy tau=0.9: 9.25
sklearn tau=0.9: 9.25
NumPy tau=0.5: 6.25
MAE / 2 : 6.25 Both implementations match the table: 9.25 at tau = 0.9 and 6.25 at tau = 0.5, which equals half the mean absolute error. Writing the NumPy version once is useful when you need the loss inside a custom training loop or a deep learning framework.
Training a Quantile Model With scikit-learn
Scoring is half the story. You can also train a model to minimize quantile loss directly. In scikit-learn, GradientBoostingRegressor(loss="quantile", alpha=tau) does this, and so do HistGradientBoostingRegressor(loss="quantile", quantile=tau) and the linear QuantileRegressor. The example below builds data where the noise grows with x, which is common in real demand data: bigger stores have bigger swings. It fits one model each for the 10th, 50th and 90th percentiles.
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_pinball_loss
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=(2000, 1))
# The noise grows with x, so the spread of y is not constant.
y = 5 * X[:, 0] + rng.normal(0, 1 + X[:, 0], size=2000)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
models = {}
for tau in (0.1, 0.5, 0.9):
models[tau] = GradientBoostingRegressor(
loss="quantile", alpha=tau, n_estimators=200, max_depth=3, random_state=0
).fit(X_train, y_train)
for tau, model in models.items():
pred = model.predict(X_test)
below = np.mean(y_test <= pred)
print(f"tau={tau}: pinball={mean_pinball_loss(y_test, pred, alpha=tau):.3f}, "
f"share of y below prediction={below:.2f}")
# A single model trained for the median, scored at tau=0.9
median_pred = models[0.5].predict(X_test)
print(f"median model scored at tau=0.9: "
f"{mean_pinball_loss(y_test, median_pred, alpha=0.9):.3f}") Output (scikit-learn 1.9):
tau=0.1: pinball=1.049, share of y below prediction=0.10
tau=0.5: pinball=2.485, share of y below prediction=0.49
tau=0.9: pinball=1.082, share of y below prediction=0.90
median model scored at tau=0.9: 2.779 Three things stand out:
- Coverage matches the target. 10% of test values fall below the 0.1 model, 49% below the median model and 90% below the 0.9 model. That is the real-world check that a quantile model is doing its job.
- Losses at different tau values are not comparable. The median model has the highest loss (2.485), but that does not make it the worst model. Losses at tau = 0.1 and 0.9 are naturally lower because one side of each error is weighted by only 0.1.
- The wrong model loses at the right tau. Scored at tau = 0.9, the median model gets 2.779 against 1.082 for the model trained for 0.9. If the planner used the median forecast, she would run short on about half of all days.
The 0.1 and 0.9 models together give an 80% prediction interval. scikit-learn’s own prediction intervals for gradient boosting example shows the same approach with a plot and hyperparameter tuning for each quantile.
When Should You Use Quantile Loss?
Use it whenever the cost of an error depends on its direction, or when you need a range instead of one number:
- Inventory and staffing. If a shortfall costs more than surplus, forecast a high quantile. The right tau comes from the ratio of costs: if being short costs 9 times as much as being over, the cost-minimizing order is the 9 / (9 + 1) = 0.9 quantile.
- Prediction intervals. Train a low and a high quantile model to show a likely range, as in the example above.
- Forecast evaluation. Probabilistic forecasting tools often report pinball loss averaged over several quantiles, which rewards forecasts that are sharp and calibrated at the same time.
Two cautions apply. Models trained separately for each quantile can cross, for example a 0.9 prediction that dips below the 0.5 prediction for some inputs. Check for this and sort the predictions if needed. And a low loss on its own does not prove calibration, so always look at coverage on held-out data. If you need a reference point first, compare against a simple baseline such as the training-set quantile for every row, the same idea as a dummy classifier for classification. For uncertainty around a single metric rather than a prediction, resampling methods like the Poisson bootstrap answer a different question.
Back to the Bread Order
The planner from the opening now has a clear rule. She trains the demand model with quantile loss at tau = 0.9, compares candidate models with mean_pinball_loss(alpha=0.9), and checks that roughly 90% of held-out days sell at or below the forecast. If running short turns out to cost even more than she thought, she raises tau and retrains. The metric finally matches the decision she has to make every evening.
Frequently Asked Questions
Is Quantile Loss the Same as Pinball Loss?
Yes. Quantile loss, pinball loss and check loss are names for the same function. scikit-learn calls it mean_pinball_loss, and libraries such as LightGBM and XGBoost expose it as a “quantile” objective.
What Value of Tau Should I Use?
Pick tau from the decision, not from habit. If an under-prediction costs a per unit and an over-prediction costs b per unit, the cost-minimizing forecast is the a / (a + b) quantile. For intervals, use pairs such as 0.05 and 0.95 for a 90% range.
How Is Quantile Loss Related to MAE?
At tau = 0.5, quantile loss equals half the mean absolute error, so both are minimized by the same prediction: the median. For any other tau, the two slopes differ and the best prediction moves toward the chosen percentile.
Can I Use Quantile Loss in Deep Learning?
Yes. The one-line NumPy formula translates directly to PyTorch or TensorFlow, and it is differentiable everywhere except at zero error, which gradient-based training handles fine. A common setup is one network with several outputs, each trained with the loss at a different tau.




