Module contents
Lesson 22 of 24Advanced 100 min

Recalibrating classifiers: Platt, isotonic, beta and temperature scaling

Develop post-hoc recalibration methods and when to use each: Platt scaling, isotonic regression using PAV, beta calibration and multiclass temperature scaling. Emphasize the correct protocol (separate calibration data or cross-fitting), prior correction after resampling, and the tradeoff between calibrator flexibility and overfitting.

After this lesson you can

  • Implement Platt scaling with Platt’s smoothed targets and justify its parametric form.
  • Implement isotonic regression with PAV and prove it gives the monotone least-squares solution.
  • Apply beta calibration and temperature scaling and explain when a sigmoid is insufficient.
  • Recalibrate without leakage using a separate calibration set or cross-fitting such as CalibratedClassifierCV.
  • Choose the method by calibration-set size and distortion shape, and verify improvement with proper scoring rules.

Before you start

Motivation: good ranking is not good probability

In the previous lesson you learned to measure classifier calibration using reliability diagrams and proper scoring rules, and saw model-family miscalibration signatures. This lesson asks: if diagnosis is bad, how can it be fixed?

The usual answer is to learn a monotonic function g^\hat g mapping model score ss to reliable probabilities p^=g^(s)\hat p = \hat g(s). This one-dimensional problem (one input, one output) takes milliseconds and is separate from training: the model continues ranking examples, while the calibrator translates ranking to probabilities.

One lab example: a Gaussian Naive Bayes trained on highly correlated features has test AUC 0.91310.9131 and log-loss 0.42340.4234. After Platt recalibration AUC remains exactly 0.91310.9131 (the increasing calibrator preserves order) and log-loss falls to 0.37300.3730. With isotonic it falls to 0.36970.3697. The model learned nothing new; it simply stopped exaggerating. If those probabilities guide credit decisions or alert review, the difference is between minimum-cost and systematically biased decisions.

There are four classical calibrators; choosing trades flexibility against variance:

  • Platt: a sigmoid of the score, two parameters. Stable with little data, but only corrects sigmoid-shaped distortions.
  • Isotonic: any increasing function, least-squares fitted with PAV. Corrects everything with sufficient data and overfits otherwise.
  • Beta: three parameters, a family including identity and asymmetric distortions Platt cannot follow.
  • Temperature: one multiclass parameter dividing network logits by TT, changing no predictions.

Before formulas, see how the first three behave on a model with known distortion.

InteractivePlatt, isotonic and beta head to head
Calibrators fitted on n=200n = 200 pairs versus the truth g(s)=P(Y=1∣s)g(s) = \Pr(Y = 1 \mid s)
diagonal: calibrated
Histogram of ss in the calibration sample
  • truth g(s)g(s)
  • frequency per bin (size: data count)
  • Platt
  • isotonic
  • beta
200
Platt on
× 10⁻⁴Brierlog-lossuncalibrated70.8310.2
Platt31.697.6
Isotonic40.5∞
Beta21.252.6
Platt: a=0.46a = 0.46, b=−0.13b = −0.13 · beta: a=1.08a = 1.08, b=0.00b = 0.00, c=0.89c = 0.89
With n=200n = 200, Beta wins on excess Brier. Isotonic predicts exactly 0 or 1 on an interval where gg is strictly between 0 and 1: its expected log-loss is infinite.
A model with log-odds z∼N(0,1.82)z \sim \Normal(0, 1.8^2) predicts s=σ(z)s = \sigma(z), but true probability is g(s)g(s) (dashed). Simulate nn pairs (si,yi)(s_i, y_i), fit all three calibrators and see each one's added Brier and log-loss relative to truth, computed exactly by quadrature. Start with asymmetric distortion and n=200n = 200; increase nn to 5000: which converges to truth, which falls short? Lower nn to 30 and press 'Ver 20 muestras' (show 20 samples). Then choose 'Ya calibrado' (already calibrated) and switch Platt to probability ss.

Three observations the rest explains. With asymmetric distortion Platt converges to a curve that is not truth: however large nn grows, error plateaus. Isotonic does converge, but with small nn draws sample-dependent steps and predicts exactly 0 or 1 at extremes, giving infinite expected log-loss. With an already calibrated model every calibrator harms something; Platt on probability instead of log-odds always harms because it cannot represent identity.

The recalibration problem

Let s(x)s(\vb{x}) be an already trained binary classifier’s score: probability, log-odds or SVM margin. We want to return the calibration function

g(u)=P(Y=1∣s(X)=u),g(u) = \Pr(Y = 1 \given s(X) = u),

because composition g∘sg \circ s is calibrated by construction: if the model says g(s)=0.3g(s) = 0.3, the positive class occurs 30% of the time. Recalibration estimates gg using sample (si,yi)i=1n(s_i, y_i)_{i=1}^n of scores and labels. It is regression of YY on one feature ss with two requirements: the estimate must be monotonic (otherwise it undoes learned ranking), and the sample cannot be the model’s training set (revisited in the protocol section).

Why estimate gg rather than something else? Among functions of ss it scores best under any proper rule.

Proof

Condition on s(X)=us(X) = u. Given uu, YY is Bernoulli with parameter g(u)g(u), and h(u)h(u) is a fixed number qq. Propriety makes expected score EY∼Bern⁡(g(u))[S(q,Y)]\E_{Y \sim \Bern(g(u))}[S(q, Y)] minimal at q=g(u)q = g(u), uniquely under strict propriety. Integrating over uu yields the inequality, and equality requires h(u)=g(u)h(u) = g(u) except on a null-probability set.

∎

Two consequences. First, ideal calibration improves log-loss and Brier together, making both measuring sticks (ECE is not: it is not a proper rule). Second, if gg is increasing, as in any reasonable model, recalibration preserves example order, so AUC, ROC curve and decisions like “review the top 5%” remain intact. What changes is each probability value, needed when comparing cost thresholds or combining models.

Platt scaling

In 1999 John Platt proposed turning an SVM’s non-probability margin f(x)f(\vb{x}) into a probability by fitting a two-parameter sigmoid.

Platt writes sigmoid 1/(1+eAf+B)1/(1 + e^{A f + B}) with A=−aA = -a: under his convention the useful slope is negative. The target form follows Lin, Lin and Weng’s note (2007), reproducing the original formulation.

Why a sigmoid

Platt empirically observed class-conditional SVM output densities were approximately exponential, and Bayes’ rule applied to two exponentials gives a sigmoid. The same argument works for equal-variance Gaussians: if u∣Y=k∼N(μk,τ2)u \given Y = k \sim \Normal(\mu_k, \tau^2) and πk=P(Y=k)\pi_k = \Pr(Y = k),

log⁡P(Y=1∣u)P(Y=0∣u)=log⁡π1π0+(u−μ0)2−(u−μ1)22τ2=μ1−μ0τ2⏟a u+log⁡π1π0+μ02−μ122τ2⏟b,\log\frac{\Pr(Y = 1 \given u)}{\Pr(Y = 0 \given u)} = \log\frac{\pi_1}{\pi_0} + \frac{(u - \mu_0)^2 - (u - \mu_1)^2}{2\tau^2} = \underbrace{\frac{\mu_1 - \mu_0}{\tau^2}}_{a}\, u + \underbrace{\log\frac{\pi_1}{\pi_0} + \frac{\mu_0^2 - \mu_1^2}{2\tau^2}}_{b},

and posterior probability is σ(au+b)\sigma(a u + b). This is the calculation making linear discriminant analysis linear. It also says when Platt fails: Kull, Silva Filho and Flach (2017) note logistic calibration assumes classwise normal scores, not true of heavily skewed Naive Bayes or AdaBoost scores.

If score is log-odds u=z=logit⁡su = z = \operatorname{logit} s, Platt with a=1a = 1 and b=0b = 0 is identity; a<1a < 1 corrects an overconfident model (pulls log-odds toward 0), a>1a > 1 an underconfident one, and bb shifts prevalence. For a binary probability classifier, applying Platt to logit⁡s\operatorname{logit} s is natural. Applying it directly to ss, as scikit-learn does without decision_function, has a one-line defect: since s∈[0,1]s \in [0, 1], output σ(as+b)\sigma(a s + b) is trapped between σ(b)\sigma(b) and σ(a+b)\sigma(a + b), excluding 0 and 1. No (a,b)(a, b) gives identity, and a perfectly calibrated model is harmed, as seen in the first figure’s “Ya calibrado” option.

Why smoothed targets

