Expected calibration error
Problem
Use n_bins equal-width bins over [0, 1], with bin index min(floor(p·n_bins), n_bins − 1). Return ECE = Σ_b (|b|/N)·|accuracy_b − mean_confidence_b| over non-empty bins, where accuracy is the mean label in the bin.
Signature
def expected_calibration_error(y_true: list[int], probs: list[float], n_bins: int = 10) -> float: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> close(expected_calibration_error([1, 0], [1.0, 0.0], 10), 0.0)
True
>>> close(expected_calibration_error([1, 1, 0, 0], [0.9, 0.9, 0.9, 0.9], 10), 0.4)
TrueHints
Equal-width bins over [0, 1]; bin index = min(floor(p * n_bins), n_bins - 1).
ECE = sum over non-empty bins of (|b|/N) * |accuracy_b - mean_confidence_b|.
accuracy is the mean label in the bin; skip empty bins; bin index must not overflow.
Reference solution
from collections import defaultdict
def expected_calibration_error(y_true, probs, n_bins=10):
N = len(y_true)
bins = defaultdict(list)
for y, p in zip(y_true, probs):
b = min(int(p * n_bins), n_bins - 1)
bins[b].append((y, p))
e = 0.0
for lst in bins.values():
acc = sum(y for y, _ in lst) / len(lst)
conf = sum(p for _, p in lst) / len(lst)
e += abs(acc - conf) * len(lst) / N
return eWhat a strong solution covers
- Bins p = 1.0 into the last bin.
- Weights bins by count; skips empty bins.
- Discusses equal-mass bins, ECE’s sensitivity to binning, the Brier score, and post-hoc calibration.
Common mistakes
- p = 1.0 indexing out of range
- unweighted averaging across bins.