TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Calibration: Reliability Diagrams, Platt and Isotonic

Calibration: Reliability Diagrams, Platt and Isotonic

A weather forecaster who says "70 % chance of rain" is calibrated if it rains on about 70 % of the days with that forecast. A classifier's probabilities should mean the same: among all emails it scores 0.9, about 90 % should be spam. Many decisions use the probability itself, not just the ranking: expected cost (probability times loss), a risk shown to a doctor, a price that includes the chance of default, combining models. A model can rank perfectly (ROC-AUC 1) and still be badly calibrated. This lesson measures calibration, shows which models tend to be off, and fixes it with Platt scaling and isotonic regression.

Definition and measures

A model with score p^(x)\hat{p}(\mathbf{x}) is calibrated if

P(y=1∣p^(x)=p)=pfor every p.P\big(y = 1 \mid \hat{p}(\mathbf{x}) = p\big) = p \quad \text{for every } p .

To check it, group predictions into bins B1,…,BMB_1, \dots, B_M by their score, and compare in each bin the average score conf(Bm)\text{conf}(B_m) with the fraction of positives freq(Bm)\text{freq}(B_m). Plotting one against the other is a reliability diagram; a calibrated model lies on the diagonal. Two summaries:

ECE=∑m=1M∣Bm∣n∣freq(Bm)−conf(Bm)∣,Brier=1n∑i=1n(p^i−yi)2\text{ECE} = \sum_{m=1}^{M} \frac{\lvert B_m \rvert}{n} \big\lvert \text{freq}(B_m) - \text{conf}(B_m) \big\rvert, \qquad \text{Brier} = \frac{1}{n} \sum_{i=1}^{n} (\hat{p}_i - y_i)^2

The expected calibration error (ECE) depends on the binning; the Brier score is a proper scoring rule (lower is better) that mixes calibration with discrimination, as does log loss.

Measuring three models

Three classifiers on the same synthetic problem (20 features, 5 of them redundant copies of others), each with 3000 rows for training, calibration and testing:

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import brier_score_loss, roc_auc_score

X, y = make_classification(n_samples=9000, n_features=20, n_informative=5, n_redundant=5, random_state=0)
X_tr, y_tr, X_te, y_te = X[:3000], y[:3000], X[6000:], y[6000:]      # rows 3000-5999: calibration, later

def reliability(p, y, bins=10):
    idx = np.minimum((p * bins).astype(int), bins - 1)                 # equal-width bins on [0, 1]
    rows = [(b, int((idx == b).sum()), p[idx == b].mean(), y[idx == b].mean()) for b in range(bins) if (idx == b).any()]
    ece = sum(n / len(p) * abs(freq - conf) for _, n, conf, freq in rows)
    return rows, ece

models = {"naive Bayes": GaussianNB(), "logistic": LogisticRegression(max_iter=1000),
          "random forest": RandomForestClassifier(n_estimators=200, random_state=0)}
for name, m in models.items():
    p = m.fit(X_tr, y_tr).predict_proba(X_te)[:, 1]
    rows, ece = reliability(p, y_te)
    print(f"{name:14s} ECE {ece:.3f}  Brier {brier_score_loss(y_te, p):.3f}  ROC-AUC {roc_auc_score(y_te, p):.3f}")
    if name == "naive Bayes":
        nb_rows = rows
print("naive Bayes reliability table:  bin      n   mean score  fraction positive")
for b, n, conf, freq in nb_rows:
    print(f"                           {b / 10:.1f}-{(b + 1) / 10:.1f}  {n:5d}  {conf:10.3f}  {freq:17.3f}")
naive Bayes    ECE 0.074  Brier 0.126  ROC-AUC 0.910
logistic       ECE 0.063  Brier 0.096  ROC-AUC 0.930
random forest  ECE 0.062  Brier 0.047  ROC-AUC 0.984
naive Bayes reliability table:  bin      n   mean score  fraction positive
                           0.0-0.1    866       0.018              0.061
                           0.1-0.2    166       0.146              0.199
                           0.2-0.3    129       0.248              0.194
                           0.3-0.4     98       0.350              0.296
                           0.4-0.5    106       0.450              0.396
                           0.5-0.6    117       0.549              0.402
                           0.6-0.7    116       0.652              0.474
                           0.7-0.8    142       0.752              0.549
                           0.8-0.9    213       0.851              0.714
                           0.9-1.0   1047       0.975              0.915

All three models are off by 0.06 to 0.07 on average (ECE), but in different ways, and the ranking metrics tell another story: the random forest has by far the best ROC-AUC (0.984) and Brier score (0.047). The naive Bayes table shows its pattern: 1047 test rows get a score above 0.9 (mean 0.975) but only 91.5 % of them are positive, and scores between 0.6 and 0.9 are 13 to 20 points too high. At the bottom, rows scored 0.018 on average are positive 6.1 % of the time.

The reliability diagram

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.calibration import calibration_curve