With 0/1 labels there is a case where likelihood has no maximum: if calibration positives all score above negatives, the problem is separable and optimal slope infinite, exactly logistic regression’s separable-data divergence. This occurs when calibrating SVM training outputs that separate their own data. With targets strictly between 0 and 1, each term log⁡(1+ez)−tz\log(1 + e^{z}) - t z grows linearly as z→±∞z \to \pm\infty (slopes 1−t>01 - t > 0 and t>0t > 0 on the two sides), so FF is coercive unless all uiu_i are equal and a minimum exists. Platt uses a Bayesian argument: the result has Laplace’s succession-rule form (k+1)/(m+2)(k + 1)/(m + 2), applied to “all N+N_+ positives were positive” and “none of N−N_- negatives was positive.” With large samples targets tend to 1 and 0 and the effect vanishes.

First-order equations show what fitting preserves. The gradient of FF with respect to (a,b)(a, b) is

∇F=[∑iui(p^i−ti)∑i(p^i−ti)],p^i=σ(aui+b),\grad F = \begin{bmatrix} \sum_i u_i(\hat p_i - t_i) \\ \sum_i (\hat p_i - t_i) \end{bmatrix}, \qquad \hat p_i = \sigma(a u_i + b),

so at optimum 1n∑ip^i=1n∑iti\frac{1}{n}\sum_i \hat p_i = \frac{1}{n}\sum_i t_i: mean calibrator probability reproduces prevalence, mildly shrunk toward 1/21/2 by smoothing.

How to fit

The Hessian is

∇2F=∑ip^i(1−p^i)[ui2uiui1],\hess F = \sum_i \hat p_i(1 - \hat p_i)\begin{bmatrix} u_i^2 & u_i \\ u_i & 1 \end{bmatrix},

positive semidefinite because each summand is, and positive definite if and only if not all uiu_i are equal: since p^i(1−p^i)>0\hat p_i(1 - \hat p_i) > 0, quadratic form v⊤∇2F v=∑ip^i(1−p^i)(v1ui+v2)2\vb{v}^\top \hess F\, \vb{v} = \sum_i \hat p_i(1 - \hat p_i)(v_1 u_i + v_2)^2 vanishes only if v1ui+v2=0v_1 u_i + v_2 = 0 for all ii, which with two distinct uiu_i forces v=0\vb{v} = \vb{0}. The problem is convex, strictly so with two distinct scores. Platt used a Levenberg–Marquardt-type method; Lin, Lin and Weng identified numerical difficulties and proposed Newton’s method with backtracking line search and guaranteed convergence, which you will implement (Armijo condition and constant 10−410^{-4}). With two parameters each Newton step solves a 2×22 \times 2 system; it converges in about ten iterations.

Isotonic regression and PAV

Platt imposes a shape. The nonparametric alternative imposes only what is known: calibration increases with score.

Zadrozny and Elkan (KDD 2002) proposed it as an alternative to Platt and binning for any binary classifier ranking examples, testing Naive Bayes and SVM, and later combined binary calibrators for multiclass. The problem is a convex quadratic program with linear constraints, so KKT conditions are necessary and sufficient. Reading them reveals solution structure.

The block solution

Write constraints θi−θi+1≤0\theta_i - \theta_{i+1} \le 0 with multipliers λi≥0\lambda_i \ge 0, i=1,…,n−1i = 1, \dots, n - 1, and let λ0=λn=0\lambda_0 = \lambda_n = 0. The Lagrangian of 12∑iwi(yi−θi)2\frac12\sum_i w_i(y_i - \theta_i)^2 gives stationarity

wi(θi−yi)+λi−λi−1=0⟹λi=∑j≤iwj(yj−θj).w_i(\theta_i - y_i) + \lambda_i - \lambda_{i-1} = 0 \quad\Longrightarrow\quad \lambda_i = \sum_{j \le i} w_j (y_j - \theta_j).

Group indices into blocks: consecutive intervals where θ\theta is constant, separated where θ\theta strictly increases. The other three conditions become:

  • Complementary slackness. Between blocks the constraint is inactive, so λi=0\lambda_i = 0: cumulative residuals vanish at each block end. Subtracting consecutive ends, each block BB satisfies ∑j∈Bwj(yj−θB)=0\sum_{j \in B} w_j(y_j - \theta_B) = 0, i.e., θB\theta_B is its yjy_j weighted mean.
  • Dual feasibility. Within a block, λi≥0\lambda_i \ge 0 means the sum of wj(yj−θB)w_j(y_j - \theta_B) from block start to ii is nonnegative: every block prefix has weighted mean ≥θB\ge \theta_B.
  • Primal feasibility. Block means are nondecreasing.

Conversely, a consecutive-block partition with those properties defines θ\theta and λ\lambda satisfying all four KKT conditions, making θ\theta optimal. Since the objective is strictly convex (all wi>0w_i > 0), it is unique.

The algorithm

The PAV algorithm (pool adjacent violators), dating to Ayer, Brunk, Ewing, Reid and Silverman (1955), constructs that partition left-to-right with a block stack:

  1. Read the next observation and push it as a single-element block.
  2. While the last block’s mean is below its predecessor’s, merge them with weighted mean and total weight.
  3. Repeat step 1 until data are exhausted. Stack blocks are the solution.

Each observation is pushed once and each merge reduces block count by one, so there are at most n−1n - 1 merges and total cost O(n)\bigO(n) after sorting, O(nlog⁡n)\bigO(n \log n) overall. You prove output optimality in an exercise: each merge preserves the prefix property.

InteractiveThe PAV algorithm
Labels ordered by model score and PAV blocks
0.000.330.500.670.671.001.00
Cumulative sum diagram (Wk,Sk)(W_k, S_k) and polyline through block endpoints
S = sum of w·y
  • data point (filled: already read)
  • stable block
  • violating blocks
  • newly merged block
Data
step 22 of 22
Data points read14 of 14
Blocks on the stack7
Merges so far7
Weighted squared error (data read)2.500
Done: 7 non-decreasing blocks and no violations. Fitted values are block means and match the slopes of the convex minorant in the lower diagram.
Above, score-ordered data and stack blocks. Step forward: each point enters as a block; if below its predecessor (red), they merge at their weighted mean (orange) and recheck backward, sometimes repeatedly. Below, cumulative sum diagram (Wk,Sk)(W_k, S_k) with Wk=∑j≤kwjW_k = \sum_{j \le k} w_j and Sk=∑j≤kwjyjS_k = \sum_{j \le k} w_j y_j: each polygon segment's slope is a block mean. On completion the polygon is convex and below all points. Click points to change labels and try weighted mode.

The lower diagram is the classical isotonic characterization: the solution is the left derivative of the greatest convex minorant of points (Wk,Sk)(W_k, S_k), the largest convex function below all of them. The prefix property says exactly this: a prefix with mean above its block’s corresponds to a diagram point above the block’s chord. PAV turns the data polygon into its lower convex envelope, merging whenever it finds a “concavity.”

Steps and overfitting

Isotonic has as many degrees of freedom as blocks, with block count growing with nn: the price of assuming no shape. With few data three symptoms appear, as in the first figure:

  • Large steps: piecewise flat probabilities, many different examples receiving identical probabilities. This introduces ties absent from original scores and slightly lowers AUC (in the lab 0.95480.9548 to 0.95410.9541 for GBDT).
  • High variance: an example’s block depends on a few neighbors.
  • Exact zeros and ones: if all lowest-scoring examples are negative, first block is 0 and any test example below gets probability 0. One positive among them makes log-loss infinite. In the lab isotonic assigns exactly 0 or 1 to 169 of 4000 GBDT test examples and misses one. With usual clipping to [10−15,1−10−15][10^{-15}, 1 - 10^{-15}] that one contributes 0.00860.0086 to mean log-loss, most of the gap between isotonic (0.28010.2801) and Platt (0.26900.2690); without clipping it is infinite.

Beta calibration

Between Platt’s rigidity and isotonic variance is a probabilistically grounded middle ground.

Origin. If each class’s scores follow beta distributions s∣Y=k∼Beta⁡(αk,βk)s \given Y = k \sim \operatorname{Beta}(\alpha_k, \beta_k), Bayes’ rule gives

logit⁡P(Y=1∣s)=log⁡π1 sα1−1(1−s)β1−1/B(α1,β1)π0 sα0−1(1−s)β0−1/B(α0,β0)=(α1−α0)ln⁡s+(β1−β0)ln⁡(1−s)+c,\operatorname{logit}\Pr(Y = 1 \given s) = \log\frac{\pi_1\, s^{\alpha_1 - 1}(1 - s)^{\beta_1 - 1} / B(\alpha_1, \beta_1)}{\pi_0\, s^{\alpha_0 - 1}(1 - s)^{\beta_0 - 1} / B(\alpha_0, \beta_0)} = (\alpha_1 - \alpha_0)\ln s + (\beta_1 - \beta_0)\ln(1 - s) + c,

