Module contents
Lesson 21 of 24Core 100 min

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

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 cFNc_{FN} and a false alarm cFPc_{FP}, the expected-cost-minimizing rule flags a case when p^(x)≥cFP/(cFP+cFN)\hat p(\vb{x}) \ge c_{FP}/(c_{FP} + c_{FN}). The assumption was that p^(x)\hat p(\vb{x}) is true probability. If the model says 0.90.9 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 ∑ip^i exposicioˊni\sum_i \hat p_i\,\text{exposición}_i makes sense only if each p^\hat p 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 Z∼N(−0.5, 1.52)Z \sim \Normal(-0.5,\ 1.5^2), label Y∣Z∼Bern⁡(σ(Z))Y \mid Z \sim \Bern(\sigmoid(Z)), and the classifier being evaluated reports

p^=σ(γZ+δ).\hat p = \sigmoid(\gamma Z + \delta).

With γ=1\gamma = 1 and δ=0\delta = 0 it reports true probability. With γ>1\gamma > 1 it exaggerates (log-odds stretch and probabilities move toward 0 and 1), with γ<1\gamma < 1 it undershoots and with δ≠0\delta \neq 0 shifts. Since p^\hat p is strictly increasing in ZZ, knowing p^\hat p is equivalent to knowing ZZ, so the truth to measure has closed form P(Y=1∣p^)=σ(Z)=σ((logit⁡p^−δ)/γ)\Pr(Y = 1 \given \hat p) = \sigmoid(Z) = \sigmoid\big((\operatorname{logit}\hat p - \delta)/\gamma\big).

What calibration means

Two definition details matter. Conditioning is on p^(X)\hat p(X), not XX: p^(x)\hat p(\vb{x}) need not equal true probability for every x\vb{x}, but among all cases assigned 0.80.8, 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

p^(X)=h(g(X))\hat p(X) = h(g(X)) with h(t)=E[Y∣g(X)=t]h(t) = \E[Y \given g(X) = t], so p^(X)\hat p(X) is a function of g(X)g(X) and the information it provides is contained in g(X)g(X). By the tower property, E[Y∣p^(X)]=E[E[Y∣g(X)]∣p^(X)]=E[p^(X)∣p^(X)]=p^(X)\E[Y \given \hat p(X)] = \E\big[\E[Y \given g(X)] \given \hat p(X)\big] = \E[\hat p(X) \given \hat p(X)] = \hat p(X).

∎

Two extremes illustrate this. With constant gg, p^≡π=P(Y=1)\hat p \equiv \pi = \Pr(Y = 1): always predicting prevalence is perfectly calibrated and distinguishes no cases. With gg identity, p^(x)=η(x)=P(Y=1∣X=x)\hat p(\vb{x}) = \eta(\vb{x}) = \Pr(Y = 1 \given X = \vb{x}), 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 η\eta preserves it while breaking calibration. You will see this below.

The theorem also gives a repair recipe: if rr is its reliability curve, r(p^(X))=E[Y∣p^(X)]r(\hat p(X)) = \E[Y \given \hat p(X)] is calibrated (the theorem with g=p^g = \hat p) and preserves ordering when rr is increasing. Estimating rr on unseen data is exactly what Platt scaling and isotonic regression do.

Multiple classes