X, y = make_classification(n_samples=9000, n_features=20, n_informative=5, n_redundant=5, random_state=0)
X_tr, y_tr, X_te, y_te = X[:3000], y[:3000], X[6000:], y[6000:]
models = {"naive Bayes": GaussianNB(), "logistic": LogisticRegression(max_iter=1000),
          "random forest": RandomForestClassifier(n_estimators=200, random_state=0)}

fig, ax = plt.subplots(figsize=(5, 5))
ax.plot([0, 1], [0, 1], "k--", label="perfectly calibrated")
for name, m in models.items():
    p = m.fit(X_tr, y_tr).predict_proba(X_te)[:, 1]
    freq, conf = calibration_curve(y_te, p, n_bins=10)        # the same bins as above
    ax.plot(conf, freq, "o-", label=name)
ax.set_xlabel("mean predicted probability")
ax.set_ylabel("fraction of positives")
ax.legend()
print("below the diagonal: fewer positives than predicted; above: more")
below the diagonal: fewer positives than predicted; above: more

The two kinds of error have opposite shapes. Naive Bayes is flatter than the diagonal: at the low end its points lie above it, and from 0.5 upwards well below it (scores of 0.75 come true 55 % of the time). Its probabilities are pushed towards 0 and 1, the shape of an overconfident model; it multiplies the evidence of the redundant features as if they were independent. Logistic regression and the random forest are steeper than the diagonal, below it on the left and above it on the right: their scores are too close to 0.5, so they are underconfident. For the forest this is typical (averaging trees rarely gives exactly 0 or 1); for logistic regression, usually well calibrated, it is a sign that its linear model does not match this data. Both still miss by about 0.06 on average (their ECE).

Fixing it: post-hoc calibration

Calibration methods learn a monotone map gg from the model's score to a probability, p~=g(p^)\tilde{p} = g(\hat{p}), on data that was not used for training (the calibration split), and are judged on a third split.

  • Platt scaling fits a logistic curve to the score: p~=σ(a s+b)\tilde{p} = \sigma(a\, s + b), where ss is the model's score (here the log-odds of p^\hat{p}). Two parameters, so it needs little data, but it can only fix S-shaped distortions.
  • Isotonic regression fits the best non-decreasing step function to the labels by least squares (the pool-adjacent-violators algorithm). It can fix any monotone distortion but needs more data (roughly a thousand calibration rows or more) and can overfit with few.

Both are monotone, so they leave the ranking, and therefore ROC-AUC, (almost) unchanged: isotonic steps can create ties.

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.isotonic import IsotonicRegression
from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score

X, y = make_classification(n_samples=9000, n_features=20, n_informative=5, n_redundant=5, random_state=0)
X_tr, y_tr = X[:3000], y[:3000]
X_cal, y_cal = X[3000:6000], y[3000:6000]
X_te, y_te = X[6000:], y[6000:]

def ece(p, y, bins=10):
    idx = np.minimum((p * bins).astype(int), bins - 1)
    return sum((idx == b).mean() * abs(y[idx == b].mean() - p[idx == b].mean()) for b in range(bins) if (idx == b).any())

nb = GaussianNB().fit(X_tr, y_tr)
logit = lambda p: np.log(np.clip(p, 1e-12, 1 - 1e-12) / np.clip(1 - p, 1e-12, 1))
s_cal, s_te = logit(nb.predict_proba(X_cal)[:, 1]), logit(nb.predict_proba(X_te)[:, 1])

platt = LogisticRegression(C=1e6).fit(s_cal.reshape(-1, 1), y_cal)          # sigma(a*s + b)
iso = IsotonicRegression(out_of_bounds="clip", y_min=0, y_max=1).fit(s_cal, y_cal)
print(f"Platt: a = {platt.coef_[0, 0]:.3f}, b = {platt.intercept_[0]:.3f}")
print(f"isotonic: a step function with {len(iso.X_thresholds_)} breakpoints")

raw = 1 / (1 + np.exp(-s_te))
for name, p in [("raw naive Bayes", raw), ("+ Platt", platt.predict_proba(s_te.reshape(-1, 1))[:, 1]),
                ("+ isotonic", np.clip(iso.predict(s_te), 1e-6, 1 - 1e-6))]:
    print(f"{name:16s} ECE {ece(p, y_te):.3f}  Brier {brier_score_loss(y_te, p):.3f}"
          f"  log loss {log_loss(y_te, p):.3f}  ROC-AUC {roc_auc_score(y_te, p):.3f}")
Platt: a = 0.569, b = -0.200
isotonic: a step function with 62 breakpoints
raw naive Bayes  ECE 0.074  Brier 0.126  log loss 0.442  ROC-AUC 0.910
+ Platt          ECE 0.036  Brier 0.120  log loss 0.388  ROC-AUC 0.910
+ isotonic       ECE 0.020  Brier 0.119  log loss 0.383  ROC-AUC 0.909