which is the family with a=α1−α0a = \alpha_1 - \alpha_0 and b=β0−β1b = \beta_0 - \beta_1. The beta distribution lives on [0,1][0, 1] and can be highly asymmetric, exactly like Naive Bayes or AdaBoost probabilities; Platt’s Gaussians cannot.

What it contains. With a=b=1a = b = 1 and c=0c = 0 the map is identity, so a calibrated model can remain unchanged. With a=ba = b, since ln⁡s−ln⁡(1−s)=logit⁡s\ln s - \ln(1 - s) = \operatorname{logit} s, the map is σ(alogit⁡s+c)\sigma(a \operatorname{logit} s + c): Platt on log-odds. Beta is Platt plus one degree of freedom.

What it adds. In log-odds with z=logit⁡sz = \operatorname{logit} s, ln⁡s=−log⁡(1+e−z)→z\ln s = -\log(1 + e^{-z}) \to z when z→−∞z \to -\infty and −ln⁡(1−s)=log⁡(1+ez)→z-\ln(1 - s) = \log(1 + e^{z}) \to z when z→+∞z \to +\infty. Thus logit⁡g^≈az+c\operatorname{logit}\hat g \approx a z + c in the left tail and ≈bz+c\approx b z + c in the right: beta applies a different temperature to each tail. A model overconfident only when saying “positive” (the first figure’s asymmetric distortion, with a=1a = 1 and b=0.3b = 0.3) is invisible to Platt, which has one slope.

Why a,b≥0a, b \ge 0. The derivative of logit⁡g^\operatorname{logit}\hat g with respect to ss is a/s+b/(1−s)a/s + b/(1 - s), nonnegative for every ss exactly when a,b≥0a, b \ge 0. If unconstrained fitting gives a negative coefficient, the map is nonmonotonic; a simple solution used here drops that feature and refits with the other.

InteractiveThe beta family
Probability: g^(s)\hat g(s) versus ss
Log-odds: logit⁡g^\operatorname{logit}\hat g versus z=logit⁡sz = \operatorname{logit} s
diagonal: identidad
  • beta map g^\hat g
  • left asymptote: slope aa
  • right asymptote: slope bb
1.00
0.30
0.49
g^(0.5)\hat g(0.5)0.500
g^(0.01)\hat g(0.01)0.016
g^(0.99)\hat g(0.99)0.865
When aa and bb differ, the tails have different slopes: 1.00 on the left and 0.30 on the right. No sigmoid of log-odds draws this curve.
The beta calibrator formula without data. Left in probability; right in log-odds, where Platt on log-odds is a line and beta a curve moving from slope aa in the left tail to bb in the right (dashed lines). Start with the first interactive's asymmetric shape; set a=ba = b for a line; set a=b=1a = b = 1, c=0c = 0 for identity. The last shape is the lab's Naive Bayes fit: which tail is more overconfident?

Multiclass: temperature, vector and matrix scaling

With KK classes the model returns logits z∈RK\vb{z} \in \R^K and probabilities softmax⁡(z)\softmax(\vb{z}), as in softmax regression. Guo, Pleiss, Sun and Weinberger (2017) found modern deep networks much worse calibrated than those a decade earlier, consistently overconfident. Their CIFAR-100 ResNet-110 has ECE 16.53%. They associate this with depth, width, batch normalization and lack of weight decay, interpreting it as NLL overfitting: classification error keeps falling at the cost of worse-modeled probabilities (they caution causality cannot be claimed). Their remedy is maximally simple.

With T>1T > 1 distributions flatten and with T<1T < 1 sharpen; T→∞T \to \infty yields uniform and T→0+T \to 0^+ concentrates all mass at argmax. Three useful properties:

  1. No prediction changes. Dividing all logits by the same T>0T > 0 preserves ordering, so argmax and accuracy are identical for every TT (proved in an exercise). This is the only correction here guaranteeing classification does not worsen.
  2. Entropy grows with TT. With β=1/T\beta = 1/T and pk∝eβzkp_k \propto e^{\beta z_k} entropy is H(β)=log⁡∑keβzk−β Ep[z]H(\beta) = \log\sum_k e^{\beta z_k} - \beta\,\E_p[z] and differentiation gives H′(β)=Ep[z]−Ep[z]−βVar⁡p(z)=−βVar⁡p(z)≤0H'(\beta) = \E_p[z] - \E_p[z] - \beta\Var_p(z) = -\beta\Var_p(z) \le 0. Raising TT lowers β\beta: more entropy, less confidence, always in the same direction.
  3. Convex in β\beta. NLL as a function of β\beta is 1n∑i[log⁡∑keβzik−βziyi]\frac1n\sum_i \big[\log\sum_k e^{\beta z_{ik}} - \beta z_{i y_i}\big], with second derivative mean logit variance under the model 1n∑iVar⁡pi(zi)≥0\frac1n\sum_i \Var_{p_i}(z_i) \ge 0. It need not be convex in TT but is in β\beta, and Newton converges smoothly. The first-order condition is
1n∑iziyi=1n∑i∑kpik zik:\frac1n\sum_i z_{i y_i} = \frac1n\sum_i \sum_k p_{ik}\, z_{ik}:

mean true-class logit equals the model-expected mean logit. Guo et al. prove (supplement claim 1) that temperature softmax uniquely solves maximum entropy under that same constraint.

InteractiveTemperature scaling
Softmax of three test examples with T=1.00T = 1.00 (outline: T=1T = 1)
Acierto seguroc1c2c31.00c4Error seguroc11.00c2c3c4Caso dudosoc1c20.21c30.32c40.47
Reliability diagram for predicted test class (10 bins; opacity: number of examples)
bar height: bin accuracy
Mean NLL versus TT: minimum calibration NLL is at T∗T^*
T* = 2.915
  • probability (true class in teal)
  • accuracy per bin
  • gap to mean bin confidence
  • calibration NLL
  • test NLL
1.00
TT1.000
Calibration NLL (1000)0.9601
Test NLL (3000)1.0681
Test ECE (15 bins)0.1648
Mean test confidence90.6 %
Test accuracy74.2 %
At T=1.00<T∗T = 1.00 < T^* the network remains overconfident: mean confidence 90.6 % versus accuracy 74.2 %. The bars lie below the diagonal.
Actual logits of the lab's overconfident network: a two-hidden-layer perceptron with 64 units, no regularization, 100% training accuracy and 74.2% on 3000 test examples. Move TT and inspect three views: softmax bars of three examples (outline: T=1T = 1), test predicted-class reliability with gap to diagonal in red, and calibration NLL (solid) and test NLL (dashed) versus TT. With T=1T = 1, which side of diagonal are bars? Press 'T=T∗T = T^*'. Has accuracy moved?

With T=1T = 1 mean test confidence is 90.6% for 74.2% accuracy, and the figure’s confident error puts nearly all mass on a wrong class. Calibration NLL minimizes at T∗=2.915T^* = 2.915: mean confidence falls to 74.9%, test NLL 1.0681.068 to 0.65250.6525 and ECE 0.1650.165 to 0.0160.016. Test curve minimizes nearly at calibration’s location because one parameter can barely overfit a thousand examples.

More parameters. Guo et al. compared two generalizations. Vector scaling uses z↦w⊙z+b\vb{z} \mapsto \vb{w} \odot \vb{z} + \vb{b} with 2K2K parameters; matrix scaling uses z↦Wz+b\vb{z} \mapsto \mat{W}\vb{z} + \vb{b} with K2+KK^2 + K. Neither generally preserves argmax. In table 1 with CIFAR-100 ResNet-110 and 5000 validation examples, ECE goes from 16.53% to 1.26% with temperature, 1.32% with vector scaling and 25.49% with matrix scaling: with 100 classes its 10 100 parameters overfit, and on ImageNet it does not converge. In binary classification temperature is Platt on log-odds with b=0b = 0; Platt is “temperature plus bias.”

One versus rest. CalibratedClassifierCV with method="sigmoid" or "isotonic" separately calibrates each kk column as binary “class kk versus rest,” then renormalizes KK probabilities to sum to 1. It is flexible, but each class has a different monotonic transformation and argmax can change after renormalization. The scikit-learn lab checks this.

Calibrators from scratch

The lesson fits into a dozen functions. logistic_newton is Lin, Lin and Weng’s backtracking Newton for any feature count, serving Platt (two variables) and beta (three). pav is the block stack. temperature_fit applies Newton in β=1/T\beta = 1/T using the previous section’s gradient and second derivative. Final checks compare PAV with IsotonicRegression and generate known-parameter data to see if Platt and temperature recover them.

[ ]Platt, PAV, beta and temperature from scratchBrowser
import numpy as np
from sklearn.isotonic import IsotonicRegression