With KK classes the predictor gives a simplex vector p^(X)∈ΔK\hat{\vb{p}}(X) \in \Delta_K and several notions exist, from most to least demanding. Call c^(X)=arg max⁡kp^k(X)\hat c(X) = \argmax_k \hat p_k(X) the predicted class (with fixed tie-breaking).

  • Canonical (or multiclass): P(Y=k∣p^(X))=p^k(X)\Pr(Y = k \given \hat{\vb{p}}(X)) = \hat p_k(X) for every kk. Among cases receiving the same vector, class frequencies match the whole vector.
  • Classwise: for each kk, P(Y=k∣p^k(X))=p^k(X)\Pr(Y = k \given \hat p_k(X)) = \hat p_k(X). These are KK binary “kk versus rest” problems.
  • Top-label (Gupta and Ramdas, 2022): P(Y=c^(X)∣c^(X),max⁡kp^k(X))=max⁡kp^k(X)\Pr(Y = \hat c(X) \given \hat c(X), \max_k \hat p_k(X)) = \max_k \hat p_k(X).
  • Confidence (Guo et al., 2017): P(Y=c^(X)∣max⁡kp^k(X))=max⁡kp^k(X)\Pr(Y = \hat c(X) \given \max_k \hat p_k(X)) = \max_k \hat p_k(X). 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 p^k\hat p_k is conditioning on less than p^\hat{\vb{p}}) and top-label calibration, which implies confidence calibration. None of the implications reverses:

  • Confidence without classwise calibration. A model always predicting (0.6,0.3,0.1)(0.6, 0.3, 0.1) when the true distribution is (0.6,0.1,0.3)(0.6, 0.1, 0.3) is correct exactly 60% of the time at confidence 0.60.6, but its class-2 0.30.3 occurs only 10%.
  • Classwise and confidence, but not canonical. Three equally likely vectors (0.6,0.2,0.2)(0.6, 0.2, 0.2), (0.2,0.6,0.2)(0.2, 0.6, 0.2) and (0.2,0.2,0.6)(0.2, 0.2, 0.6) have true distributions (0.6,0.3,0.1)(0.6, 0.3, 0.1), (0.1,0.6,0.3)(0.1, 0.6, 0.3) and (0.3,0.1,0.6)(0.3, 0.1, 0.6). For class 1, value 0.60.6 appears only in the first and is satisfied; 0.20.2 appears in the other two with frequencies 0.10.1 and 0.30.3 averaging 0.20.2. Likewise classes 2 and 3, and confidence is always 0.60.6 with 60% accuracy. Yet no vector matches its true distribution.

In binary classification classwise and canonical coincide, while confidence is weaker: a model saying 0.70.7 for cases with true frequency 0.60.6 and 0.30.3 for others with frequency 0.20.2 gets the predicted class right at frequencies 0.60.6 and 0.80.8, averaging confidence 0.70.7 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 r(q)r(q) cannot be estimated pointwise: with continuous predictions each qq 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 Ib=(b−1B,bB]I_b = \big(\tfrac{b-1}{B}, \tfrac{b}{B}\big] are used by Guo et al. and calibration_curve by default; when predictions cluster near 0, most bins are nearly empty and a few contain everything. Quantile bins use b/Bb/B quantiles of p^i\hat p_i as edges and put n/Bn/B 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 nbn_b cases, frec⁡b\operatorname{frec}_b is a Bernoulli mean fluctuating on the order of p^(1−p^)/nb\sqrt{\hat p(1 - \hat p)/n_b} even for a perfect model. Bröcker and Smith’s (2007) consistency bands show this: repeatedly simulate labels yi∗∼Bern⁡(p^i)y_i^* \sim \Bern(\hat p_i) 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.
InteractiveBuild a reliability diagram
Reliability diagram
0.00.00.20.20.40.40.60.60.80.81.01.0
  • bin: (mean confidence, frequency)
  • diagonal: perfect calibration
  • gap to diagonal
  • true model curve
  • consistency band (90%)
Sample ECE versus number of bins
110203040500.050.100.15
  • sample ECE, chosen model
  • sample ECE, calibrated model (truth: 0)
  • population ECE with BB bins
  • true error
Model
2.5
10
Bins
2,000
Sample ECE0.122
90% bootstrap CI[0.112, 0.141]
Population ECE with these bins0.128
True calibration error0.128
Sample MCE0.203
Sample CE2\mathrm{CE}_20.130
Corrected CE2\mathrm{CE}_20.126
True CE2\mathrm{CE}_20.140
Predictions from this lesson's model, p^=σ(γZ+δ)\hat p = \sigmoid(\gamma Z + \delta). Start with overconfident (γ=2.5\gamma = 2.5): left points lie above the diagonal and right points below, following the dashed true curve; most leave their gray bands. Switch to quantile bins and see point distribution. Below, this sample's ECE versus bin count: compare blue with green, the calibrated model's ECE on exactly the same cases, whose true error is 0. Lower nn to 200 and raise BB: what ECE does a perfect model show? Press 'Otra muestra' (another sample) several times.

The overconfident model’s shape resembles Naive Bayes: when it says 0.030.03 the event occurs substantially more often, and when it says 0.970.97 substantially less. The curve crosses the diagonal at 0.50.5 because δ=0\delta = 0. 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 B=15B = 15 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 ECE^\widehat{\mathrm{ECE}} estimate with infinite data? Each bin converges to E[Y∣p^∈Ib]\E[Y \given \hat p \in I_b] and E[p^∣p^∈Ib]\E[\hat p \given \hat p \in I_b], so the limit is error of the binned version of the model, which predicts mean p^\hat p in each bin (Kumar, Liang and Ma, 2019):