Platt scaling learned a=0.569a = 0.569: the naive Bayes log-odds are almost twice too large, so it shrinks them, which is exactly the overconfidence seen above. Both methods cut the ECE (0.074 to 0.036 and 0.020) and improve log loss and Brier score, and ROC-AUC stays at 0.910 (isotonic's ties cost 0.001). The Brier score improves less than ECE because most of it comes from the model's limited ability to separate the classes, which no calibration can fix.

With scikit-learn: CalibratedClassifierCV

CalibratedClassifierCV does the split for you: with cv=5 it trains five copies of the model on four folds each, fits the calibrator on the fifth, and averages the five calibrated models. Here on the combined 6000 training and calibration rows, judged on the same test rows:

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import brier_score_loss, log_loss

X, y = make_classification(n_samples=9000, n_features=20, n_informative=5, n_redundant=5, random_state=0)
X_fit, y_fit, X_te, y_te = X[:6000], y[:6000], X[6000:], y[6000:]

def ece(p, y, bins=10):
    idx = np.minimum((p * bins).astype(int), bins - 1)
    return sum((idx == b).mean() * abs(y[idx == b].mean() - p[idx == b].mean()) for b in range(bins) if (idx == b).any())

for base_name, base in [("naive Bayes", GaussianNB()),
                        ("random forest", RandomForestClassifier(n_estimators=100, random_state=0))]:
    for method in [None, "sigmoid", "isotonic"]:
        m = base if method is None else CalibratedClassifierCV(base, method=method, cv=5)
        p = np.clip(m.fit(X_fit, y_fit).predict_proba(X_te)[:, 1], 1e-6, 1 - 1e-6)
        print(f"{base_name:14s} {str(method):9s} ECE {ece(p, y_te):.3f}  Brier {brier_score_loss(y_te, p):.3f}  log loss {log_loss(y_te, p):.3f}")
naive Bayes    None      ECE 0.079  Brier 0.129  log loss 0.451
naive Bayes    sigmoid   ECE 0.043  Brier 0.125  log loss 0.402
naive Bayes    isotonic  ECE 0.018  Brier 0.121  log loss 0.388
random forest  None      ECE 0.052  Brier 0.039  log loss 0.160
random forest  sigmoid   ECE 0.013  Brier 0.036  log loss 0.129
random forest  isotonic  ECE 0.009  Brier 0.036  log loss 0.132

For both models, both methods reduce ECE, Brier score and log loss on the test rows. Naive Bayes gains most from isotonic (ECE 0.079 to 0.018), whose free shape fits its distortion better than a single logistic curve; for the underconfident forest, sigmoid and isotonic are about equal (ECE 0.013 and 0.009, log loss 0.129 and 0.132). With 6000 rows there is enough data for isotonic; with a few hundred, prefer "sigmoid". Calibration fixes the probabilities, not the ranking: the forest remains the far better model (log loss 0.129 against 0.388).

Pitfalls

  • Calibrating on the training data. The model is overconfident on rows it has seen; the calibrator would learn the wrong map. Use a held-out split or CalibratedClassifierCV.
  • Judging calibration with few rows. With 200 test rows and 10 bins, each bin has about 20 rows and the ECE is mostly noise. Use fewer bins, or equal-count bins, and report the Brier score too.
  • Calibration does not travel. A model calibrated on last year's data is miscalibrated when the share of positives changes (Distribution Shift); resampling or class weights also break it (Class Imbalance).
  • Multiclass: calibrate one-vs-rest and renormalise (what CalibratedClassifierCV does), or use temperature scaling (divide all logits by one fitted TT), the standard fix for neural networks.

Practice

  1. Among the predictions a model scores between 0.8 and 0.9, 62 % are positive. Over- or underconfident?
Answer

Overconfident: it claims about 85 % and is right 62 % of the time. The reliability point lies below the diagonal.

  1. Why can Platt scaling not hurt ROC-AUC?
Answer

With a>0a > 0, σ(as+b)\sigma(a s + b) is strictly increasing in ss, so the order of the examples, and therefore every ROC point, is unchanged. (A negative aa would reverse the ranking; that would mean the model is worse than random.)

  1. You have 300 calibration rows. Platt or isotonic?
Answer

Platt. With two parameters it is stable on small data; isotonic regression fits a free step function and tends to overfit with a few hundred rows.

Test yourself

What does it mean for a classifier to be calibrated?

  1. Its accuracy is above 0.5
  2. Among examples it scores pp, about a fraction pp are positive
  3. Its ROC-AUC is 1
  4. Its scores sum to 1

Naive Bayes on correlated features tends to be…

  1. perfectly calibrated
  2. overconfident: probabilities pushed towards 0 and 1
  3. underconfident: probabilities pushed towards 0.5
  4. unable to output probabilities

On which data should a calibrator be fitted?

  1. The training data of the model
  2. A held-out calibration split (or cross-validation folds)
  3. The test set
  4. Any data, it does not matter

Which statement about isotonic regression as a calibrator is right?

  1. It has two parameters
  2. It fits a non-decreasing step function and needs more data than Platt scaling
  3. It changes the ranking of examples
  4. It only works for neural networks