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 mapping model score to reliable probabilities . 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 and log-loss . After Platt recalibration AUC remains exactly (the increasing calibrator preserves order) and log-loss falls to . With isotonic it falls to . 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 , changing no predictions.
Before formulas, see how the first three behave on a model with known distortion.
Three observations the rest explains. With asymmetric distortion Platt converges to a curve that is not truth: however large grows, error plateaus. Isotonic does converge, but with small 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 be an already trained binary classifier’s score: probability, log-odds or SVM margin. We want to return the calibration function
because composition is calibrated by construction: if the model says , the positive class occurs 30% of the time. Recalibration estimates using sample of scores and labels. It is regression of on one feature 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 rather than something else? Among functions of it scores best under any proper rule.
Proof
Condition on . Given , is Bernoulli with parameter , and is a fixed number . Propriety makes expected score minimal at , uniquely under strict propriety. Integrating over yields the inequality, and equality requires 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 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 into a probability by fitting a two-parameter sigmoid.
Platt writes sigmoid with : 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 and ,
and posterior probability is . 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 , Platt with and is identity; corrects an overconfident model (pulls log-odds toward 0), an underconfident one, and shifts prevalence. For a binary probability classifier, applying Platt to is natural. Applying it directly to , as scikit-learn does without decision_function, has a one-line defect: since , output is trapped between and , excluding 0 and 1. No 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 grows linearly as (slopes and on the two sides), so is coercive unless all are equal and a minimum exists. Platt uses a Bayesian argument: the result has Laplace’s succession-rule form , applied to “all positives were positive” and “none of 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 with respect to is
so at optimum : mean calibrator probability reproduces prevalence, mildly shrunk toward by smoothing.
How to fit
The Hessian is
positive semidefinite because each summand is, and positive definite if and only if not all are equal: since , quadratic form vanishes only if for all , which with two distinct forces . 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 ). With two parameters each Newton step solves a 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 with multipliers , , and let . The Lagrangian of gives stationarity
Group indices into blocks: consecutive intervals where is constant, separated where strictly increases. The other three conditions become:
- Complementary slackness. Between blocks the constraint is inactive, so : cumulative residuals vanish at each block end. Subtracting consecutive ends, each block satisfies , i.e., is its weighted mean.
- Dual feasibility. Within a block, means the sum of from block start to is nonnegative: every block prefix has weighted mean .
- Primal feasibility. Block means are nondecreasing.
Conversely, a consecutive-block partition with those properties defines and satisfying all four KKT conditions, making optimal. Since the objective is strictly convex (all ), 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:
- Read the next observation and push it as a single-element block.
- While the last block’s mean is below its predecessor’s, merge them with weighted mean and total weight.
- 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 merges and total cost after sorting, overall. You prove output optimality in an exercise: each merge preserves the prefix property.
The lower diagram is the classical isotonic characterization: the solution is the left derivative of the greatest convex minorant of points , 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 : 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 to 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 that one contributes to mean log-loss, most of the gap between isotonic () and Platt (); 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 , Bayes’ rule gives
which is the family with and . The beta distribution lives on and can be highly asymmetric, exactly like Naive Bayes or AdaBoost probabilities; Platt’s Gaussians cannot.
What it contains. With and the map is identity, so a calibrated model can remain unchanged. With , since , the map is : Platt on log-odds. Beta is Platt plus one degree of freedom.
What it adds. In log-odds with , when and when . Thus in the left tail and 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 and ) is invisible to Platt, which has one slope.
Why . The derivative of with respect to is , nonnegative for every exactly when . If unconstrained fitting gives a negative coefficient, the map is nonmonotonic; a simple solution used here drops that feature and refits with the other.
Multiclass: temperature, vector and matrix scaling
With classes the model returns logits and probabilities , 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 distributions flatten and with sharpen; yields uniform and concentrates all mass at argmax. Three useful properties:
- No prediction changes. Dividing all logits by the same preserves ordering, so argmax and accuracy are identical for every (proved in an exercise). This is the only correction here guaranteeing classification does not worsen.
- Entropy grows with . With and entropy is and differentiation gives . Raising lowers : more entropy, less confidence, always in the same direction.
- Convex in . NLL as a function of is , with second derivative mean logit variance under the model . It need not be convex in but is in , and Newton converges smoothly. The first-order condition is
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.
With 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 : mean confidence falls to 74.9%, test NLL to and ECE to . 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 with parameters; matrix scaling uses with . 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 ; Platt is “temperature plus bias.”
One versus rest. CalibratedClassifierCV with method="sigmoid" or "isotonic" separately calibrates each column as binary “class versus rest,” then renormalizes 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 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.
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 , 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 , which saturates at 0 or 1 on many rows.
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 : the model exaggerates log-odds by about 44% (). Correction lowers log-loss to and ECE to . Beta finds ( and ): 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 (), also asymmetric: beta gives and , 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 , Brier , ECE . Beta lies between on log-loss ( versus Platt ).
- 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.
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 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.
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 , and ), temperature best with one parameter: network distortion is mainly excess scale. With 100, vector rises to and matrix to while temperature stays fixed. With 30, matrix NLL shoots to : with 20 parameters and 30 examples, maximum likelihood lowers calibration NLL to by amplifying scale, and the last column measures it: median maximum absolute test-row logit becomes versus for temperature and 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.
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 , multiplying log-odds by more than three. On test the model was overconfident ( with clean data), so the contaminated calibrator pushes precisely the wrong way: log-loss rises from uncalibrated to . 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 and calibrator fitted on the excluded fold. At prediction average pair probabilities.ensemble=False: obtain out-of-fold scores withcross_val_predict, fit one calibrator on all and apply it to a model retrained on all data. This isSVC(probability=True)’s procedure. There is a slight mismatch: calibrator learned distortion of models trained on 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 and all positives. The model learns posterior probability in a world where negatives are times rarer:
Solving for the original-population probability gives
Correction is a constant log-odds shift, so Platt on log-odds contains it (, ). Duplicating each positive times is the same with , 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 . 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").
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 ( and ) because it calibrates decision_function, the log-odds. For Naive Bayes it calibrates , and your Platt on matches within (optimizer tolerance). Here Platt on is slightly better than log-odds ( versus ): with asymmetric distortion sigmoids of and are distinct approximations neither dominating. The argument against is identity: when calibrated, Platt on 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 () 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.
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 ( versus ). Both cross-fitting variants also improve on fixed separation, which reached with Platt: they use all data for model and calibrator. ensemble=True wins clearly ( versus ) and alone raises AUC ( to ): 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 production models; the second one.
Prior correction with positive class 5.5% and training on 10% of negatives:
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 % versus true %, log-loss . The prior formula uses no extra data and restores mean to % and log-loss to . Platt on true-prevalence calibration data does more: intercept is near as theory predicts, but also shrinks slope to because a GBDT trained on only about 3000 examples is overconfident. With the lowest log-loss of three (), 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:
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 via bounded search) gives the same as your Newton. One-versus-rest Platt trails badly (NLL ): 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 to . 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 and true probability depends on distortion: when calibrated; when overconfident; (beta with and ) for asymmetric; and for the plateau is for and rises linearly to and at extremes. The interactive adds underconfidence . Metric is excess Brier , added above minimum achievable Brier, computed by quadrature over distribution .
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 the harm is large: Platt adds (units ), beta and isotonic . If previous diagnosis finds no clear issue and data are few, do not recalibrate.
- Overconfident (a sigmoid). Platt is best at every : its family contains truth and estimates only two parameters. Isotonic needs to reach ; Platt already reaches with 1000.
- Asymmetric. Platt plateaus near ( with 1000, with 4000): bias does not fall with more data. Beta contains truth and drops to , already beating Platt with 200 examples ( versus ); isotonic reaches with 4000 and also beats it. With , all three worsen the uncalibrated model (): fitting variance outweighs corrected distortion.
- Plateau. Neither parametric family contains this shape: Platt and beta plateau near , and isotonic alone converges with examples or more.
With 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:
- Few calibration data (hundreds): Platt on log-odds or, for multiclass, temperature. For probabilities of very biased models (Naive Bayes, AdaBoost), beta.
- Thousands of examples and unknown shape: isotonic, or beta if reliability looks smooth and you want to avoid steps and exact zeros.
- Multiclass with many classes: temperature before vector scaling; matrix scaling only with much data per parameter.
- 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 , fit isotonic twice, adding the example to calibration with labels 0 and 1, obtaining probabilities . Their theorem 1 guarantees, assuming only iid data, that a selector exists for which selected is perfectly calibrated, (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 . Width measures dependence on sample. If the model trained on other data, the score is a fixed function and the procedure applies directly to calibration.
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 ( and in the tails). With 100, log-odds example becomes : 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
More than one answer may be correct.
CalibratedClassifierCV(base, cv=5, ensemble=...) with default method='sigmoid', which statements are true?More than one answer may be correct.
Step 1 of 4. Why does the invariant hold immediately after pushing a new observation?
Step 1 of 3. How do you compare classes and ?
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 with . 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()Summary
- Platt: univariate logistic regression on score, with targets and 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 with . Contains identity and log-odds Platt (), with different slope per tail.
- Temperature: with one , convex in ; 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 models) orFalse(one model and calibrator). After subsampling use 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.