def sigmoid(t):
    e = np.exp(-np.abs(t))
    return np.where(t >= 0, 1 / (1 + e), e / (1 + e))

def log1pexp(t):                                # log(1 + e^t) sin desbordamiento
    return np.maximum(t, 0) + np.log1p(np.exp(-np.abs(t)))

def logistic_newton(X, t, tol=1e-12, max_iter=100):
    """min_w  sum_i [log(1 + e^{z_i}) - t_i z_i],  z = X w,  por Newton con backtracking."""
    w = np.zeros(X.shape[1])
    F = lambda w: np.sum(log1pexp(X @ w) - t * (X @ w))
    f = F(w)
    for _ in range(max_iter):
        p = sigmoid(X @ w)
        g = X.T @ (p - t)
        H = (X * (p * (1 - p))[:, None]).T @ X + 1e-10 * np.eye(X.shape[1])
        d = -np.linalg.solve(H, g)
        if -(g @ d) < tol:                      # decremento de Newton: ya estamos en el mínimo
            break
        a = 1.0
        while F(w + a * d) > f + 1e-4 * a * (g @ d) and a > 1e-10:
            a /= 2                              # retroceso (condición de Armijo)
        w = w + a * d
        f = F(w)
    return w

def platt_fit(s, y):
    """Escalado de Platt: p = sigmoid(a s + b), ajustado con los objetivos suavizados."""
    n_pos = y.sum(); n_neg = len(y) - n_pos
    t = np.where(y == 1, (n_pos + 1) / (n_pos + 2), 1 / (n_neg + 2))
    return logistic_newton(np.column_stack([s, np.ones_like(s)]), t)

def platt_predict(ab, s):
    return sigmoid(ab[0] * s + ab[1])

def pav(y, w=None):
    """Regresión isotónica no decreciente de y con pesos w: pila de bloques, tiempo lineal."""
    y = np.asarray(y, dtype=float)
    w = np.ones_like(y) if w is None else np.asarray(w, dtype=float)
    val, wt, cnt = [], [], []                   # media, peso y tamaño de cada bloque
    for yi, wi in zip(y, w):
        val.append(yi); wt.append(wi); cnt.append(1)
        while len(val) > 1 and val[-2] > val[-1]:   # dos bloques adyacentes violan: fusión
            v, ww, c = val.pop(), wt.pop(), cnt.pop()
            val[-1] = (val[-1] * wt[-1] + v * ww) / (wt[-1] + ww)
            wt[-1] += ww; cnt[-1] += c
    return np.repeat(val, cnt)

def isotonic_fit(s, y):
    """Calibrador isotónico: agrupa empates, aplica PAV e interpola linealmente (como sklearn)."""
    u, inv = np.unique(s, return_inverse=True)
    n_u = np.bincount(inv)
    return u, pav(np.bincount(inv, weights=y) / n_u, n_u)

def isotonic_predict(model, s):
    u, f = model
    return np.interp(s, u, f)                   # fuera del rango, el valor del extremo

def beta_fit(log_s, log_1ms, y):
    """Calibración beta: regresión logística sobre (ln s, -ln(1 - s)) con a, b >= 0."""
    X = np.column_stack([log_s, -log_1ms, np.ones_like(log_s)])
    abc = logistic_newton(X, y.astype(float))
    if abc[0] < 0:                              # coeficiente negativo: se quita esa variable
        abc = np.r_[0.0, logistic_newton(X[:, 1:], y.astype(float))]
    elif abc[1] < 0:
        a, c = logistic_newton(X[:, [0, 2]], y.astype(float))
        abc = np.array([a, 0.0, c])
    return abc

def beta_predict(abc, log_s, log_1ms):
    return sigmoid(abc[0] * log_s - abc[1] * log_1ms + abc[2])

def softmax_rows(Z):
    E = np.exp(Z - Z.max(axis=1, keepdims=True))
    return E / E.sum(axis=1, keepdims=True)

def temperature_fit(Z, y, tol=1e-12):
    """Escalado de temperatura: Newton en beta = 1/T sobre la NLL, que es convexa en beta."""
    beta, zy = 1.0, Z[np.arange(len(y)), y]
    for _ in range(100):
        P = softmax_rows(beta * Z)
        Ez = (P * Z).sum(axis=1)                # logit esperado bajo el modelo
        g = np.mean(Ez - zy)                    # dNLL/dbeta
        h = np.mean((P * Z**2).sum(axis=1) - Ez**2)   # d2NLL/dbeta2: varianza media de los logits
        step = g / h
        while beta - step <= 0:                 # beta tiene que seguir siendo positivo
            step /= 2
        beta -= step
        if abs(step) < tol:
            break
    return 1 / beta

# comprobaciones con parámetros conocidos
rng = np.random.default_rng(0)
y_ = rng.normal(size=3000).cumsum() * 0.05 + rng.normal(size=3000)
w_ = rng.uniform(0.5, 2.0, size=3000)
ref = IsotonicRegression().fit_transform(np.arange(3000), y_, sample_weight=w_)
print("PAV frente a IsotonicRegression: diferencia máxima", np.abs(pav(y_, w_) - ref).max())
z_ = rng.normal(0, 2, size=20000)
y_bin = (rng.random(20000) < sigmoid(0.5 * z_ - 0.3)).astype(float)
print("Platt sobre datos con log-odds verdadero 0.5 z - 0.3: (a, b) =", np.round(platt_fit(z_, y_bin), 3))
Z_ = rng.normal(size=(20000, 5)) * 3
u_ = rng.random(20000)
y_mc = (softmax_rows(Z_ / 2.5).cumsum(axis=1) < u_[:, None]).sum(axis=1)   # etiquetas con T = 2.5
print("temperatura estimada sobre datos generados con T = 2.5:", round(temperature_fit(Z_, y_mc), 3))

PAV matches IsotonicRegression up to rounding, and Platt and temperature recover parameters within the error expected from 20 000 examples.

Now the motivation’s two models. make_classification data have 20 features, 5 informative and 10 linear combinations, so many are highly correlated, and 3% randomly assigned labels. Three disjoint sets: 5000 training, 3000 calibration, 4000 measurement. First model is gradient boosting (HistGradientBoostingClassifier with 60 trees and learning rate 0.30.3, no early stopping); second Gaussian Naive Bayes. Both log-odds calibrators apply to each model’s log-odds, provided by GBDT decision_function and Naive Bayes predict_log_proba difference, avoiding pp, which saturates at 0 or 1 on many rows.

[ ]Recalibrate a GBDT and Naive BayesBrowser
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import roc_auc_score

def log_loss(y, p):
    p = np.clip(p, 1e-15, 1 - 1e-15)
    return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))

def brier(y, p):
    return np.mean((p - y) ** 2)

def ece(y, p, M=15):                            # 15 bins de igual anchura sobre P(y = 1)
    b = np.minimum((p * M).astype(int), M - 1)
    return sum(np.mean(b == k) * abs(y[b == k].mean() - p[b == k].mean()) for k in range(M) if np.any(b == k))

X, y = make_classification(n_samples=12000, n_features=20, n_informative=5, n_redundant=10,
                           flip_y=0.03, class_sep=0.8, random_state=0)
X_tr, y_tr = X[:5000], y[:5000]                 # entrenar el modelo
X_cal, y_cal = X[5000:8000], y[5000:8000]       # ajustar el calibrador
X_te, y_te = X[8000:], y[8000:]                 # medir

gb = HistGradientBoostingClassifier(max_iter=60, learning_rate=0.3, max_bins=63, early_stopping=False,
                                    random_state=0).fit(X_tr, y_tr)
nb = GaussianNB().fit(X_tr, y_tr)

def log_odds(model, X):
    if hasattr(model, "decision_function"):     # GBDT: su salida cruda ya es un log-odds
        return model.decision_function(X)
    L = model.predict_log_proba(X)              # NB: log-odds directo, sin pasar por p, que satura
    return L[:, 1] - L[:, 0]