CE1(B)=∑bP(p^∈Ib) ∣E[r(p^)−p^∣p^∈Ib]∣.\mathrm{CE}_1^{(B)} = \sum_b \Pr(\hat p \in I_b)\,\Big\lvert\E\big[r(\hat p) - \hat p \given \hat p \in I_b\big]\Big\rvert.
Proof

By Jensen’s inequality applied to ∣⋅∣\abs{\cdot} in each bin, ∣E[r(p^)−p^∣p^∈Ib]∣≤E[∣r(p^)−p^∣∣p^∈Ib]\abs{\E[r(\hat p) - \hat p \given \hat p \in I_b]} \le \E[\abs{r(\hat p) - \hat p} \given \hat p \in I_b]. Multiply by P(p^∈Ib)\Pr(\hat p \in I_b) and sum to obtain E∣r(p^)−p^∣=CE1\E\abs{r(\hat p) - \hat p} = \mathrm{CE}_1.

∎

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 0.490.49. In our overconfident model deviation r(q)−qr(q) - q changes sign only at q=0.5q = 0.5, so the effect is small (calculated below): one bin measures only global calibration ∣E[p^]−π∣=0.031\abs{\E[\hat p] - \pi} = 0.031; with even BB, 0.50.5 is an edge so nothing cancels, recovering true value 0.12770.1277.

Few data per bin overestimate

Conversely, with finite nn, ∣frec⁡b−conf⁡b∣\abs{\operatorname{frec}_b - \operatorname{conf}_b} 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, frec⁡b−conf⁡b=1nb∑i∈Bb(yi−p^i)\operatorname{frec}_b - \operatorname{conf}_b = \frac{1}{n_b}\sum_{i \in \mathcal{B}_b}(y_i - \hat p_i) has mean 0 and variance vb/nbv_b/n_b with vb=1nb∑i∈Bbp^i(1−p^i)v_b = \frac{1}{n_b}\sum_{i \in \mathcal{B}_b}\hat p_i(1 - \hat p_i). By the central limit theorem and E∣N(0,σ2)∣=σ2/π\E\abs{\Normal(0, \sigma^2)} = \sigma\sqrt{2/\pi},

E[ECE^]≈∑bnbn2vbπ nb=2π ∑bnb vbn.\E\big[\widehat{\mathrm{ECE}}\big] \approx \sum_b \frac{n_b}{n}\sqrt{\frac{2 v_b}{\pi\,n_b}} = \sqrt{\frac{2}{\pi}}\,\sum_b \frac{\sqrt{n_b\,v_b}}{n}.

With equal-sized bins nb=n/Bn_b = n/B, this is 2/π  vb‾  B/n\sqrt{2/\pi}\;\overline{\sqrt{v_b}}\;\sqrt{B/n}: a perfect model’s ECE grows like B/n\sqrt{B/n}. Doubling bins multiplies it by 1.41.4 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 BB.

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,

CE^2 2,corr=∑bnbn[(frec⁡b−conf⁡b)2−frec⁡b(1−frec⁡b)nb−1].\widehat{\mathrm{CE}}_2^{\,2,\text{corr}} = \sum_b \frac{n_b}{n}\left[(\operatorname{frec}_b - \operatorname{conf}_b)^2 - \frac{\operatorname{frec}_b(1 - \operatorname{frec}_b)}{n_b - 1}\right].

Kumar et al. (2019) prove for models already taking BB values that estimating CE22\mathrm{CE}_2^2 with bounded relative error takes order B/CE22B/\mathrm{CE}_2^2 samples with the direct estimator but only B/CE22\sqrt{B}/\mathrm{CE}_2^2 with the corrected one. For ECE ℓ1\ell_1 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:

