Sub topic 8
Calibration: when predicted probabilities can be trusted
This chapter assumes you know binary classification metrics (accuracy, precision, recall, ROC AUC), basic Python, pandas and scikit-learn, and the difference between train, validation and test splits. It also assumes you know what a deployed model's prediction log is. The next chapter uses calibrated probabilities to estimate performance without labels. That estimate is only as good as the calibration behind it, so this chapter covers how to check it and fix it.
What calibration means
A classifier is calibrated if its predicted probabilities match observed frequencies. Take all cases where the model says 0.8. If the model is calibrated, about 80% of those cases are truly positive.
Calibration is a different property from ranking quality. ROC AUC only asks whether positives tend to score higher than negatives. A model can have excellent AUC and badly wrong probabilities. If you multiply every score by a constant and the ranking stays the same, AUC does not change, but calibration does.
This matters here because, with delayed labels, the score is often the only signal you have today. If you want to read the score as a probability of being correct, it must behave like one.
| Property | Question it answers | Changes under monotonic rescaling of scores? |
|---|---|---|
| Discrimination (AUC) | Do positives rank above negatives? | No |
| Calibration | Does a score of p mean frequency p? | Yes |
| Accuracy at a threshold | How often is the thresholded call right? | Only if the threshold is fixed |
Why miscalibration happens
Common causes:
- Training objective. Models trained with log loss (logistic regression) tend to be well calibrated on their training distribution. Tree ensembles, boosted models, SVMs and naive Bayes often are not. Random forests tend to pull scores toward the middle. Boosting often pushes probabilities toward the extremes.
- Class rebalancing. If you oversample the positive class or use class weights, the scores reflect the rebalanced prior, not the real one. The model then overestimates the positive rate in production.
- Overfitting. Deep or flexible models often become overconfident on training data.
- Distribution shift. A model calibrated at training time can become miscalibrated in production when the data or the base rate changes. This is the most important cause for monitoring, because calibration you verified at launch can quietly expire.
Measuring calibration
Reliability diagram
A reliability diagram bins predictions by score. For each bin, it plots the mean predicted probability against the observed fraction of positives. A calibrated model lies on the diagonal. Points below the diagonal mean the model is overconfident (it predicts higher than the truth). Points above mean it is underconfident.
import numpy as np
import pandas as pd
from sklearn.calibration import calibration_curve
rng = np.random.default_rng(0)
n = 20000
true_p = rng.beta(2, 5, size=n)
y = rng.binomial(1, true_p)
# An overconfident model: it pushes probabilities toward 0 and 1.
logit = np.log(true_p / (1 - true_p))
scores = 1 / (1 + np.exp(-2.0 * logit))
frac_pos, mean_pred = calibration_curve(y, scores, n_bins=10, strategy="quantile")
table = pd.DataFrame({"mean_predicted": mean_pred, "observed_rate": frac_pos})
print(table.round(3))Use strategy="quantile" so each bin holds the same number of cases. With uniform-width bins, the high-score bins can hold very few rows, and their observed rates are noisy.
Expected calibration error
Expected calibration error (ECE) summarizes the diagram in one number. It is the weighted average gap between predicted and observed rates across bins.
import numpy as np
def expected_calibration_error(y_true, p, n_bins=10):
"""Weighted mean |observed rate - mean prediction| over equal-count bins."""
y_true = np.asarray(y_true, dtype=float)
p = np.asarray(p, dtype=float)
order = np.argsort(p)
bins = np.array_split(order, n_bins)
ece = 0.0
for idx in bins:
if len(idx) == 0:
continue
gap = abs(y_true[idx].mean() - p[idx].mean())
ece += (len(idx) / len(p)) * gap
return eceECE has limits. It depends on the number of bins and the binning scheme, and with small samples it is biased upward because noise alone creates gaps. Use it to compare models on the same data, and do not treat a single value as an absolute verdict.
Brier score and log loss
The Brier score is the mean squared difference between the predicted probability and the 0/1 outcome. It mixes calibration and discrimination. Lower is better. Log loss is similar but punishes confident mistakes more heavily. Both are proper scoring rules, which means they are minimized only by reporting the true probability. Track them alongside ECE.
from sklearn.metrics import brier_score_loss, log_loss
print("Brier:", brier_score_loss(y, scores))
print("Log loss:", log_loss(y, scores))Fixing miscalibration: recalibration
Recalibration fits a small mapping from the model's raw score to a calibrated probability, using held-out labeled data. The base model stays unchanged.
Two standard methods:
- Platt scaling fits a logistic regression on the score (usually on the logit of the score). It has two parameters, so it works with little data. It assumes a sigmoid-shaped distortion.
- Isotonic regression fits a monotonic step function. It makes fewer assumptions but needs more data (thousands of rows is a common rule of thumb) and can overfit on small samples.
import numpy as np
from sklearn.isotonic import IsotonicRegression
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
# Reuse `scores` and `y` from the earlier example.
s_fit, s_test, y_fit, y_test = train_test_split(
scores, y, test_size=0.5, random_state=0, stratify=y
)
def to_logit(p):
p = np.clip(p, 1e-6, 1 - 1e-6)
return np.log(p / (1 - p)).reshape(-1, 1)
platt = LogisticRegression().fit(to_logit(s_fit), y_fit)
iso = IsotonicRegression(out_of_bounds="clip").fit(s_fit, y_fit)
p_platt = platt.predict_proba(to_logit(s_test))[:, 1]
p_iso = iso.predict(s_test)
for name, p in [("raw", s_test), ("platt", p_platt), ("isotonic", p_iso)]:
print(name, round(expected_calibration_error(y_test, p), 4))Fit the calibrator on data the base model did not train on, and evaluate it on a third slice it has not seen. If you fit and evaluate on the same rows, the ECE looks better than it will be in production.
Recalibration does not change AUC for a monotonic mapping, apart from ties introduced by isotonic's step shape. It only changes what the numbers mean.
Calibration in the delayed-label setting
Delayed labels create a specific problem. You calibrate on labeled data, and labeled data is old. Several traps follow.
- Calibrate on matured cohorts only. If you include recent rows whose labels have not fully arrived, positives are undercounted and the calibrator learns rates that are too low. Use the maturity window from the earlier chapters.
- The calibration data is from the past. If the base rate or the feature distribution has moved since then, the mapping is stale. Under pure covariate shift (the inputs change but P(y given x) does not), a model calibrated on the old data stays calibrated for each input, but the mix of inputs differs, so overall accuracy still changes. Under label shift or concept drift, calibration itself breaks.
- Censoring. If only some outcomes are observed, such as approved loans only, the calibration set is a biased sample. The calibrator is then accurate for the observed population and may be wrong for the rest.
- Subgroup calibration. A model can be calibrated overall and miscalibrated within segments, for example by region or product. Errors in different segments can cancel in the aggregate. Check the reliability diagram per segment that matters.
Tracking calibration over time
Compute ECE and the Brier score for each matured prediction cohort. A rising value is evidence of drift in P(y given x) or in the base rate, which no label-free signal can reveal directly. The next code block builds a monthly table.
import numpy as np
import pandas as pd
def monthly_calibration(df, now, maturity):
"""df columns: predicted_at, score, label (label is 0/1 once matured)."""
mature = df[df["predicted_at"] <= now - maturity].copy()
mature["cohort"] = mature["predicted_at"].dt.to_period("M")
rows = []
for cohort, g in mature.groupby("cohort"):
rows.append({
"cohort": str(cohort),
"n": len(g),
"mean_score": g["score"].mean(),
"base_rate": g["label"].mean(),
"ece": expected_calibration_error(g["label"], g["score"], n_bins=10),
})
return pd.DataFrame(rows)The gap between mean_score and base_rate is a quick check on its own. For a calibrated model, the average score equals the base rate. A persistent gap shows a global bias.
Decision criteria
| Situation | Suggested action |
|---|---|
| Few labeled rows (hundreds) | Platt scaling, or no recalibration and a wider uncertainty band |
| Many labeled rows (thousands or more) | Isotonic regression, compared against Platt on held-out data |
| Training used class weights or resampling | Correct for the prior shift, or recalibrate on data with the true class mix |
| ECE rises across matured cohorts | Recalibrate on the most recent matured data and investigate drift |
| Calibrated overall, poor in a segment | Recalibrate per segment if it has enough data, or exclude that segment from probability-based estimates |
Failure modes
- Calibrating on the wrong population. A calibrator fit on approved applicants is applied to all applicants.
- Reusing the training set. Tree models can score training rows near 0 or 1, so the calibrator learns nothing useful.
- Too few bins or too many. Ten quantile bins suit thousands of rows. With a few hundred, use fewer bins or report confidence intervals.
- Ignoring ties and clipping. Scores at exactly 0 or 1 make logits infinite. Clip before taking logs, as the code above does.
- Treating calibrated as accurate. A model that outputs the base rate for every case is perfectly calibrated and nearly useless. Calibration says the probabilities are honest, not that they are informative.
Exercise
A fraud model has an AUC of 0.93 on a matured cohort. The reliability diagram shows that cases scored 0.9 are fraudulent only 60% of the time. Is the model calibrated? Would applying isotonic regression change the AUC, and would it make the mean predicted probability a better estimate of the fraud rate?
Show answer
The model is not calibrated: it is overconfident, because a score of 0.9 corresponds to an observed rate of 0.6. A high AUC does not imply calibration, since AUC only measures ranking. Isotonic regression fitted on held-out matured data would not change the ranking meaningfully (apart from ties from its step shape), so AUC stays essentially the same. It would move scores toward observed frequencies, so the mean predicted probability would become a much better estimate of the fraud rate, provided the calibration data is a matured, unbiased sample of the current population.
Exercise
You have a calibration set built from the last 30 days of predictions, joined to labels that exist today. Your label maturity window is 60 days. What goes wrong, and how do you fix it?
Show answer
Most positives in the last 30 days have not been labeled yet, because their outcomes arrive up to 60 days later. Missing labels are treated as negatives, so the observed positive rate is too low, and the calibrator learns to lower the scores, which makes the model look underconfident. Restrict the calibration set to predictions made at least 60 days ago, and report how many rows were excluded.