for nombre, modelo in [("GBDT", gb), ("Naive Bayes", nb)]:
    z_cal, z_te = log_odds(modelo, X_cal), log_odds(modelo, X_te)
    ab = platt_fit(z_cal, y_cal)
    iso = isotonic_fit(z_cal, y_cal)
    abc = beta_fit(-log1pexp(-z_cal), -log1pexp(z_cal), y_cal)   # ln s = -log(1 + e^-z), ln(1 - s) = -log(1 + e^z)
    preds = {"sin calibrar": sigmoid(z_te),
             "Platt": platt_predict(ab, z_te),
             "isotónica": isotonic_predict(iso, z_te),
             "beta": beta_predict(abc, -log1pexp(-z_te), -log1pexp(z_te))}
    print(f"{nombre}: exactitud test {np.mean((z_te > 0) == y_te):.4f}   Platt (a, b) = ({ab[0]:.3f}, {ab[1]:.3f})   "
          f"beta (a, b, c) = ({abc[0]:.3f}, {abc[1]:.3f}, {abc[2]:.3f})   bloques isotónicos: {len(np.unique(iso[1]))}")
    for k, p in preds.items():
        print(f"   {k:13s} log-loss {log_loss(y_te, p):.4f}   Brier {brier(y_te, p):.4f}   ECE {ece(y_te, p):.4f}   AUC {roc_auc_score(y_te, p):.4f}")
    p_iso = preds["isotónica"]
    ext = (p_iso == 0) | (p_iso == 1)
    fall = ext & (p_iso != y_te)
    print(f"   isotónica: {ext.sum()} predicciones exactamente 0 o 1, {fall.sum()} falladas, que aportan"
          f" {fall.sum() * -np.log(1e-15) / len(y_te):.4f} a la log-loss media (con el recorte a 1e-15)")

What the output says, model by model:

  • GBDT. Platt slope a=0.696a = 0.696: the model exaggerates log-odds by about 44% (1/0.696≈1.441/0.696 \approx 1.44). Correction lowers log-loss 0.29240.2924 to 0.26900.2690 and ECE 0.0410.041 to 0.0130.013. Beta finds a≈ba \approx b (0.6860.686 and 0.7160.716): distortion is nearly symmetric, beta reduces to Platt and they tie. Isotonic improves on uncalibrated but trails Platt on all three metrics, especially log-loss, because of the previously discussed exact-probability error.
  • Naive Bayes. More overconfident (a=0.588a = 0.588), also asymmetric: beta gives a=0.424a = 0.424 and b=0.815b = 0.815, making the negative tail much more exaggerated. This is Naive Bayes with redundant features counting the same evidence repeatedly. With 3000 calibration examples isotonic has enough data to follow that shape and wins all three: log-loss 0.36970.3697, Brier 0.11130.1113, ECE 0.0180.018. Beta lies between on log-loss (0.37020.3702 versus Platt 0.37300.3730).
  • Both Platt and beta AUCs equal uncalibrated AUC: both are strictly increasing.

Temperature needs a multiclass model. The temperature figure’s network comes from this cell: four overlapping make_classification classes (class_sep=0.8), 1000 examples training a two-hidden-layer 64-unit perceptron without regularization (alpha=0), 1000 calibration and 3000 test. Logits are recomputed manually from network weights to avoid probabilities.

[ ]Temperature scaling for a multiclass networkBrowser
import numpy as np
from sklearn.datasets import make_classification
from sklearn.neural_network import MLPClassifier

Xm, ym = make_classification(n_samples=5000, n_features=20, n_informative=6, n_redundant=4, n_classes=4,
                             class_sep=0.8, flip_y=0.0, random_state=1)
Xm_tr, ym_tr = Xm[:1000], ym[:1000]
Xm_cal, ym_cal = Xm[1000:2000], ym[1000:2000]
Xm_te, ym_te = Xm[2000:], ym[2000:]
red = MLPClassifier(hidden_layer_sizes=(64, 64), alpha=0.0, max_iter=200, random_state=0).fit(Xm_tr, ym_tr)

def logits(red, X):                             # salida de la última capa, antes de la softmax
    a = X
    for i, (W, b) in enumerate(zip(red.coefs_, red.intercepts_)):
        a = a @ W + b
        if i < len(red.coefs_) - 1:
            a = np.maximum(a, 0)
    return a

def nll(Z, y):
    Zs = Z - Z.max(axis=1, keepdims=True)
    return np.mean(np.log(np.exp(Zs).sum(axis=1)) - Zs[np.arange(len(y)), y])

def ece_top(P, y, M=15):                        # ECE de la clase predicha (top-label), 15 bins
    conf, acierto = P.max(axis=1), P.argmax(axis=1) == y
    b = np.minimum((conf * M).astype(int), M - 1)
    return sum(np.mean(b == k) * abs(acierto[b == k].mean() - conf[b == k].mean()) for k in range(M) if np.any(b == k))

Z_cal, Z_te = logits(red, Xm_cal), logits(red, Xm_te)
assert np.allclose(softmax_rows(Z_te), red.predict_proba(Xm_te))
T = temperature_fit(Z_cal, ym_cal)
print(f"exactitud: entrenamiento {red.score(Xm_tr, ym_tr):.3f}, test {red.score(Xm_te, ym_te):.3f}")
print(f"T* = {T:.3f}")
for nombre, Tk in [("T = 1", 1.0), ("T = T*", T)]:
    P = softmax_rows(Z_te / Tk)
    print(f"{nombre:7s} NLL test {nll(Z_te / Tk, ym_te):.4f}   ECE {ece_top(P, ym_te):.4f}   confianza media {P.max(1).mean():.3f}"
          f"   exactitud {np.mean(P.argmax(1) == ym_te):.3f}")

One number corrects nearly all overconfidence, while accuracy stays 0.7420.742 in both rows. Next see what more-parameter calibrators add and their cost with few data. The next cell fits vector and matrix scaling by NLL with L-BFGS (analytic gradient) on calibration subsamples of 1000, 100 and 30.

[ ]Temperature, vector and matrix scaling with little dataBrowser
import numpy as np
from scipy.optimize import minimize

def scaling_fit(Z, y, tipo):
    """Vector scaling (z * w + b, 2K parámetros) o matrix scaling (W z + b, K^2 + K) por NLL con L-BFGS."""
    K = Z.shape[1]
    def aplica(th, Z):
        if tipo == "vector":
            return Z * th[:K] + th[K:]
        return Z @ th[:K * K].reshape(K, K).T + th[K * K:]
    def f(th):
        L = aplica(th, Z)
        Ls = L - L.max(axis=1, keepdims=True)
        P = np.exp(Ls); P /= P.sum(axis=1, keepdims=True)
        G = P.copy(); G[np.arange(len(y)), y] -= 1; G /= len(y)      # dNLL/dL
        grad = np.r_[(G * Z).sum(axis=0), G.sum(axis=0)] if tipo == "vector" else np.r_[(G.T @ Z).ravel(), G.sum(axis=0)]
        return np.mean(np.log(np.exp(Ls).sum(axis=1)) - Ls[np.arange(len(y)), y]), grad
    th0 = np.r_[np.ones(K), np.zeros(K)] if tipo == "vector" else np.r_[np.eye(K).ravel(), np.zeros(K)]
    th = minimize(f, th0, jac=True, method="L-BFGS-B").x
    return lambda Z: aplica(th, Z)

rng = np.random.default_rng(0)
print(f"logits originales: mediana en test del mayor |logit| de cada fila {np.median(np.abs(Z_te).max(axis=1)):.1f}")
print(f"{'n_cal':>6s} {'método':>9s} {'parám.':>6s} {'NLL cal':>8s} {'NLL test':>9s} {'ECE test':>9s} {'exact. test':>11s} {'med. máx|L|':>11s}")
for n_cal in [1000, 100, 30]:
    idx = rng.choice(len(ym_cal), n_cal, replace=False) if n_cal < len(ym_cal) else np.arange(len(ym_cal))
    Zc, yc = Z_cal[idx], ym_cal[idx]
    Tn = temperature_fit(Zc, yc)
    metodos = {"T": (lambda Z: Z / Tn, 1), "vector": (scaling_fit(Zc, yc, "vector"), 8),
               "matrix": (scaling_fit(Zc, yc, "matrix"), 20)}
    for nombre, (f, k) in metodos.items():
        L = f(Z_te)
        print(f"{n_cal:6d} {nombre:>9s} {k:6d} {nll(f(Zc), yc):8.4f} {nll(L, ym_te):9.4f} {ece_top(softmax_rows(L), ym_te):9.4f}"
              f" {np.mean(L.argmax(axis=1) == ym_te):11.3f} {np.median(np.abs(L).max(axis=1)):11.1f}")

With 1000 examples all three are close (NLL 0.65250.6525, 0.65820.6582 and 0.65980.6598), temperature best with one parameter: network distortion is mainly excess scale. With 100, vector rises to 0.71010.7101 and matrix to 0.80640.8064 while temperature stays fixed. With 30, matrix NLL shoots to 15.3515.35: with 20 parameters and 30 examples, maximum likelihood lowers calibration NLL to 0.20210.2021 by amplifying scale, and the last column measures it: median maximum absolute test-row logit becomes 88.588.5 versus 3.03.0 for temperature and 9.59.5 original. Such logits make each test error assign nearly zero probability to the true class. This reproduces Guo et al.’s 100-class pattern with four classes and little data.

Protocol: calibrate without leakage