RuleS(q,y)S(q, y)Sˉ(q;p)\bar S(q; p)Proper?
Logarithmic (log-loss)−log⁡q-\log q if y=1y = 1, −log⁡(1−q)-\log(1 - q) if y=0y = 0H⁡(p)+KL⁡(p∥q)\Ent(p) + \KL(p \Vert q)strictly
Brier (quadratic)(y−q)2(y - q)^2(q−p)2+p(1−p)(q - p)^2 + p(1 - p)strictly
Spherical1−qy/q2+(1−q)21 - q_y/\sqrt{q^2 + (1 - q)^2}, with q1=qq_1 = q and q0=1−qq_0 = 1 - qstrictly
Absolute∣y−q∣\abs{y - q}p+q(1−2p)p + q(1 - 2p)no
0-1 with threshold 1/21/21[1[q≥1/2]≠y]\ind[\ind[q \ge 1/2] \neq y]1−p1 - p or ppyes, not strictly

Log-loss is the logarithmic score (the logistic regression loss), and its excess over truth is KL divergence: Sˉ(q;p)−Sˉ(p;p)=KL⁡(Bern⁡(p) ∥ Bern⁡(q))≥0\bar S(q; p) - \bar S(p; p) = \KL(\Bern(p) \,\|\, \Bern(q)) \ge 0, with equality only if q=pq = p (Gibbs’ inequality). Brier, for KK classes ∑k(1[y=k]−qk)2\sum_k (\ind[y = k] - q_k)^2, is probability mean squared error, with excess (q−p)2(q - p)^2; you prove this in an exercise. Absolute loss is linear in qq, so its minimum is at an endpoint: with p>1/2p > 1/2 it pays to report q=1q = 1. 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 0.510.51 and 0.990.99 equally.

InteractiveWhy lying does not pay
0.00.20.40.60.81.00.20.40.60.81.0p = 0.70
  • log-loss
  • Brier
  • absolute ∣y−q∣\abs{y - q}
  • minimum of each curve
0.70
0.90
Expected log-loss0.765
Excess over q=pq = p (the KL⁡\KL)0.1537
Expected Brier0.250
Excess over q=pq = p: (q−p)2(q - p)^20.0400
Expected absolute loss0.340
Excess over q=pq = p−0.0800
Log-loss and Brier are minimized at q=p=0.70q = p = 0.70. Absolute loss is minimized at q=1q = 1: reporting the truth costs 0.120 compared with fully misreporting.
True probability is pp; choose reported qq and see each rule's expected loss. Start exaggerating: p=0.7p = 0.7 and report q=0.9q = 0.9. Log-loss and Brier have minima (hollow circle) at q=0.7q = 0.7, and moving either way costs: log-loss excess is KL, Brier excess (q−p)2(q - p)^2. Absolute loss instead rewards exaggeration, more so at q=1q = 1: it falls in a straight line. Drag qq to either side of the minimum. Move pp to 0.50.5 and below. Enable 0-1 and spherical: which is flat over an entire interval?

All proper rules have the same form

Call H(p)=Sˉ(p;p)H(p) = \bar S(p; p) the minimum expected loss: the rule’s generalized entropy. For log-loss this is binary entropy; for Brier, p(1−p)p(1 - p).

Proof

For fixed qq, p↦Sˉ(q;p)p \mapsto \bar S(q; p) is affine. If SS is proper, H(p)=min⁡qSˉ(q;p)H(p) = \min_q \bar S(q; p) is a minimum of affine functions and thus concave, and line p↦Sˉ(q;p)p \mapsto \bar S(q; p) lies above HH and touches at p=qp = q: a supertangent at qq with slope S(q,1)−S(q,0)=:H′(q)S(q, 1) - S(q, 0) =: H'(q). Evaluating the line at p=y∈{0,1}p = y \in \{0, 1\} gives S(q,y)=Sˉ(q;y)=H(q)+H′(q)(y−q)S(q, y) = \bar S(q; y) = H(q) + H'(q)(y - q). Conversely, in that form Sˉ(q;p)=H(q)+H′(q)(p−q)≥H(p)\bar S(q; p) = H(q) + H'(q)(p - q) \ge H(p), because a concave function lies below its supertangents, with equality only at p=qp = q under strict concavity.

∎

With H(q)=q(1−q)H(q) = q(1 - q) and H′(q)=1−2qH'(q) = 1 - 2q this gives q−q2+(1−2q)(y−q)=y−2qy+q2=(y−q)2q - q^2 + (1 - 2q)(y - q) = y - 2qy + q^2 = (y - q)^2, because y2=yy^2 = y. Binary entropy gives log-loss. Excess d(p,q)=Sˉ(q;p)−H(p)d(p, q) = \bar S(q; p) - H(p) is the Bregman divergence of −H-H: (p−q)2(p - q)^2 for Brier and KL for log-loss.

