Calibration: definition, reliability diagrams and proper scoring rules
The platform’s home lesson for calibration. Define precisely what classifier calibration means (binary, top-label, classwise and canonical), how to measure it (reliability diagrams, ECE and its biases), and why strictly proper scoring rules (log loss, Brier) reward both calibration and discrimination, as Murphy’s decomposition shows. Catalog the characteristic miscalibration signatures of model families studied in this module.
After this lesson you can
- Define perfect calibration P(Y = 1 | p̂(X) = p) = p and its multiclass variants (top-label, classwise and canonical).
- Build reliability diagrams using uniform and quantile binning and estimate ECE with bootstrap intervals.
- Explain binned ECE bias and dependence on bin count, and use alternatives such as bias-corrected ECE.
- Prove log loss and Brier are strictly proper scoring rules and decompose Brier into reliability, resolution and uncertainty.
- Recognize typical miscalibration signatures of Naive Bayes, SVM, boosting, Random Forest and modern networks.
Before you start
- 11Logistic regressionNaive BayesRandom forestAdaBoostSoft-margin SVMGradient boosting machineCost-sensitive decision thresholdStatistical functional elicited by a loss
- 07Logarithmic scoring ruleCross-entropyKullback-Leibler divergence (relative entropy)
- 05Nonparametric bootstrapBootstrap percentile and basic intervals
- 04Conditional expectation
Motivation: probabilities used as numbers
A classifier that only ranks well serves one purpose: putting more likely cases first. Many decisions need more because they use the value of probability, not its list position.
- Decisions with costs. In the metrics lesson you saw that if missing a positive costs and a false alarm , the expected-cost-minimizing rule flags a case when . The assumption was that is true probability. If the model says and is right 70% of the time, the correct threshold on its scale differs, and the rule applies the right number to the wrong scale.
- Capacity planning. A security team gets 400 daily alerts with probabilities of being real incidents. Their sum is the expected number to investigate. If the model is overconfident, staffing is wrong daily even with perfect queue order.
- Combining sources. Averaging two models’ probabilities, multiplying one detector’s by another’s, or passing the number to a risk system computing expected loss makes sense only if each means what it says.
- Measuring risk. In credit, medicine or an LLM saying “I am 95% confident,” the number itself is the consumed output.
Probabilities meaning what they say is called calibration. This lesson defines it precisely (also multiclass), teaches reliability diagrams and ECE while accounting for their biases, explains why log-loss and Brier reward both calibration and discrimination, and catalogs typical distortions of model families studied in this module. Correcting them (Platt, isotonic, temperature) is the next lesson.
Everything plotted and calculated comes from an explicit model you can simulate, or the cells that run it. Each case has true log-odds , label , and the classifier being evaluated reports
With and it reports true probability. With it exaggerates (log-odds stretch and probabilities move toward 0 and 1), with it undershoots and with shifts. Since is strictly increasing in , knowing is equivalent to knowing , so the truth to measure has closed form .
What calibration means
Two definition details matter. Conditioning is on , not : need not equal true probability for every , but among all cases assigned , 80% must be positive. Conditional expectation is the measure-theoretic conditional expectation, allowing continuous predictors without binning yet.
The most important consequence is that calibration is cheap.
Proof
with , so is a function of and the information it provides is contained in . By the tower property, .
∎Two extremes illustrate this. With constant , : always predicting prevalence is perfectly calibrated and distinguishes no cases. With identity, , the ideal predictor, also calibrated. Infinitely many calibrated predictors lie between, differing in information used. Calibration says whether numbers are honest; discrimination (or resolution) says how much cases are separated. They are separate axes: AUC depends only on score ordering, and any strictly increasing transformation of preserves it while breaking calibration. You will see this below.
The theorem also gives a repair recipe: if is its reliability curve, is calibrated (the theorem with ) and preserves ordering when is increasing. Estimating on unseen data is exactly what Platt scaling and isotonic regression do.
Multiple classes
With classes the predictor gives a simplex vector and several notions exist, from most to least demanding. Call the predicted class (with fixed tie-breaking).
- Canonical (or multiclass): for every . Among cases receiving the same vector, class frequencies match the whole vector.
- Classwise: for each , . These are binary “ versus rest” problems.
- Top-label (Gupta and Ramdas, 2022): .
- Confidence (Guo et al., 2017): . It only asks whether the predicted class is correct as often as its announced probability.
By the tower property canonical implies classwise calibration (conditioning on is conditioning on less than ) and top-label calibration, which implies confidence calibration. None of the implications reverses:
- Confidence without classwise calibration. A model always predicting when the true distribution is is correct exactly 60% of the time at confidence , but its class-2 occurs only 10%.
- Classwise and confidence, but not canonical. Three equally likely vectors , and have true distributions , and . For class 1, value appears only in the first and is satisfied; appears in the other two with frequencies and averaging . Likewise classes 2 and 3, and confidence is always with 60% accuracy. Yet no vector matches its true distribution.
In binary classification classwise and canonical coincide, while confidence is weaker: a model saying for cases with true frequency and for others with frequency gets the predicted class right at frequencies and , averaging confidence if groups have equal weight. Deep networks are often evaluated by confidence because with a thousand classes the others are almost impossible to estimate; when a decision uses a particular class probability (“malignant,” not most likely), classwise calibration matters.
Reliability diagrams
Curve cannot be estimated pointwise: with continuous predictions each value appears once. The classical solution from weather-forecast verification (DeGroot and Fienberg, 1983), popularized in machine learning by Niculescu-Mizil and Caruana, is binning.
Three things must be fixed.
- Bins. Uniform bins are used by Guo et al. and
calibration_curveby default; when predictions cluster near 0, most bins are nearly empty and a few contain everything. Quantile bins use quantiles of as edges and put cases in each: similar variance per point, at the cost of narrow bins where mass is high and wide tails. - Confidence histogram. Without it the diagram misleads: a point far from the diagonal with 12 cases weighs little, while a slightly displaced point with 3000 cases can dominate error. Guo et al. explicitly note that the diagram does not show bin counts.
- Noise. With cases, is a Bernoulli mean fluctuating on the order of even for a perfect model. Bröcker and Smith’s (2007) consistency bands show this: repeatedly simulate labels with the same predictions, assuming calibration, and mark bin-frequency 5th and 95th percentiles. A point outside its band is a deviation difficult to explain by chance.
The overconfident model’s shape resembles Naive Bayes: when it says the event occurs substantially more often, and when it says substantially less. The curve crosses the diagonal at because . For underconfidence it reverses into an S (left points below diagonal, right above), with histogram concentrated centrally: the maximum-margin signature seen below. For shifted predictions all points lie on the same side.
Measuring with one number: ECE and MCE
A diagram cannot be ranked or optimized. The natural scalar summary is mean distance between reliability curve and diagonal.
Guo et al. (2017) use uniform bins and give a percentage. ECE is useful and ubiquitous, but is an estimator with two biases of opposite sign worth understanding before comparing numbers.
Binning underestimates
What does estimate with infinite data? Each bin converges to and , so the limit is error of the binned version of the model, which predicts mean in each bin (Kumar, Liang and Ma, 2019):
Proof
By Jensen’s inequality applied to in each bin, . Multiply by and sum to obtain .
∎Loss arises from cancellation: if within a bin the model overpredicts in one part and underpredicts in another, their average looks calibrated. Kumar et al. construct distributions for any partition where the binned version has zero error and the model at least . In our overconfident model deviation changes sign only at , so the effect is small (calculated below): one bin measures only global calibration ; with even , is an edge so nothing cancels, recovering true value .
Few data per bin overestimate
Conversely, with finite , is the absolute value of a random variable and has positive expectation even when its mean is zero. For a calibrated model, conditional on predictions, has mean 0 and variance with . By the central limit theorem and ,
With equal-sized bins , this is : a perfect model’s ECE grows like . Doubling bins multiplies it by and four times the data are needed to restore it. An ECE is comparable only with one computed using the same bins and sample size, hence the interactive’s green curve rises with .
For squared error there is a classical weather-verification correction (Ferro and Fricker, 2012; Bröcker, 2012): subtract an estimate of frequency variance from each bin,
Kumar et al. (2019) prove for models already taking values that estimating with bounded relative error takes order samples with the direct estimator but only with the corrected one. For ECE there is no closed correction; they propose a heuristic based on a normal approximation. A bin-free alternative is smoothing: smECE (Błasiok and Nakkiran, ICLR 2024) estimates the reliability curve with a Gaussian kernel instead of bins and, with suitable bandwidth, gives a consistent measure that does not jump when the predictor changes slightly, unlike binned ECE.
Proper scoring rules
ECE is not the training measure or what should decide between models: always predicting prevalence has calibration error 0, like the ideal model. We seek a loss minimized only by telling the truth. This is the idea of a proper rule.
The important rules:
| Rule | Proper? | ||
|---|---|---|---|
| Logarithmic (log-loss) | if , if | strictly | |
| Brier (quadratic) | strictly | ||
| Spherical | , with and | strictly | |
| Absolute | no | ||
| 0-1 with threshold | or | yes, not strictly |
Log-loss is the logarithmic score (the logistic regression loss), and its excess over truth is KL divergence: , with equality only if (Gibbs’ inequality). Brier, for classes , is probability mean squared error, with excess ; you prove this in an exercise. Absolute loss is linear in , so its minimum is at an endpoint: with it pays to report . This is the median of the module’s first lesson: absolute loss elicits the median, 0 or 1 for a Bernoulli. And 0-1 is proper but not strict: it treats reporting and equally.
All proper rules have the same form
Call the minimum expected loss: the rule’s generalized entropy. For log-loss this is binary entropy; for Brier, .
Proof
For fixed , is affine. If is proper, is a minimum of affine functions and thus concave, and line lies above and touches at : a supertangent at with slope . Evaluating the line at gives . Conversely, in that form , because a concave function lies below its supertangents, with equality only at under strict concavity.
∎With and this gives , because . Binary entropy gives log-loss. Excess is the Bregman divergence of : for Brier and KL for log-loss.
Why a proper rule rewards calibration and discrimination
Now condition on prediction. If , given the label is and expected loss . Taking expectations,
and since is concave and , refinement is : problem uncertainty minus how much the model separates cases, which is by Jensen. A strictly proper rule penalizes both: miscalibration (zero only if ) and lack of information (refinement decreases as move away from ). It also shows why recalibrating with the true curve never worsens loss: is calibrated and has the same refinement, so its expected loss is .
ECE is not a scoring rule (it is not calculated case by case) and is not proper in a useful sense: it is 0 for constant prevalence and the ideal model, and may prefer the former over a slightly miscalibrated informative model. A cell below checks this.
Murphy decomposition
For Brier, the previous calculation has an exact data version when predictions take finitely many values, like weather forecasts issued in tenths. This is Murphy’s (1973) partition.
This Murphy decomposition separates three quantities:
- Reliability (meteorological terminology): mean squared distance between predictions and outcomes. It is empirical calibration error and should be small. Beware the name: high reliability is bad.
- Resolution: how far group frequencies are from the overall mean. It measures separation and should be large; it is subtracted. It does not depend on values, only how cases are grouped.
- Uncertainty: variance of . It does not depend on the model: it is the Brier score of always predicting .
The proof sums squares within groups; you reconstruct it in the guided exercise. In population, with reliability curve , this is the previous section’s calculation: .
Two practical cautions. First, if predictions are continuous and each value appears once, every “group” has , reliability is the entire Brier score and resolution equals uncertainty: the decomposition becomes trivial. Binning introduces two extra within-bin terms, prediction variance and covariance with labels (Stephenson, Coelho and Jolliffe, 2008):
with reliability and resolution calculated using and . Second, empirical reliability has the same upward bias as ECE, and Ferro and Fricker (2012) propose the same correction.
The figure shows the partition. Problem uncertainty is . With and the model is calibrated and separates well: resolution , Brier , AUC . The same model with ranks identically (same resolution and AUC) and pays reliability : Brier . The uninformative model is calibrated yet reaches , near constant prevalence because it resolves little (). Calibrated does not mean good, the lesson’s final common mistake.
Intact ranking, broken probabilities
AUC is the probability that a positive scores above a negative (ROC and AUC): it depends only on ordering. Any strictly increasing transformation of probabilities preserves it, and almost all break calibration. The next interactive lets you draw .
The lesson’s recurring distinction: AUC answers “does it rank well?” and calibration “do its numbers mean anything?” A model can have AUC and ECE (in the signatures cell AdaBoost has AUC and ECE ), and strictly increasing recalibration fixes the latter without changing the former. Proper rules measure both and therefore choose models when probabilities will be used.
Implementation from scratch
The cell implements reliability diagrams with uniform and quantile bins, ECE, MCE, bootstrap intervals, consistency bands, corrected squared error and stable log-loss, and validates against scikit-learn. Its bin convention matches calibration_curve: np.searchsorted(bordes[1:-1], p) puts a value exactly on an edge in the left bin.
import numpy as np
from scipy.special import expit, logit
MU, S = -0.5, 1.5
def muestra(n, gamma=1.0, delta=0.0, seed=0):
"""Z ~ N(MU, S²), Y ~ Bern(σ(Z)); el modelo reporta σ(γ Z + δ)."""
rng = np.random.default_rng(seed)
z = rng.normal(MU, S, n)
y = (rng.random(n) < expit(z)).astype(int)
return y, expit(gamma * z + delta)
def bordes(p, n_bins, strategy="uniform"):
if strategy == "uniform":
return np.linspace(0.0, 1.0, n_bins + 1)
return np.quantile(p, np.linspace(0.0, 1.0, n_bins + 1))
def curva_fiabilidad(y, p, n_bins=10, strategy="uniform"):
"""Confianza media, frecuencia observada y tamaño de cada bin no vacío."""
e = bordes(p, n_bins, strategy)
b = np.searchsorted(e[1:-1], p) # bins (e_k, e_k+1], el primero cerrado en 0
n_b = np.bincount(b, minlength=n_bins)
s_p = np.bincount(b, weights=p, minlength=n_bins)
s_y = np.bincount(b, weights=y, minlength=n_bins)
ok = n_b > 0
return s_p[ok] / n_b[ok], s_y[ok] / n_b[ok], n_b[ok]
def ece_mce(y, p, n_bins=10, strategy="uniform"):
conf, frec, n_b = curva_fiabilidad(y, p, n_bins, strategy)
hueco = np.abs(frec - conf)
return np.sum(n_b * hueco) / n_b.sum(), hueco.max()
def ce2(y, p, n_bins=10, strategy="uniform"):
"""Error cuadrático de calibración: estimador directo y corregido (Ferro y Fricker; Bröcker)."""
conf, frec, n_b = curva_fiabilidad(y, p, n_bins, strategy)
w = n_b / n_b.sum()
directo = np.sum(w * (frec - conf) ** 2)
m = n_b > 1
correccion = np.sum(w[m] * frec[m] * (1 - frec[m]) / (n_b[m] - 1))
return directo, directo - correccion
def ece_bootstrap(y, p, n_bins=10, reps=200, seed=0):
rng = np.random.default_rng(seed)
idx = rng.integers(0, len(y), (reps, len(y)))
return np.percentile([ece_mce(y[i], p[i], n_bins)[0] for i in idx], [5, 95])
def bandas_consistencia(p, n_bins=10, reps=500, seed=0):
"""Percentiles 5 y 95 de la frecuencia de cada bin si Y* ~ Bern(p), es decir, si p estuviera calibrada."""
rng = np.random.default_rng(seed)
b = np.searchsorted(bordes(p, n_bins)[1:-1], p)
n_b = np.bincount(b, minlength=n_bins)
ok = n_b > 0
sims = [np.bincount(b, weights=rng.random(len(p)) < p, minlength=n_bins)[ok] / n_b[ok] for _ in range(reps)]
return np.percentile(sims, [5, 95], axis=0)
def log_loss_estable(y, s):
"""Log-loss a partir de log-odds s: log(1 + e^{-s}) si y = 1 y log(1 + e^{s}) si y = 0, sin overflow."""
return np.mean(np.logaddexp(0.0, -(2 * y - 1) * s))
y, p = muestra(5000, gamma=2.5, seed=1)
conf, frec, n_b = curva_fiabilidad(y, p)
lo, hi = bandas_consistencia(p)
print("modelo sobreconfiado (γ = 2.5), n = 5000, 10 bins uniformes")
print(" conf frec n banda del 90 % si estuviera calibrado")
for c, f, k, a, b in zip(conf, frec, n_b, lo, hi):
print(f" {c:.3f} {f:.3f} {k:5d} [{a:.3f}, {b:.3f}]{' fuera' if not a <= f <= b else ''}")
ece, mce = ece_mce(y, p)
d, c = ce2(y, p)
ic = ece_bootstrap(y, p)
print(f"ECE = {ece:.4f} MCE = {mce:.4f} IC bootstrap del 90 %: [{ic[0]:.4f}, {ic[1]:.4f}]")
print(f"CE2: directo {np.sqrt(d):.4f}, corregido {np.sqrt(max(c, 0)):.4f}")
print(f"Brier = {np.mean((p - y) ** 2):.4f} log-loss = {log_loss_estable(y, logit(p)):.4f}")
y0, p0 = muestra(5000, seed=2)
ic0 = ece_bootstrap(y0, p0)
print(f"\nmodelo calibrado (verdad: 0): ECE = {ece_mce(y0, p0)[0]:.4f}, IC bootstrap del 90 %: [{ic0[0]:.4f}, {ic0[1]:.4f}]")Six of the overconfident model’s ten points lie outside their bands, and the four inside are between and near the curve’s diagonal crossing. Estimated ECE is close to true error because with 5000 cases and 10 bins upward bias is small relative to signal. The last line demonstrates the warning: the calibrated model has ECE of a few hundredths and its bootstrap interval excludes 0.
Now check against scikit-learn, which uses the same bin convention:
from sklearn.calibration import calibration_curve
from sklearn.metrics import brier_score_loss, log_loss
for strategy in ["uniform", "quantile"]:
frec_sk, conf_sk = calibration_curve(y, p, n_bins=10, strategy=strategy)
c2, f2, _ = curva_fiabilidad(y, p, 10, strategy)
print(f"{strategy:8s}: coincide con calibration_curve: {np.allclose(frec_sk, f2) and np.allclose(conf_sk, c2)}")
print("Brier coincide:", np.isclose(np.mean((p - y) ** 2), brier_score_loss(y, p)))
print("log-loss coincide:", np.isclose(log_loss_estable(y, logit(p)), log_loss(y, p)))
# la log-loss desde probabilidades redondeadas a 1 explota; desde log-odds, no
s = np.array([40.0, -40.0])
print("desde log-odds:", log_loss_estable(np.array([0, 1]), s), " desde probabilidades:", -np.mean(np.log(1 - expit(s[:1]))))calibration_curve returns observed frequency first and mean confidence second, omitting empty bins. The last line shows why log-loss is computed from log-odds: rounds to 1 in floating point, and , whereas is representable. scikit-learn receives probabilities and clips them at using the data type’s epsilon.
ECE bias, measured
The next cell repeats ECE measurement 200 times on a perfectly calibrated model for three sample sizes and three bin counts, comparing with approximation and direct and corrected squared error. It then calculates in population by quadrature the binned overconfident model’s error.
print("modelo calibrado: media de 200 repeticiones (verdad = 0)")
print(" n B ECE medio aproximación CE2 directo CE2 corregido")
for n in [250, 1000, 4000]:
for B in [5, 15, 50]:
e, ap, d2, c2 = [], [], [], []
for r in range(200):
y_, p_ = muestra(n, seed=10_000 * n + 100 * B + r)
e.append(ece_mce(y_, p_, B)[0])
b = np.searchsorted(np.linspace(0, 1, B + 1)[1:-1], p_)
nb = np.bincount(b, minlength=B)
v = np.bincount(b, weights=p_ * (1 - p_), minlength=B)
ok = nb > 0
ap.append(np.sum(np.sqrt(2 / np.pi * v[ok])) / n)
dd, cc = ce2(y_, p_, B)
d2.append(dd); c2.append(cc)
print(f" {n:5d} {B:4d} {np.mean(e):.4f} {np.mean(ap):.4f} {np.sqrt(np.mean(d2)):.4f} {np.sqrt(max(np.mean(c2), 0)):.4f}")
# agrupar subestima: versión agrupada del sobreconfiado (γ = 2.5), por cuadratura
z = np.linspace(MU - 8 * S, MU + 8 * S, 20001)
w = np.exp(-0.5 * ((z - MU) / S) ** 2); w /= w.sum()
q, pz = expit(2.5 * z), expit(z)
print(f"\nsobreconfiado: error verdadero E|r(p̂) - p̂| = {np.sum(w * np.abs(q - pz)):.4f}")
for B in [1, 2, 5, 10, 15, 30]:
b = np.searchsorted(np.linspace(0, 1, B + 1)[1:-1], q)
print(f" B = {B:2d}: error de la versión agrupada = {np.sum(np.abs(np.bincount(b, weights=w * (q - pz), minlength=B))):.4f}")Approximation (in code sqrt(2/π · v_b), since v already sums ) matches every row. With and a perfect model shows ECE , and even with 4000 cases and 15 bins . Going from to multiplies ECE by about 3 as predicts. Corrected squared error drastically reduces bias ( to with 1000 cases and 50 bins), though not always eliminating it. Below is the binned overconfident model: one bin sees only global calibration ; with bin contains the crossing and loses some; even recovers truth.
Proper rules in numbers
q = np.linspace(0.001, 0.999, 999)
reglas = {
"log": lambda q, y: -np.log(np.where(y == 1, q, 1 - q)),
"Brier": lambda q, y: (y - q) ** 2,
"esférica": lambda q, y: 1 - np.where(y == 1, q, 1 - q) / np.hypot(q, 1 - q),
"absoluta": lambda q, y: np.abs(y - q),
"0-1": lambda q, y: ((q >= 0.5) != y).astype(float),
}
print("minimizadores de E[S(q, Y)] con Y ~ Bern(p), en una rejilla de paso 0.001")
print(" p " + "".join(f"{k:>15s}" for k in reglas))
for p_ in [0.1, 0.3, 0.7, 0.9]:
fila = []
for S_ in reglas.values():
esp = p_ * S_(q, 1) + (1 - p_) * S_(q, 0)
mins = q[np.isclose(esp, esp.min(), rtol=0, atol=1e-12)]
fila.append(f"{mins[0]:.3f}" if len(mins) == 1 else f"[{mins[0]:.3f}, {mins[-1]:.3f}]")
print(f" {p_:.1f} " + "".join(f"{s:>15s}" for s in fila))
H = {"Brier": (lambda q: q * (1 - q), lambda q: 1 - 2 * q),
"log": (lambda q: -q * np.log(q) - (1 - q) * np.log(1 - q), lambda q: np.log((1 - q) / q))}
for k, (h, dh) in H.items():
err = max(np.max(np.abs(h(q) + dh(q) * (y_ - q) - reglas[k](q, y_))) for y_ in (0, 1))
print(f"{k:5s}: máx |H(q) + H'(q)(y - q) - S(q, y)| = {err:.1e}")
# el ECE no es una regla propia
y_tr, _ = muestra(100_000, seed=3)
y4, p4 = muestra(20_000, seed=4)
_, p4_sc = muestra(20_000, gamma=2.5, seed=4)
print("\n ECE (15 bins) Brier log-loss")
for nombre, pr in [("verdad σ(z)", p4), ("sobreconfiado γ = 2.5", p4_sc), ("constante = prevalencia", np.full(len(y4), y_tr.mean()))]:
print(f" {nombre:24s} {ece_mce(y4, pr, 15)[0]:.4f} {np.mean((pr - y4) ** 2):.4f} {log_loss_estable(y4, logit(pr)):.4f}")The minimizer table reproduces the earlier one: all three strictly proper rules hit exactly, absolute goes to an extreme and 0-1 accepts half an interval. Savage representation holds to rounding. The last table is the important example: by ECE constant prevalence () looks as good as truth () and much better than the overconfident model (); by Brier and log-loss the constant is worst, and the overconfident model, ranking exactly like truth, lies between.
Murphy, exact and binned
def murphy(y, p, grupos):
"""Fiabilidad, resolución, incertidumbre y los dos términos dentro de cada grupo."""
n = len(y)
_, g = np.unique(grupos, return_inverse=True)
n_k = np.bincount(g)
f_k = np.bincount(g, weights=p) / n_k
o_k = np.bincount(g, weights=y) / n_k
obar = y.mean()
fiab = np.sum(n_k * (f_k - o_k) ** 2) / n
resol = np.sum(n_k * (o_k - obar) ** 2) / n
incert = obar * (1 - obar)
var_intra = np.sum((p - f_k[g]) ** 2) / n
cov_intra = np.sum((p - f_k[g]) * (y - o_k[g])) / n
return fiab, resol, incert, var_intra, cov_intra
y5, p5 = muestra(10_000, gamma=2.5, seed=5)
brier = lambda pr: np.mean((pr - y5) ** 2)
p_dec = np.round(p5, 1) # predicciones en décimas, como un parte meteorológico
f, r, u, v, c = murphy(y5, p_dec, p_dec)
print(f"décimas: Brier {brier(p_dec):.5f} = {f:.5f} - {r:.5f} + {u:.5f} = {f - r + u:.5f}")
bins = np.searchsorted(np.linspace(0, 1, 11)[1:-1], p5)
f, r, u, v, c = murphy(y5, p5, bins)
print(f"continuas, 10 bins: Brier {brier(p5):.5f}; fiab - resol + incert = {f - r + u:.5f};"
f" + var {v:.5f} - 2 cov {2 * c:.5f} = {f - r + u + v - 2 * c:.5f}")
f, r, u, v, c = murphy(y5, p5, p5)
print(f"un grupo por valor: fiabilidad {f:.4f} (el Brier entero), resolución {r:.4f} = incertidumbre {u:.4f}")With predictions in tenths the identity is exact. With continuous predictions grouped in 10 bins, the three classical terms yield rather than , and the two within-bin terms close the difference. With one group per value the decomposition degenerates: all loss is “reliability” and resolution equals uncertainty.
Multiple classes
On digits (10 classes), with Naive Bayes and heavily regularized logistic regression, the cell calculates Guo’s confidence ECE (15 bins) and classwise ECE, the mean of ten binary versus ECEs.
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
def ece_confianza(y, P, n_bins=15):
"""¿Acierta la clase predicha con la frecuencia que anuncia su probabilidad?"""
return ece_mce((P.argmax(1) == y).astype(int), P.max(1), n_bins)[0]
def ece_por_clase(y, P, n_bins=15):
"""Media sobre clases del ECE binario de p_k frente a 1[y = k]."""
return np.mean([ece_mce((y == k).astype(int), P[:, k], n_bins)[0] for k in range(P.shape[1])])
Xd, yd = load_digits(return_X_y=True)
Xd_tr, Xd_te, yd_tr, yd_te = train_test_split(Xd, yd, test_size=0.5, stratify=yd, random_state=0)
for nombre, m in [("Naive Bayes gaussiano", GaussianNB()),
("logística, C = 0.1", make_pipeline(StandardScaler(), LogisticRegression(C=0.1, max_iter=2000)))]:
P = m.fit(Xd_tr, yd_tr).predict_proba(Xd_te)
print(f"{nombre:22s} exactitud {np.mean(P.argmax(1) == yd_te):.3f} confianza media {P.max(1).mean():.3f} "
f"ECE de confianza {ece_confianza(yd_te, P):.3f} ECE por clase {ece_por_clase(yd_te, P):.4f}")The models are miscalibrated in opposite directions. Naive Bayes is overconfident: mean confidence with accuracy , as in the generative classifiers lesson. Logistic with is underconfident: accuracy % with mean confidence , because the penalty shrinks weights and log-odds. Classwise ECE is much smaller for both, not because they are better calibrated: nine of ten class probabilities are near 0 and easy to predict, diluting the mean. Calibration figures of different definitions are not comparable.
Miscalibration signatures by family
Niculescu-Mizil and Caruana (2005) compared probabilities from ten model families on eight binary problems, with 4000 training cases, 1000 independent calibration cases and large test sets. Their reliability diagrams (10 uniform bins) show characteristic distortions, miscalibration signatures:
- Maximum-margin methods (boosted trees, boosted stumps and SVM) push predictions away from 0 and 1: the histogram concentrates centrally and the diagram is sigmoid. Boosted trees showed this on seven of eight problems (in the eighth boosting stopped after four iterations due to overfitting), boosted stumps most extremely. SVM outputs, not probabilities, were rescaled to with .
- Naive Bayes has the opposite bias: pushes predictions toward 0 and 1, because independence counts the same evidence repeatedly.
- Neural networks, bagged trees and logistic regression were initially well calibrated and subsequent calibration did not improve them (slightly worsening networks).
- Random Forest was least clear: well calibrated on some problems, and in others a milder version of margin methods’ tendency. Their explanation: an average of high-variance trees predicts 0 only if all trees predict 0, so variance errors near extremes are one-sided and pull the mean toward center.
After Platt or isotonic calibration boosted trees, random forests and SVMs were best: distortion was systematic and thus correctable.
Twelve years later Guo et al. (2017) found modern deep networks no longer behaved like 2005’s small networks: they are overconfident. On CIFAR-100, a five-layer LeNet had ECE % with error %, while a 110-layer ResNet had ECE % with error % (15 bins; paper tables 1 and S2). More accurate and much worse calibrated. They associated deterioration with depth, width, batch normalization and less weight decay without claiming causality, and observed overfitting appears in log-likelihood before classification error: the network keeps reducing training log-loss by becoming more confident. One-parameter temperature scaling reduced % to %.
The mechanisms match what you know of each model:
- Naive Bayes adds log-likelihood ratios of correlated features as if independent (Naive Bayes): with copies of one feature, its log-odds contribution multiplies by . This is in the lesson’s model.
- AdaBoost (boosting) gives weighted vote with . In population exponential loss pushes it toward (exponential loss), but a finite weak-learner vote ending by fitting margin is not on that scale. scikit-learn’s
predict_probaalso returns with : vote is normalized to before sigmoid, so all probabilities lie between and (the cell checks). - SVM (soft margin) produces distance from boundary; linearly rescaled to it is not a probability, and hinge loss elicits only the sign of .
- Random Forest (random forest) averages tree votes: the one-sided-variance argument.
- Gradient boosting with log-loss (gradient boosting) and logistic regression minimize a strictly proper rule. This does not guarantee calibration (finite data, regularization or misspecification cause deviations), but points the right way. Logistic regression with intercept also has an exact property: at optimum the intercept derivative vanishes and on training data, global calibration.
Lab: signatures at smaller scale
Reproduce the study on one synthetic problem: make_classification with 20 features (5 informative, 10 redundant linear combinations, 2 clusters per class and 5% flipped labels), 4000 training cases as in the paper and 4000 for measurement. Models use module defaults except where specified. The SVM has RBF kernel and its decision_function is rescaled with as Niculescu-Mizil and Caruana did.
from sklearn.datasets import make_classification
from sklearn.svm import SVC
from sklearn.metrics import roc_auc_score
X, y = make_classification(n_samples=8000, n_features=20, n_informative=5, n_redundant=10,
n_clusters_per_class=2, flip_y=0.05, class_sep=0.8, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, train_size=4000, random_state=0)
proba, exactitud = {}, {}
for nombre, m in [("logística", LogisticRegression(max_iter=1000)), ("Naive Bayes", GaussianNB())]:
m.fit(X_tr, y_tr)
proba[nombre], exactitud[nombre] = m.predict_proba(X_te)[:, 1], m.score(X_te, y_te)
svm = SVC(kernel="rbf", C=1.0).fit(X_tr, y_tr)
d = svm.decision_function(X_te)
proba["SVM (reescalado)"], exactitud["SVM (reescalado)"] = (d - d.min()) / (d.max() - d.min()), svm.score(X_te, y_te)
for k in proba:
print(f"{k:18s} exactitud {exactitud[k]:.3f} AUC {roc_auc_score(y_te, proba[k]):.3f}")from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(n_estimators=100, random_state=0).fit(X_tr, y_tr)
proba["Random Forest"], exactitud["Random Forest"] = rf.predict_proba(X_te)[:, 1], rf.score(X_te, y_te)
print(f"Random Forest exactitud {exactitud['Random Forest']:.3f} AUC {roc_auc_score(y_te, proba['Random Forest']):.3f}")from sklearn.ensemble import AdaBoostClassifier
ada = AdaBoostClassifier(n_estimators=200, random_state=0).fit(X_tr, y_tr) # 200 stumps potenciados
pa = ada.predict_proba(X_te)[:, 1]
proba["AdaBoost (stumps)"], exactitud["AdaBoost (stumps)"] = pa, ada.score(X_te, y_te)
print(f"AdaBoost (stumps) exactitud {exactitud['AdaBoost (stumps)']:.3f} AUC {roc_auc_score(y_te, pa):.3f}")
print(f"probabilidades entre {pa.min():.3f} y {pa.max():.3f}")
# predict_proba es σ(2 F / Σ α) en binario, con F = Σ α_m h_m y h_m = ±1: nunca sale de [σ(-2), σ(2)]
F = sum(a * (2 * h.predict(X_te) - 1) for a, h in zip(ada.estimator_weights_, ada.estimators_))
print("coincide con σ(2 F / Σ α):", np.allclose(pa, expit(2 * F / ada.estimator_weights_.sum())))from sklearn.ensemble import GradientBoostingClassifier
gb = GradientBoostingClassifier(n_estimators=100, random_state=0).fit(X_tr, y_tr)
proba["gradient boosting"], exactitud["gradient boosting"] = gb.predict_proba(X_te)[:, 1], gb.score(X_te, y_te)
print(f"gradient boosting exactitud {exactitud['gradient boosting']:.3f} AUC {roc_auc_score(y_te, proba['gradient boosting']):.3f}")import matplotlib.pyplot as plt
from sklearn.calibration import CalibrationDisplay
print(" AUC ECE fiab. resol. incert. Brier log-loss % fuera de [0.1, 0.9]")
for k, pr in proba.items():
b = np.searchsorted(np.linspace(0, 1, 11)[1:-1], pr)
f, r, u, v, c = murphy(y_te, pr, b)
ll = log_loss(y_te, np.clip(pr, 1e-6, 1 - 1e-6))
print(f"{k:18s} {roc_auc_score(y_te, pr):.3f} {ece_mce(y_te, pr)[0]:.3f} {f:.4f} {r:.4f} {u:.4f} "
f"{np.mean((pr - y_te) ** 2):.4f} {ll:.4f} {100 * np.mean((pr < 0.1) | (pr > 0.9)):.0f}")
print("\nbins uniformes (conf, frec, n) para la galería:")
for k, pr in proba.items():
conf, frec, n_b = curva_fiabilidad(y_te, pr)
print(k, np.round(conf, 3).tolist(), np.round(frec, 3).tolist(), n_b.tolist())
fig, axes = plt.subplots(2, 3, figsize=(11, 7), sharex=True, sharey=True)
for ax, (k, pr) in zip(axes.ravel(), proba.items()):
CalibrationDisplay.from_predictions(y_te, pr, n_bins=10, ax=ax, name=k)
ax.set_title(k); ax.get_legend().remove()
plt.tight_layout(); plt.show()What emerges model by model, and what it means:
- Naive Bayes reproduces the textbook signature: 81% of predictions are outside , and intermediate-bin frequency is far from confidence (says , occurs %). It ranks well (AUC ) and pays reliability .
- AdaBoost is opposite: all probabilities lie between and despite near-best discrimination (AUC ). ECE and reliability make it the worst probability in the group with one of the best rankings. This is the high-AUC, high-ECE exercise case.
- Rescaled SVM: same sigmoid (says , occurs %; says , occurs %), with central mass.
- Random Forest: mild symmetric sigmoid (says , occurs %; says , occurs %), as in the problems where Niculescu-Mizil and Caruana saw it avoid extremes.
- Logistic regression: also a mild sigmoid, absent in the paper. Here the problem has two clusters per class and a nonlinear boundary, so the model is misspecified: it cannot express true probability, and its prediction is the closest log-loss projection onto a linear family. Minimizing a proper rule is insufficient if the model cannot contain the answer.
- Gradient boosting with log-loss: best calibrated (ECE , reliability ) and best Brier alongside forest. Unlike 2005 boosting it minimizes a strictly proper rule in function space.
The resolution column confirms Murphy: AdaBoost’s , measured with only four occupied bins, already exceeds logistic and Naive Bayes . AdaBoost knows more than those models; reliability hurts it, precisely what monotonic recalibration removes. This matches the paper: calibrated margin methods are among the best.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 3. How do you start?
Step 1 of 3. How do you treat the sum inside group ?
expected_calibration_error(y, p, n_bins=10, strategy='uniform'), returning ECE as a float. With strategy='uniform' edges are np.linspace(0, 1, n_bins + 1); with 'quantile', np.quantile(p, np.linspace(0, 1, n_bins + 1)). A value goes to bin np.searchsorted(bordes[1:-1], p), the calibration_curve convention (bins are and the first includes 0). Empty bins contribute nothing and must produce no warnings or nan.import numpy as np
def expected_calibration_error(y, p, n_bins=10, strategy="uniform"):
y = np.asarray(y, dtype=float)
p = np.asarray(p, dtype=float)
# tu código: bordes, índice de bin, recuentos y sumas por bin (np.bincount ayuda)
return 0.0Summary
- Binary calibration is . Multiclass canonical calibration implies classwise and top-label, and top-label implies confidence; no implication reverses.
- Reliability diagrams group predictions and compare mean confidence with observed frequency. They need a histogram and consistency bands to avoid reading noise.
- ECE has two biases: binning underestimates (Jensen) and few observations per bin overestimate (grows like for a perfect model). Compare ECE only with identical bins and data; corrected squared error reduces the second bias.
- Log-loss, Brier and spherical are strictly proper; absolute is not, 0-1 is not strict, and ECE is not a scoring rule. Every binary proper rule is with concave .
- Murphy: Brier = reliability − resolution + uncertainty. A monotonic distortion only changes reliability; information changes resolution.
- Signatures: Naive Bayes and modern deep networks toward extremes; margin boosting and SVM toward center in a sigmoid; Random Forest mildly toward center; logistic and gradient boosting with log-loss near the diagonal when well specified. All are monotonic and corrected by recalibration.