So far calibrators always used data unseen by the model. The reason is the same as data leakage: models behave differently on training and new data, and calibrators learn what they see.

[ ]Calibrating on training dataBrowser
z_tr, z_cal, z_te = (gb.decision_function(A) for A in (X_tr, X_cal, X_te))
ab_tr = platt_fit(z_tr, y_tr)
ab_cal = platt_fit(z_cal, y_cal)
print(f"exactitud del GBDT: entrenamiento {gb.score(X_tr, y_tr):.4f}, test {gb.score(X_te, y_te):.4f}")
for nombre, ab_ in [("datos de entrenamiento", ab_tr), ("datos de calibración", ab_cal)]:
    p = platt_predict(ab_, z_te)
    print(f"Platt con {nombre:23s} a = {ab_[0]:.3f}, b = {ab_[1]:+.3f}   log-loss test {log_loss(y_te, p):.4f}   ECE {ece(y_te, p):.4f}")
print(f"sin calibrar {'':34s} log-loss test {log_loss(y_te, sigmoid(z_te)):.4f}   ECE {ece(y_te, sigmoid(z_te)):.4f}")

The GBDT gets 99.98% training accuracy. From there a model saying “95%” and nearly always correct looks underconfident, so Platt responds with a=3.274a = 3.274, multiplying log-odds by more than three. On test the model was overconfident (a=0.696a = 0.696 with clean data), so the contaminated calibrator pushes precisely the wrong way: log-loss rises from 0.29240.2924 uncalibrated to 0.71500.7150. Training-data calibration does not merely add noise; it learns the opposite distortion.

There are two correct ways to get clean scores.

Separate calibration set. This is what you have done. Simple and the only choice for an already-trained model (e.g., a network you will not retrain), but calibration examples cannot train the model.

CalibratedClassifierCV implements cross-fitting in two variants:

  • ensemble=True (default unless estimator is frozen): per fold, one model trained on the other K−1K - 1 and calibrator fitted on the excluded fold. At prediction average KK pair probabilities.
  • ensemble=False: obtain out-of-fold scores with cross_val_predict, fit one calibrator on all and apply it to a model retrained on all data. This is SVC(probability=True)’s procedure. There is a slight mismatch: calibrator learned distortion of models trained on (K−1)/K(K-1)/K of data and applies to one trained on all, often more confident.

Resampling and prior correction. With highly imbalanced classes (class imbalance), negative subsampling is common: retain each negative with probability β\beta and all positives. The model learns posterior probability in a world where negatives are 1/β1/\beta times rarer:

ps(x)=π1p(x∣1)π1p(x∣1)+β π0p(x∣0)⟹ps1−ps=1β⋅p1−p.p_s(\vb{x}) = \frac{\pi_1 p(\vb{x} \given 1)}{\pi_1 p(\vb{x} \given 1) + \beta\, \pi_0 p(\vb{x} \given 0)} \quad\Longrightarrow\quad \frac{p_s}{1 - p_s} = \frac{1}{\beta}\cdot\frac{p}{1 - p}.

Solving for the original-population probability gives

p=β psβ ps−ps+1,logit⁡p=logit⁡ps+ln⁡β.p = \frac{\beta\, p_s}{\beta\, p_s - p_s + 1}, \qquad \operatorname{logit} p = \operatorname{logit} p_s + \ln\beta.

Correction is a constant log-odds shift, so Platt on log-odds contains it (a=1a = 1, b=ln⁡βb = \ln\beta). Duplicating each positive kk times is the same with β=1/k\beta = 1/k, and class weights in a weighted loss act likewise. Correction holds only if subsampling was genuinely random within each class and deployment prevalence matches the original dataset.

Threshold and calibration, each with its own data. Choosing a decision threshold on the recalibration set makes estimated cost doubly optimistic. With well-calibrated probabilities no threshold search is needed: the minimum-cost threshold is cFP/(cFP+cFN)c_{\text{FP}}/(c_{\text{FP}} + c_{\text{FN}}). If tuning anyway, use a third set or nest the procedure.

The protocol with scikit-learn

First reproduce our results. FrozenEstimator wraps an already trained model so CalibratedClassifierCV does not retrain it and uses all supplied data for calibration (replacing the removed cv="prefit").

[ ]CalibratedClassifierCV versus custom calibratorsBrowser
import numpy as np
from sklearn.calibration import CalibratedClassifierCV
from sklearn.frozen import FrozenEstimator

for nombre, modelo in [("GBDT", gb), ("Naive Bayes", nb)]:
    for metodo in ["sigmoid", "isotonic"]:
        cal = CalibratedClassifierCV(FrozenEstimator(modelo), method=metodo).fit(X_cal, y_cal)
        p = cal.predict_proba(X_te)[:, 1]
        print(f"{nombre:12s} {metodo:9s} log-loss {log_loss(y_te, p):.4f}   Brier {brier(y_te, p):.4f}")

# GaussianNB no tiene decision_function: sklearn le pasa predict_proba, y Platt se ajusta sobre p en [0, 1]
z_cal_nb, z_te_nb = log_odds(nb, X_cal), log_odds(nb, X_te)
p_cal_nb, p_te_nb = nb.predict_proba(X_cal)[:, 1], nb.predict_proba(X_te)[:, 1]
ab_p, ab_z = platt_fit(p_cal_nb, y_cal), platt_fit(z_cal_nb, y_cal)
cal_nb = CalibratedClassifierCV(FrozenEstimator(nb), method="sigmoid").fit(X_cal, y_cal)
print("\nNaive Bayes, Platt propio sobre p:        log-loss", f"{log_loss(y_te, platt_predict(ab_p, p_te_nb)):.4f}",
      "  diferencia máxima con sklearn:", f"{np.abs(platt_predict(ab_p, p_te_nb) - cal_nb.predict_proba(X_te)[:, 1]).max():.1e}")
print("Naive Bayes, Platt propio sobre log-odds: log-loss", f"{log_loss(y_te, platt_predict(ab_z, z_te_nb)):.4f}")
print(f"fracción de p del NB por encima de 0.999 o por debajo de 0.001: {np.mean((p_cal_nb > 0.999) | (p_cal_nb < 0.001)):.3f}")

For GBDT, sklearn matches your functions (0.26900.2690 and 0.28010.2801) because it calibrates decision_function, the log-odds. For Naive Bayes it calibrates pp, and your Platt on pp matches within 10−1010^{-10} (optimizer tolerance). Here Platt on pp is slightly better than log-odds (0.37120.3712 versus 0.37300.3730): with asymmetric distortion sigmoids of pp and zz are distinct approximations neither dominating. The argument against pp is identity: when calibrated, Platt on pp harms at any sample size, as in the first figure. If uncertain, beta contains log-odds Platt and identity, follows asymmetric distortions and improves both Platts here (0.37020.3702) for one extra parameter.

Now cross-fitting. Instead of holding out 3000 examples use all 8000 training and calibration examples in five folds, compared with an uncalibrated model trained on all 8000.

[ ]Cross-fitting: ensemble=True versus ensemble=FalseBrowser
import numpy as np
from sklearn.calibration import CalibratedClassifierCV
from sklearn.ensemble import HistGradientBoostingClassifier

X_all, y_all = X[:8000], y[:8000]
base = HistGradientBoostingClassifier(max_iter=60, learning_rate=0.3, max_bins=63, early_stopping=False, random_state=0)
print(f"{'variante':38s} {'log-loss':>9s} {'Brier':>7s} {'AUC':>7s}")
p = base.fit(X_all, y_all).predict_proba(X_te)[:, 1]
print(f"{'GBDT con 8000, sin calibrar':38s} {log_loss(y_te, p):9.4f} {brier(y_te, p):7.4f} {roc_auc_score(y_te, p):7.4f}")
for ens in [True, False]:
    cal = CalibratedClassifierCV(base, method="sigmoid", cv=5, ensemble=ens).fit(X_all, y_all)
    p = cal.predict_proba(X_te)[:, 1]
    print(f"{'GBDT + Platt, cv=5, ensemble=' + str(ens):38s} {log_loss(y_te, p):9.4f} {brier(y_te, p):7.4f} {roc_auc_score(y_te, p):7.4f}")

Three readings. Training on 8000 instead of 5000 already improves the uncalibrated model (0.26260.2626 versus 0.29240.2924). Both cross-fitting variants also improve on fixed separation, which reached 0.26900.2690 with Platt: they use all data for model and calibrator. ensemble=True wins clearly (0.24670.2467 versus 0.25480.2548) and alone raises AUC (0.95930.9593 to 0.96330.9633): averaging five GBDTs trained on different data is small bagging, reducing model variance as well as calibrating. ensemble=False preserves AUC exactly by applying an increasing function to one model. The first costs storing and evaluating KK production models; the second one.