Why a proper rule rewards calibration and discrimination

Now condition on prediction. If r(p^)=E[Y∣p^]r(\hat p) = \E[Y \given \hat p], given p^\hat p the label is Bern⁡(r(p^))\Bern(r(\hat p)) and expected loss Sˉ(p^;r(p^))=H(r(p^))+d(r(p^),p^)\bar S(\hat p; r(\hat p)) = H(r(\hat p)) + d(r(\hat p), \hat p). Taking expectations,

E[S(p^,Y)]=E[d(r(p^),p^)]⏟descalibracioˊn+E[H(r(p^))]⏟refinamiento,\E\big[S(\hat p, Y)\big] = \underbrace{\E\big[d(r(\hat p), \hat p)\big]}_{\text{descalibración}} + \underbrace{\E\big[H(r(\hat p))\big]}_{\text{refinamiento}},

and since HH is concave and E[r(p^)]=π\E[r(\hat p)] = \pi, refinement is H(π)−(H(π)−E[H(r(p^))])H(\pi) - \big(H(\pi) - \E[H(r(\hat p))]\big): problem uncertainty minus how much the model separates cases, which is ≥0\ge 0 by Jensen. A strictly proper rule penalizes both: miscalibration (zero only if r(p^)=p^r(\hat p) = \hat p) and lack of information (refinement decreases as r(p^)r(\hat p) move away from π\pi). It also shows why recalibrating with the true curve never worsens loss: r(p^)r(\hat p) is calibrated and has the same refinement, so its expected loss is E[H(r(p^))]≤E[S(p^,Y)]\E[H(r(\hat p))] \le \E[S(\hat p, Y)].

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 ℓ2\ell_2 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 fkf_k values, only how cases are grouped.
  • Uncertainty: variance of YY. It does not depend on the model: it is the Brier score of always predicting oˉ\bar o.

The proof sums squares within groups; you reconstruct it in the guided exercise. In population, with reliability curve rr, this is the previous section’s calculation: BS=E[(p^−r(p^))2]−Var⁡(r(p^))+π(1−π)\mathrm{BS} = \E[(\hat p - r(\hat p))^2] - \Var(r(\hat p)) + \pi(1 - \pi).

Two practical cautions. First, if predictions are continuous and each value appears once, every “group” has oˉk∈{0,1}\bar o_k \in \{0, 1\}, 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):

BS=fiab.−resol.+incert.+1n∑b∑i∈Bb(p^i−conf⁡b)2−2n∑b∑i∈Bb(p^i−conf⁡b)(yi−frec⁡b),\mathrm{BS} = \text{fiab.} - \text{resol.} + \text{incert.} + \frac{1}{n}\sum_b\sum_{i \in \mathcal{B}_b}(\hat p_i - \operatorname{conf}_b)^2 - \frac{2}{n}\sum_b\sum_{i \in \mathcal{B}_b}(\hat p_i - \operatorname{conf}_b)(y_i - \operatorname{frec}_b),

with reliability and resolution calculated using conf⁡b\operatorname{conf}_b and frec⁡b\operatorname{frec}_b. Second, empirical reliability has the same upward bias as ECE, and Ferro and Fricker (2012) propose the same correction.

InteractiveReliability, resolution and uncertainty
0.000.050.100.150.200.250.30Constant prevalence0.242Calibrated, low information (τ = 3)0.229Calibrated, informative (τ = 0.5)0.180Discriminative and overconfident (τ = 0.5, γ = 2.5)0.200Your model0.191
  • uncertainty π(1−π)\pi(1 - \pi)
  • resolution (subtracted)
  • reliability (added)
  • resulting Brier
0.50
1.80
0.50
Reliability (increases Brier)0.0116
Resolution (decreases Brier)0.0626
Uncertainty π(1−π)\pi(1 - \pi)0.2423
Brier = reliability − resolution + uncertainty0.1914
Expected log-loss0.5864
AUC0.7957
γ\gamma and δ\delta are monotonic transformations: they do not change the order, so resolution and AUC do not change. Only τ\tau, which changes what the model knows, changes them.
Each row is a model of the lesson's problem seeing noisy feature W=Z+εW = Z + \varepsilon, ε∼N(0,τ2)\varepsilon \sim \Normal(0, \tau^2), and predicting σ(γlogit⁡p^(W)+δ)\sigmoid(\gamma \operatorname{logit}\hat p(W) + \delta), where p^(W)=E[σ(Z)∣W]\hat p(W) = \E[\sigmoid(Z) \given W] is calibrated. Quantities are exact in population. Gray bar is uncertainty; green is resolution, subtracted; red reliability, added; black line resulting Brier. Constant prevalence has neither red nor green. In the last row move γ\gamma and δ\delta: only red changes. Move τ\tau: green and AUC change.

