Sub topic 7
Expected calibration error and its pitfalls
This chapter assumes you can already draw a reliability diagram, you know what log loss and Brier score measure, and you are comfortable with NumPy. Expected calibration error (ECE) compresses a reliability diagram into one number. That makes it convenient and also easy to misuse.
What ECE measures
A reliability diagram groups predictions into bins. In each bin it compares two numbers:
- Confidence: the mean predicted probability of the positive class.
- Accuracy: the observed fraction of positives (for binary problems, the positive rate).
If the model is calibrated, the two numbers match in every bin. ECE is the average gap between them, weighted by how many samples fall in each bin:
ECE = sum over bins b of (nb / n) × |accb − conf_b|
Here n_b is the number of samples in bin b and n is the total. A value of 0 means every bin matches exactly. A value of 0.05 means that, on average, predicted probabilities are off by five percentage points.
A reference implementation
This function uses equal-width bins on [0, 1]. Empty bins are skipped, because they have no samples to weight.
import numpy as np
def expected_calibration_error(y_true, y_prob, n_bins=10):
y_true = np.asarray(y_true)
y_prob = np.asarray(y_prob)
edges = np.linspace(0.0, 1.0, n_bins + 1)
bin_ids = np.digitize(y_prob, edges[1:-1], right=True)
ece = 0.0
for b in range(n_bins):
mask = bin_ids == b
if mask.any():
weight = mask.mean()
gap = abs(y_true[mask].mean() - y_prob[mask].mean())
ece += weight * gap
return ecenp.digitize with the interior edges and right=True returns an index from 0 to n_bins - 1. A probability of exactly 1.0 lands in the last bin, and a probability of 0.0 lands in the first.
For multiclass models, the usual variant is top-label ECE. Take the highest predicted probability as the confidence, and use "was the top class correct" (1 or 0) as the outcome. The same function then works on those two arrays.
Pitfall 1: ECE is not zero for a perfect model
Each bin's observed positive rate is a noisy estimate from a finite sample. Even when the true probabilities are exactly right, the bin averages wobble, and the absolute value turns every wobble into a positive contribution. ECE is therefore biased upward on small samples.
The next script simulates a perfectly calibrated model. It draws the true probability p for each sample and then draws the label from that probability.
import numpy as np
from calib_ece import expected_calibration_error # the function above, saved as calib_ece.py
rng = np.random.default_rng(0)
for n in (200, 2000, 100000):
p = rng.beta(2, 2, size=n)
y = (rng.random(n) < p).astype(int)
print(n, round(expected_calibration_error(y, p), 4))The model is calibrated by construction, yet ECE is clearly above zero at n = 200. It shrinks as n grows, and at n = 100,000 it is well under 0.01. A reported ECE of 0.03 on 300 test samples may be entirely sampling noise.
A practical remedy is a bootstrap. Resample the test set with replacement, recompute ECE each time, and report a percentile interval. If two models' intervals overlap heavily, you cannot say one is better calibrated.
Pitfall 2: the number depends on the binning
ECE changes with the number of bins and with how the bins are placed. You can see this by scoring one set of predictions at several bin counts.
import numpy as np
from calib_ece import expected_calibration_error
rng = np.random.default_rng(1)
n = 2000
p = rng.beta(2, 2, size=n)
y = (rng.random(n) < np.clip(p * 1.15, 0, 1)).astype(int) # mildly miscalibrated
for n_bins in (5, 10, 15, 20, 50):
print(n_bins, round(expected_calibration_error(y, p, n_bins), 4))Fewer bins average away local errors. More bins give each bin fewer samples, so noise grows and ECE rises. Neither choice is correct.
Equal-width bins also have a second problem. Many classifiers put most predictions near 0 or 1. Then a few bins hold nearly all the samples, and the middle bins have only a handful. Equal-mass (quantile) bins give every bin the same number of samples. They are what calibration_curve(..., strategy="quantile") uses. Quantile bins have uniform noise, but their widths vary, so a single bin can span a wide range of probabilities.
| Binning | Strength | Weakness |
|---|---|---|
| Equal width | Easy to explain, matches the usual diagram | Sparse bins give noisy gaps, dense bins hide variation |
| Equal mass | Same noise level in every bin | Wide bins can mix very different probabilities |
Pick one scheme and one bin count, and keep them fixed whenever you compare models or time periods. State both in your report.
Pitfall 3: a useless model can score perfectly
ECE only checks whether stated probabilities match observed frequencies. It says nothing about whether the model separates positives from negatives. A model that predicts the overall base rate for every sample is perfectly calibrated and has no discriminative power.
import numpy as np
from calib_ece import expected_calibration_error
rng = np.random.default_rng(2)
y = (rng.random(5000) < 0.3).astype(int)
p = np.full(5000, y.mean())
print(expected_calibration_error(y, p)) # 0.0All predictions fall in one bin, and that bin's confidence equals its accuracy. ECE is 0.0, and the model would have an AUC of 0.5. This is why ECE is not a proper scoring rule. Minimizing it does not lead to the best probabilistic model. Log loss and Brier score are proper: they reward calibration and sharpness together, so they penalize this constant predictor.
Pitfall 4: the absolute value hides direction
ECE sums absolute gaps, so overconfidence in one region and underconfidence in another do not cancel. That is intended, but it also means ECE cannot tell you which problem you have. Two models with the same ECE may need opposite fixes. Look at the signed gap per bin, or at the reliability diagram. Overconfident models have bins where conf > acc at high probabilities, and underconfident models show the reverse.
Pitfall 5: the average hides the worst bin
A weighted mean can be small while one region is badly wrong, especially if that region is rare. Maximum calibration error (MCE) takes the largest per-bin gap instead of the weighted average. It is also noisy, because small bins dominate it, so use it for diagnosis rather than ranking. In risk-sensitive settings, check the bins that drive decisions, such as the top bin used for a high-confidence automatic action.
Pitfall 6: multiclass ECE checks only one slice
Top-label ECE ignores the probabilities assigned to non-top classes. A model can have low top-label ECE while its second-choice probabilities are poor. If downstream code uses the full probability vector, compute a classwise ECE. Treat each class as a one-vs-rest binary problem, compute ECE for each, and average the results. This costs more samples per class, so the noise from Pitfall 1 gets worse for rare classes.
A practical reporting recipe
- Fix the bin count and binning scheme before looking at results.
- Compute ECE on data that was not used to train the model or fit the calibrator.
- Bootstrap the test set and report an interval, not a single value.
- Report Brier score or log loss and AUC next to it.
- Include the reliability diagram so readers can see where and in which direction the gaps lie.
When you compare a raw model with a calibrated one, a drop in ECE together with an unchanged or improved Brier score is good evidence. A drop in ECE with a worse Brier score is a warning that the calibrator may have flattened useful signal.
Exercise
A model scores ECE = 0.00 on a test set. A colleague says it is perfectly calibrated and ready to ship. Give two reasons ECE = 0.00 might not mean the model is good, and name one metric you would check next.
Show answer
First, ECE ignores discrimination. A model that predicts the base rate for every sample has ECE of 0 but cannot rank positives above negatives. Second, ECE depends on binning and on sample size. With very few bins, or with all predictions in one or two bins, gaps average out and the value can look better than the model deserves. Check a proper scoring rule such as Brier score or log loss (which would expose a constant predictor) and AUC for ranking quality. A reliability diagram with the bin counts also helps.
Exercise
You evaluate two models. Model A has ECE 0.021 on 400 test samples. Model B has ECE 0.034 on 40,000 test samples. Can you conclude A is better calibrated? What would you do?
Show answer
No. ECE is biased upward on small samples, so A's value is inflated by noise and B's much less so. The true gap between the models could be larger or smaller than it looks, and the sizes differ, so the numbers are not comparable. Evaluate both on the same test set, use the same binning, and bootstrap to get confidence intervals. Also compare Brier score or log loss, which are proper scoring rules.