Prior correction with positive class 5.5% and training on 10% of negatives:

[ ]Prior correction after subsamplingBrowser
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import HistGradientBoostingClassifier

Xr, yr = make_classification(n_samples=40000, n_features=20, n_informative=5, n_redundant=5,
                             weights=[0.95], flip_y=0.01, class_sep=0.8, random_state=2)
Xr_tr, yr_tr = Xr[:20000], yr[:20000]
Xr_cal, yr_cal = Xr[20000:25000], yr[20000:25000]
Xr_te, yr_te = Xr[25000:], yr[25000:]
beta = 0.1                                      # se conserva el 10 % de los negativos
rng = np.random.default_rng(0)
keep = (yr_tr == 1) | (rng.random(len(yr_tr)) < beta)
print(f"prevalencia: real {yr_tr.mean():.3f}, tras submuestrear {yr_tr[keep].mean():.3f} ({keep.sum()} ejemplos de entrenamiento)")
m = HistGradientBoostingClassifier(max_iter=60, learning_rate=0.3, max_bins=63, early_stopping=False,
                                   random_state=0).fit(Xr_tr[keep], yr_tr[keep])
p_s = m.predict_proba(Xr_te)[:, 1]
p_corr = beta * p_s / (beta * p_s - p_s + 1)    # corrección de priors
ab = platt_fit(m.decision_function(Xr_cal), yr_cal)
p_platt = platt_predict(ab, m.decision_function(Xr_te))
print(f"Platt sobre el conjunto de calibración natural: a = {ab[0]:.3f}, b = {ab[1]:.3f}   (ln beta = {np.log(beta):.3f})")
for nombre, p in [("sin corregir", p_s), ("corrección de priors", p_corr), ("Platt (calibración natural)", p_platt)]:
    print(f"{nombre:28s} media {p.mean():.4f}   log-loss {log_loss(yr_te, p):.4f}   Brier {brier(yr_te, p):.4f}   AUC {roc_auc_score(yr_te, p):.4f}")
print(f"{'frecuencia real en test':28s} {yr_te.mean():.4f}")

Uncorrected the model predicts mean positives 9.979.97% versus true 5.435.43%, log-loss 0.14170.1417. The prior formula uses no extra data and restores mean to 5.695.69% and log-loss to 0.09420.0942. Platt on true-prevalence calibration data does more: intercept b=−2.099b = -2.099 is near ln⁡β=−2.303\ln\beta = -2.303 as theory predicts, but also shrinks slope to a=0.573a = 0.573 because a GBDT trained on only about 3000 examples is overconfident. With the lowest log-loss of three (0.08040.0804), prior correction fixes resampling alone; recalibration on real-prevalence data fixes both. AUC is identical across rows: all three transformations increase.

Finally the multiclass case with CalibratedClassifierCV’s three options on the earlier network:

[ ]Multiclass: temperature versus one versus restBrowser
import numpy as np
from sklearn.calibration import CalibratedClassifierCV
from sklearn.frozen import FrozenEstimator

for metodo in ["temperature", "sigmoid", "isotonic"]:
    cal = CalibratedClassifierCV(FrozenEstimator(red), method=metodo).fit(Xm_cal, ym_cal)
    P = cal.predict_proba(Xm_te)
    extra = f"   T = {1 / cal.calibrated_classifiers_[0].calibrators[0].beta_:.3f}" if metodo == "temperature" else ""
    cambia = np.mean(P.argmax(1) != Z_te.argmax(1))   # predicciones distintas de las de la red
    print(f"{metodo:12s} NLL {nll(np.log(np.clip(P, 1e-15, 1)), ym_te):.4f}   ECE {ece_top(P, ym_te):.4f}"
          f"   exactitud {np.mean(P.argmax(1) == ym_te):.3f}   argmax cambiado {cambia:.1%}{extra}")
print(f"{'desde cero':12s} NLL {nll(Z_te / T, ym_te):.4f}   T = {T:.3f}")

sklearn temperature (available since 1.8, optimizing log⁡β\log\beta via bounded search) gives the same TT as your Newton. One-versus-rest Platt trails badly (NLL 0.77580.7758): MLPClassifier lacks decision_function, so each Platt fits a probability column rather than logits and renormalization cannot compensate. Argmax changes as warned: Platt on 0.4% of test examples (no net accuracy effect) and isotonic on 4.3%, lowering accuracy 0.7420.742 to 0.7330.733. Temperature changes 0.0%. For networks start with temperature.

Choosing the method and verifying improvement

The first figure has an explicit model, reproduced by the next cell with 20 repetitions per configuration. Model log-odds are z∼N(0,1.82)z \sim \Normal(0, 1.8^2) and true probability gg depends on distortion: g=σ(z)g = \sigma(z) when calibrated; g=σ(0.5z)g = \sigma(0.5 z) when overconfident; logit⁡g=ln⁡s−0.3ln⁡(1−s)+0.7ln⁡2\operatorname{logit} g = \ln s - 0.3\ln(1 - s) + 0.7\ln 2 (beta with a=1a = 1 and b=0.3b = 0.3) for asymmetric; and for the plateau gg is 0.50.5 for s∈[0.3,0.7]s \in [0.3, 0.7] and rises linearly to 0.050.05 and 0.950.95 at extremes. The interactive adds underconfidence g=σ(2z)g = \sigma(2z). Metric is excess Brier E[(g^(s)−g(s))2]\E[(\hat g(s) - g(s))^2], added above minimum achievable Brier, computed by quadrature over distribution zz.

[ ]Calibration set sizeBrowser
import numpy as np

SIGMA = 1.8
def g_true(tipo, z):
    s = sigmoid(z)
    if tipo == "calibrado":
        return s
    if tipo == "sobreconfiado":                 # logit g = 0.5 z: el modelo exagera
        return sigmoid(0.5 * z)
    if tipo == "asimétrico":                    # beta con a = 1, b = 0.3: solo exagera por arriba
        return sigmoid(1.0 * (-log1pexp(-z)) - 0.3 * (-log1pexp(z)) + 0.7 * np.log(2))
    if tipo == "meseta":                        # creciente pero no sigmoide: plana entre 0.3 y 0.7
        u = s - 0.5
        return 0.5 + 0.45 * np.sign(u) * np.maximum(0, np.abs(u) - 0.2) / 0.3

zq = np.linspace(-9, 9, 721)                    # cuadratura para las esperanzas sobre z
wq = np.exp(-zq**2 / (2 * SIGMA**2)); wq /= wq.sum()
lsq, l1sq = -log1pexp(-zq), -log1pexp(zq)

def exceso_brier(pred, g):                      # E[(ĝ(s) - g(s))^2]
    return np.sum(wq * (pred - g) ** 2)

rng = np.random.default_rng(1)
tamaños, R = [50, 200, 1000, 4000], 20
print(f"exceso de Brier medio (x 1e-4) en {R} repeticiones")
for tipo in ["calibrado", "sobreconfiado", "asimétrico", "meseta"]:
    gq = g_true(tipo, zq)
    print(f"{tipo:14s} sin calibrar: {1e4 * exceso_brier(sigmoid(zq), gq):6.1f}")
    for n in tamaños:
        e = {"Platt": [], "isotónica": [], "beta": []}
        for _ in range(R):
            z = rng.normal(0, SIGMA, n)
            yy = (rng.random(n) < g_true(tipo, z)).astype(float)
            e["Platt"].append(exceso_brier(platt_predict(platt_fit(z, yy), zq), gq))
            e["isotónica"].append(exceso_brier(isotonic_predict(isotonic_fit(z, yy), zq), gq))
            e["beta"].append(exceso_brier(beta_predict(beta_fit(-log1pexp(-z), -log1pexp(z), yy), lsq, l1sq), gq))
        print(f"   n = {n:5d}   " + "   ".join(f"{k} {1e4 * np.mean(v):6.1f}" for k, v in e.items()))

The table summarizes four cases:

  • Already calibrated. Every calibrator worsens it; with n=50n = 50 the harm is large: Platt adds 50.550.5 (units 10−410^{-4}), beta 72.472.4 and isotonic 172.1172.1. If previous diagnosis finds no clear issue and data are few, do not recalibrate.
  • Overconfident (a sigmoid). Platt is best at every nn: its family contains truth and estimates only two parameters. Isotonic needs n=4000n = 4000 to reach 8.58.5; Platt already reaches 3.53.5 with 1000.
  • Asymmetric. Platt plateaus near 1111 (12.712.7 with 1000, 11.311.3 with 4000): bias does not fall with more data. Beta contains truth and drops to 1.51.5, already beating Platt with 200 examples (23.423.4 versus 28.528.5); isotonic reaches 9.19.1 with 4000 and also beats it. With n=50n = 50, all three worsen the uncalibrated model (70.870.8): fitting variance outweighs corrected distortion.
  • Plateau. Neither parametric family contains this shape: Platt and beta plateau near 3030, and isotonic alone converges with 10001000 examples or more.