The figure shows the partition. Problem uncertainty is π(1−π)=0.242\pi(1 - \pi) = 0.242. With τ=0.5\tau = 0.5 and γ=1\gamma = 1 the model is calibrated and separates well: resolution 0.0630.063, Brier 0.1800.180, AUC 0.7960.796. The same model with γ=2.5\gamma = 2.5 ranks identically (same resolution and AUC) and pays reliability 0.0200.020: Brier 0.2000.200. The uninformative model τ=3\tau = 3 is calibrated yet reaches 0.2290.229, near constant prevalence because it resolves little (0.0130.013). 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 TT of probabilities preserves it, and almost all break calibration. The next interactive lets you draw TT.

InteractiveIntact ranking, broken probabilities
Transformation TT: original → reported probability
0.00.00.50.51.01.0
Reliability diagram for T(p)T(p)
0.00.00.50.51.01.0
  • transformation and bins
  • calibration gap
  • diagonal (perfect calibration)
AUC: original → transformed0.8111 → 0.8111
Tied (positive, negative) pairs0
ECE (10 bins)0.027 → 0.122
Brier0.1733 → 0.1906
Log-loss0.5180 → 0.6234
2000 lesson-model cases with true probability p=σ(Z)p = \sigmoid(Z), calibrated by construction. In the first panel draw a nondecreasing transformation TT by dragging five knots; the second shows T(p)T(p)'s reliability diagram. Start with overconfidence: AUC has not moved from its original value while ECE, Brier and log-loss worsen. Try underconfidence and return to identity. Then press the step: flat intervals combine cases of different probabilities, producing ties and lowering AUC.

The lesson’s recurring distinction: AUC answers “does it rank well?” and calibration “do its numbers mean anything?” A model can have AUC 0.950.95 and ECE 0.150.15 (in the signatures cell AdaBoost has AUC 0.9600.960 and ECE 0.3510.351), 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.

[ ]Reliability diagram, ECE and bands from scratchBrowser
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 0.350.35 and 0.650.65 near the curve’s diagonal crossing. Estimated ECE 0.1230.123 is close to true error 0.12770.1277 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:

[ ]Against calibration_curve, brier_score_loss and log_lossBrowser
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: σ(40)\sigmoid(40) rounds to 1 in floating point, and −log⁡(1−1)=∞-\log(1 - 1) = \infty, whereas log⁡(1+e40)=40\log(1 + e^{40}) = 40 is representable. scikit-learn receives probabilities and clips them at [ϵ,1−ϵ][\epsilon, 1 - \epsilon] 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 2/π∑bnbvb/n\sqrt{2/\pi}\sum_b \sqrt{n_b v_b}/n and direct and corrected squared error. It then calculates in population by quadrature the binned overconfident model’s error.

[ ]The two ECE biasesBrowser
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 2/π∑bnbvb/n\sqrt{2/\pi}\sum_b\sqrt{n_b v_b}/n (in code sqrt(2/π · v_b), since v already sums nbvbn_b v_b) matches every row. With n=250n = 250 and B=50B = 50 a perfect model shows ECE 0.140.14, and even with 4000 cases and 15 bins 0.0200.020. Going from B=5B = 5 to B=50B = 50 multiplies ECE by about 3 as 50/5=3.16\sqrt{50/5} = 3.16 predicts. Corrected squared error drastically reduces bias (0.0910.091 to 0.0050.005 with 1000 cases and 50 bins), though not always eliminating it. Below is the binned overconfident model: one bin sees only global calibration 0.0310.031; with B=5B = 5 bin (0.4,0.6](0.4, 0.6] contains the crossing and loses some; even BB recovers truth.

Proper rules in numbers

[ ]Proper rules, Savage representation and a misleading ECEBrowser
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 pp 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 (0.0080.008) looks as good as truth (0.0070.007) and much better than the overconfident model (0.1260.126); by Brier and log-loss the constant is worst, and the overconfident model, ranking exactly like truth, lies between.

Murphy, exact and binned

[ ]Murphy decompositionBrowser
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 0.196040.19604 rather than 0.194360.19436, 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 p^k\hat p_k versus 1[y=k]\ind[y = k] ECEs.

[ ]Confidence and classwise calibration on digitsBrowser
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 0.9900.990 with accuracy 0.8290.829, as in the generative classifiers lesson. Logistic with C=0.1C = 0.1 is underconfident: accuracy 96.396.3% with mean confidence 0.8720.872, 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 [0,1][0, 1] with (x−min⁡)/(max⁡−min⁡)(x - \min)/(\max - \min).
  • 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 4.854.85% with error 44.9244.92%, while a 110-layer ResNet had ECE 16.5316.53% with error 27.8327.83% (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 16.5316.53% to 1.261.26%.

The mechanisms match what you know of each model:

  • Naive Bayes adds log-likelihood ratios of correlated features as if independent (Naive Bayes): with mm copies of one feature, its log-odds contribution multiplies by mm. This is γ>1\gamma > 1 in the lesson’s model.
  • AdaBoost (boosting) gives weighted vote ∑mαmhm(x)\sum_m \alpha_m h_m(\vb{x}) with hm∈{−1,1}h_m \in \{-1, 1\}. In population exponential loss pushes it toward 12log⁡p1−p\frac12\log\frac{p}{1-p} (exponential loss), but a finite weak-learner vote ending by fitting margin is not on that scale. scikit-learn’s predict_proba also returns σ(2F(x)/∑mαm)\sigmoid\big(2F(\vb{x})/\sum_m \alpha_m\big) with F=∑mαmhmF = \sum_m \alpha_m h_m: vote is normalized to [−1,1][-1, 1] before sigmoid, so all probabilities lie between σ(−2)=0.12\sigmoid(-2) = 0.12 and σ(2)=0.88\sigmoid(2) = 0.88 (the cell checks).
  • SVM (soft margin) produces distance from boundary; linearly rescaled to [0,1][0, 1] it is not a probability, and hinge loss elicits only the sign of p−1/2p - 1/2.
  • 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 ∑ip^i=∑iyi\sum_i \hat p_i = \sum_i y_i 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 (x−min⁡)/(max⁡−min⁡)(x - \min)/(\max - \min) as Niculescu-Mizil and Caruana did.

[ ]Signatures: data, logistic regression, Naive Bayes and SVMBrowser
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}")
[ ]Signatures: Random ForestBrowser
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}")
[ ]Signatures: AdaBoostBrowser
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())))
[ ]Signatures: gradient boosting with log-lossBrowser
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}")
[ ]Signatures: reliability diagrams and Brier decompositionBrowser
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()
InteractiveSignature gallery
Reliability diagram: Naive Bayes
0.00.00.20.20.40.40.60.60.80.81.01.0
Reliability and resolution of the six models
Logistic regression0.16410.0039Naive Bayes0.16070.0074SVM (rescaled)0.19330.0622Random Forest0.20180.0029AdaBoost (stumps)0.17650.1231Gradient boosting0.19730.0005
  • bin: (mean confidence, frequency)
  • calibration gap
  • resolution
  • reliability
AUC0.944
ECE (10 bins)0.068
Reliability0.0074
Resolution0.1607
Brier0.0954
Predictions outside [0.1, 0.9]81 %
Reliability diagrams (10 uniform bins) and Brier decomposition for the lab's six models, with exact numbers printed by the final cell. Explore models and compare diagram shape with confidence histogram: Naive Bayes piles mass at extremes, above diagonal on left and below on right; AdaBoost and SVM concentrate centrally and draw a sigmoid; forest and logistic show a mild sigmoid; gradient boosting with log-loss places points near diagonal.

What emerges model by model, and what it means:

  • Naive Bayes reproduces the textbook signature: 81% of predictions are outside [0.1,0.9][0.1, 0.9], and intermediate-bin frequency is far from confidence (says 0.140.14, occurs 3434%). It ranks well (AUC 0.9440.944) and pays reliability 0.00740.0074.
  • AdaBoost is opposite: all probabilities lie between 0.310.31 and 0.690.69 despite near-best discrimination (AUC 0.9600.960). ECE 0.3510.351 and reliability 0.1230.123 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 0.350.35, occurs 55%; says 0.660.66, occurs 9191%), with central mass.
  • Random Forest: mild symmetric sigmoid (says 0.250.25, occurs 1010%; says 0.760.76, occurs 8888%), 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 0.0120.012, reliability 0.00050.0005) and best Brier alongside forest. Unlike 2005 boosting it minimizes a strictly proper rule in function space.