With n=50n = 50 isotonic is worst for all four distortions and worse than uncalibrated in overconfident and asymmetric cases. scikit-learn recommends against isotonic when calibration data are much fewer than about 1000. Practical rules:

  1. Few calibration data (hundreds): Platt on log-odds or, for multiclass, temperature. For probabilities of very biased models (Naive Bayes, AdaBoost), beta.
  2. Thousands of examples and unknown shape: isotonic, or beta if reliability looks smooth and you want to avoid steps and exact zeros.
  3. Multiclass with many classes: temperature before vector scaling; matrix scaling only with much data per parameter.
  4. Always decide with a proper rule (log-loss and Brier) on test data untouched by model and calibrator, and inspect test reliability. ECE describes, does not select, and AUC should stay equal or nearly equal as a monotonicity check.

Beyond: Venn–Abers and the door to conformal prediction

All previous calibrators return one number without guarantees. Vovk and Petej (2014) proposed Venn–Abers predictors built on isotonic regression: for a new score ss, fit isotonic twice, adding the example to calibration with labels 0 and 1, obtaining probabilities p0≤p1p_0 \le p_1. Their theorem 1 guarantees, assuming only iid data, that a selector exists for which selected PP is perfectly calibrated, E[Y∣P]=P\E[Y \given P] = P (the selector depends on the unknown true label, so the output is a pair, not one number). If one number is needed, minimizing worst-case log-loss regret gives p=p1/(1−p0+p1)p = p_1/(1 - p_0 + p_1). Width p1−p0p_1 - p_0 measures dependence on sample. If the model trained on other data, the score is a fixed function and the procedure applies directly to calibration.

[ ]Venn–Abers on Naive BayesBrowser
import numpy as np

def venn_abers(z_cal, y_cal, z_new):
    """Venn-Abers con el modelo fijo: isotónica con el punto nuevo etiquetado 0 y etiquetado 1."""
    p0, p1 = np.empty(len(z_new)), np.empty(len(z_new))
    for i, z in enumerate(z_new):
        for etiqueta, salida in [(0, p0), (1, p1)]:
            modelo = isotonic_fit(np.r_[z_cal, z], np.r_[y_cal, etiqueta])
            salida[i] = isotonic_predict(modelo, z)
    return p0, p1

sel = np.argsort(z_te_nb)[np.linspace(100, len(z_te_nb) - 100, 5).astype(int)]   # cinco ejemplos de test
rng = np.random.default_rng(0)
for n in [3000, 100]:
    idx = rng.choice(3000, n, replace=False)
    p0, p1 = venn_abers(z_cal_nb[idx], y_cal[idx], z_te_nb[sel])
    print(f"n_cal = {n}")
    for i in range(5):
        print(f"   log-odds NB {z_te_nb[sel[i]]:7.2f}   [p0, p1] = [{p0[i]:.3f}, {p1[i]:.3f}]   p = {p1[i] / (1 - p0[i] + p1[i]):.3f}")

With 3000 calibration examples intervals are narrow: none much wider than one hundredth ([0.012,0.025][0.012, 0.025] and [0.988,1.000][0.988, 1.000] in the tails). With 100, log-odds example −0.94-0.94 becomes [0.273,0.500][0.273, 0.500]: isotonic with 100 points knows little about that region, and Venn–Abers says so rather than hiding it. This is the idea developed in conformal prediction: validity guarantees without parametric assumptions, in exchange for sets or intervals rather than a number.

Common mistakes

Exercises

NumericPlatt targets
Your calibration set has 30 positives and 70 negatives. What target does Platt scaling use for each positive?
NumericUndo subsampling
You trained a model retaining 10% of negatives (β=0.1\beta = 0.1) and all positives. For a customer it predicts ps=0.6p_s = 0.6. What is the original-population probability?
NumericTemperature by hand
A network gives logits z=(4,2,0)\vb{z} = (4, 2, 0). At temperature T=2T = 2, what probability does it assign the predicted class?
Quiz200 examples and a sigmoid
A binary GBDT reliability diagram shows sigmoid distortion and you have 200 calibration examples unseen by the model. Which calibrator do you choose?
QuizA calibrator that worsens things
You fit Platt on training log-odds of a GBDT with 99.98% training and 89.6% test accuracy. What happens?
QuizWho can leave it unchanged?
Your binary model is already perfectly calibrated and you have an enormous calibration set. Which calibrators can return exactly the same probabilities in the limit?

More than one answer may be correct.

QuizThe two cross-fitting variants
For CalibratedClassifierCV(base, cv=5, ensemble=...) with default method='sigmoid', which statements are true?

More than one answer may be correct.

QuizMore parameters, worse calibration
With 30 calibration examples and a four-class network, test NLL was 0.6520.652 with temperature and 15.3515.35 with matrix scaling. Why?
ProofPAV returns the isotonic solution
Prove: Let y1,…,yny_1, \dots, y_n have weights wi>0w_i > 0. PAV's final blocks define the solution to min⁡∑iwi(yi−θi)2\min \sum_i w_i(y_i - \theta_i)^2 with θ1≤⋯≤θn\theta_1 \le \cdots \le \theta_n.
0
Use the lesson's KKT characterization: a consecutive-block partition is optimal if (i) each block takes its weighted mean of yjy_j, (ii) block means are nondecreasing and (iii) every block prefix has weighted mean at least the block mean. Call property (iii) for all stack blocks the invariant.

Step 1 of 4. Why does the invariant hold immediately after pushing a new observation?

ProofTemperature changes no predictions
Prove: For every T>0T > 0, arg max⁡ksoftmax⁡(z/T)k=arg max⁡kzk\argmax_k \softmax(\vb{z}/T)_k = \argmax_k z_k. Consequently temperature scaling does not change accuracy.
0
Write pk(T)=ezk/T/∑lezl/Tp_k(T) = e^{z_k/T}/\sum_l e^{z_l/T}.

Step 1 of 3. How do you compare classes jj and kk?

CodeWeighted PAV
Implement pav(y, w): given equal-length arrays y (values in score order) and w (positive weights), return fitted values of nondecreasing isotonic regression, i.e., the solution to min⁡∑iwi(yi−θi)2\min \sum_i w_i (y_i - \theta_i)^2 with θ1≤⋯≤θn\theta_1 \le \cdots \le \theta_n. It must run in linear time using a block stack; do not use IsotonicRegression.
import numpy as np

def pav(y, w):
  """Regresión isotónica no decreciente de y con pesos w."""
  y = np.asarray(y, dtype=float)
  w = np.asarray(w, dtype=float)
  # tu código: una pila de bloques (media, peso, tamaño); fusiona mientras el último baje
  return y.copy()
Shift+Enter to run

Summary

Key idea
Recalibration estimates an increasing function g(s)=P(Y=1∣s)g(s) = \Pr(Y = 1 \given s) using data unseen by the model. Example order stays fixed and probabilities become reliable; calibrator choice trades small-family bias against large-family variance.
  • Platt: univariate logistic regression on score, with targets (N++1)/(N++2)(N_+ + 1)/(N_+ + 2) and 1/(N−+2)1/(N_- + 2) ensuring a finite minimum. Convex and fitted by backtracking Newton. Contains identity on log-odds, not on probability.
  • Isotonic: monotonic least squares, solved in linear time by PAV, whose output satisfies KKT: blocks with data means and prefixes above them. Converges to any increasing form, but few data produce steps, high variance and exact zeros and ones.
  • Beta: logistic regression on (ln⁡s,−ln⁡(1−s))(\ln s, -\ln(1 - s)) with a,b≥0a, b \ge 0. Contains identity and log-odds Platt (a=ba = b), with different slope per tail.
  • Temperature: softmax⁡(z/T)\softmax(\vb{z}/T) with one TT, convex in 1/T1/T; changes no prediction. With few data it beats vector and matrix scaling, and one-versus-rest can change argmax.
  • Protocol: never on training data (the calibrator learns opposite distortion); separate set or cross-fitting, ensemble=True (average KK models) or False (one model and calibrator). After subsampling use logit⁡p=logit⁡ps+ln⁡β\operatorname{logit} p = \operatorname{logit} p_s + \ln\beta or recalibrate at real prevalence.
  • Choice and verification: few data and sigmoid shape, Platt or temperature; asymmetric, beta; thousands and free shape, isotonic; already calibrated with little data, nothing. Decide using test log-loss and Brier, and for guarantees consider Venn–Abers and conformal prediction.