The resolution column confirms Murphy: AdaBoost’s 0.17650.1765, measured with only four occupied bins, already exceeds logistic 0.16410.1641 and Naive Bayes 0.16070.1607. 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

NumericA bin's reliability contribution
A model predicts 0.80.8 for 100 cases, 65 positive. How much does each case contribute to Murphy's reliability term? (The term is 1n∑knk(fk−oˉk)2\frac{1}{n}\sum_k n_k (f_k - \bar o_k)^2; give per-case contribution of that bin, (fk−oˉk)2(f_k - \bar o_k)^2.)
NumericResolution of a two-value model
A model emits only two probabilities: 0.20.2 for 60 cases, 15 positive, and 0.70.7 for 40 cases, 30 positive. What is Murphy decomposition's resolution term?
NumericThe cost of exaggerating
An event's true probability is 0.70.7 and you report 0.90.9. How much does expected log-loss increase (in nats) compared with reporting 0.70.7?
NumericA perfect model's ECE
A perfectly calibrated model predicts 0.50.5 for 400 cases all in one bin. Approximately what is expected contribution ∣frec⁡b−conf⁡b∣\abs{\operatorname{frec}_b - \operatorname{conf}_b} to that bin? Use the normal approximation.
QuizHigh AUC, high ECE
A model has validation AUC 0.950.95 and ECE 0.150.15. Which statement is correct?
QuizWhich are strictly proper?
Which losses are strictly proper scoring rules for a binary event?

More than one answer may be correct.

QuizWhose diagram is this?
A model's confidence histogram puts almost all mass between 0.350.35 and 0.650.65, and its reliability diagram lies below the diagonal left of 0.50.5 and above on the right, S-shaped. AUC is high. Which model is likeliest?
QuizCalibrated confidence
A three-class classifier always emits vector (0.6,0.3,0.1)(0.6, 0.3, 0.1) and, among cases receiving it, class frequencies are (0.6,0.1,0.3)(0.6, 0.1, 0.3). Which calibration notions does it satisfy?

More than one answer may be correct.

ProofBrier is strictly proper
Prove: If Y∼Bern⁡(p)Y \sim \Bern(p), then E[(Y−q)2]\E[(Y - q)^2] is minimized only at q=pq = p.
0
Fix p∈[0,1]p \in [0, 1] and consider Sˉ(q;p)=E[(Y−q)2]\bar S(q; p) = \E[(Y - q)^2] as a function of q∈[0,1]q \in [0, 1].

Step 1 of 3. How do you start?

ProofMurphy decomposition
Prove: For predictions taking values f1,…,fKf_1, \dots, f_K, with nkn_k cases and frequency oˉk\bar o_k at value fkf_k, BS=1n∑knk(fk−oˉk)2−1n∑knk(oˉk−oˉ)2+oˉ(1−oˉ)\mathrm{BS} = \frac{1}{n}\sum_k n_k(f_k - \bar o_k)^2 - \frac{1}{n}\sum_k n_k(\bar o_k - \bar o)^2 + \bar o(1 - \bar o).
0
Write BS=1n∑k∑i∈Gk(fk−yi)2\mathrm{BS} = \frac{1}{n}\sum_k \sum_{i \in G_k}(f_k - y_i)^2, where GkG_k are cases receiving fkf_k.

Step 1 of 3. How do you treat the sum inside group GkG_k?

CodeECE with uniform and quantile bins
Implement 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 (eb−1,eb](e_{b-1}, e_b] 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.0
Shift+Enter to run

Summary

Key idea
A classifier is calibrated if among cases assigned probability qq, fraction qq are positive. This is cheap (prevalence prediction satisfies it) and independent of ordering; optimization uses a strictly proper rule, minimized only by telling the truth and rewarding both calibration and resolution.
  • Binary calibration is E[Y∣p^]=p^\E[Y \given \hat p] = \hat p. 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 B/n\sqrt{B/n} 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 S(q,y)=H(q)+H′(q)(y−q)S(q, y) = H(q) + H'(q)(y - q) with concave HH.
  • 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.