Skip to content

Calibration and recalibration

When a model says 70%, does the event happen 70% of the time? Read a reliability curve, see why AUC can't tell you, and fix probabilities without retraining.

Applied ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Read a reliability curve and the calibration slope
  • Explain why calibration and discrimination are separate properties
  • Choose a recalibration method and keep its score honest

Read first

01

Do the words match the world?

Read

CalibrationCalibrationWhether predicted probabilities match observed frequencies — of cases given 30%, about 30% should be positive. asks: among rows given about 70%, is the event's share about 70%?

A reliability curve groups rows by predicted probability, and plots each group's mean prediction against its observed share. Perfect calibration lies on the diagonal.

  • Below the diagonal at the high end: the model is too confident there.
  • S-shape through the diagonal: probabilities too extreme overall, with a calibration slope below 1.
Calibration plotDo predicted probabilities match observed frequencies?
View data
mean predicted riskobserved readmission ratepatientslower (Wilson)upper (Wilson)
0.04000.0722970.03540.1415
0.13500.2439820.16380.3469
0.23000.2442860.16560.3446
0.32500.2990970.21690.3963
0.42000.3494830.25560.4566
0.51500.5341880.43060.6347
0.61000.5541740.44090.6618
0.70500.59631090.50250.6836
0.80000.7802910.68480.8530
0.89500.7841880.68720.8572
02

Can AUC see it?

Predict

Predict first

Two sets of predictions on Pima. The first is well calibrated, with a slope of 1.00. The second is stretched to be overconfident, with a slope of 0.625. What's the second one's AUC, compared with the first?

Much higherAbout the same, or identicalMuch lower
Reveal

Identical: 0.855 and 0.855. Stretching keeps the order, and AUC only sees order. The Brier score does see it: 0.144 against 0.150.

03

Bend it yourself

Explore

Drag Overconfidence above 1 and below 1, and watch the reliability curve bend. Use the check to bring Calibration slope to within 5% of 1. Then raise Bins with a small n: more bins mean noisier points.

HExplorable · Calibration and reliability

When a model says 80%, does the event happen 80% of the time?

If you make the model more overconfident, what happens to its AUC?

How sure?
2.00

Above 1 the model is too extreme; below 1 it hedges. At 1 it is perfectly calibrated.

2000
10
BrierECECalibration slopeAUC
0.1750.0870.500.835

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

04

Who needs it?

Read

If you only rank rows, or act on the top 100, calibration doesn't matter much. It matters when the number itself gets used:

  • Comparing probability with a cost threshold.
  • Expected values: predicted risk times amount at stake.
  • Showing a probability to a person who'll believe it.

Which learners go wrong? Boosted trees, random forests, SVMs and naive Bayes often need it. Anything trained with class weights or resampling does too.

05

Four fixes

Read

Each learns a map from out-of-fold probabilities to observed outcomes. None retrains the model.

MethodParametersGood for
Platt scalingPlatt scalingRecalibrates scores with a logistic curve fitted on held-out predictions; simple and stable with little data.2Steady with few rows; S-shaped errors
Beta calibration3Lopsided errors a single sigmoid can't fix
Isotonic regressionIsotonic calibrationRecalibrates with a stepwise increasing curve; flexible, but it needs plenty of held-out data to avoid overfitting.ManyAny monotone shape; needs several hundred rows
Temperature scalingTemperature scalingDivides a model's logits by one learned number to soften or sharpen its probabilities without changing its ranking.1Multiclass too; keeps the ranking

Each fold is recalibrated by a map learned on the other folds, so the new run's scores are honest.

06

How much will it change?

Predict

Predict first

You apply Platt scaling to an overconfident boosted model. What do you expect on the leaderboard?

AUC and Brier both improve a lotBrier improves, and AUC barely movesAUC improves, and Brier barely moves
Reveal

Brier improves, and AUC barely moves. Temperature and Platt maps are monotone, so the ranking doesn't change. Isotonic can create ties, which can nudge AUC a little. Judge recalibration on a proper score, on held-out rows.

07

Check your understanding

Checkpoint

Check yourself

A model has a calibration slope of 0.6 on new data. What does that mean?

Show the answer

Answer: a

A slope below 1 is the classic overfit signature: stretch the predictions less and they'd match. A slope above 1 means they're too timid.

Check yourself

You have 150 rows of out-of-fold predictions. Which calibrator is the safest?

Show the answer

Answer: a

Isotonic fits any monotone step shape, and with few rows it overfits. Two parameters are much steadier.

Check yourself

Why learn the calibrator on out-of-fold predictions, not on training predictions?

Show the answer

Answer: b

The map must reflect how the model behaves on rows it hasn't seen.

08

Recalibrate a run

In the app

Open a classification run and go to Evaluation for the reliability chart and Expected calibration error. Then, on Diagnostics, use Recalibrate probabilities, pick a method and press Recalibrate. The new run joins the leaderboard with a calibrated badge, so you can compare the two on Brier score.

Python
import pandas as pd
from sklearn.calibration import CalibratedClassifierCV
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict

df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
cv = StratifiedKFold(5, shuffle=True, random_state=1)
base = GradientBoostingClassifier(n_estimators=200, max_depth=3, random_state=1)
for name, m in [("raw", base), ("platt", CalibratedClassifierCV(base, method="sigmoid", cv=3))]:
    p = cross_val_predict(m, X, y, cv=cv, method="predict_proba")[:, 1]
    print(name, "auc", round(roc_auc_score(y, p), 3), "brier", round(brier_score_loss(y, p), 4))
R
library(xgboost)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
X <- as.matrix(df[, setdiff(names(df), "type")]); y <- as.numeric(df$type == "Yes")
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(X)))
p <- numeric(nrow(X))
for (k in 1:5) {
  fit <- xgb.train(list(max_depth = 3, learning_rate = 0.3, objective = "binary:logistic"),
                   xgb.DMatrix(X[fold != k, ], label = y[fold != k]), nrounds = 100, verbose = 0)
  p[fold == k] <- predict(fit, X[fold == k, ])
}
logit <- qlogis(pmin(pmax(p, 1e-6), 1 - 1e-6))
cal <- numeric(length(p))
for (k in 1:5) {  # each fold's map is learned on the other folds
  m <- glm(y ~ logit, binomial, subset = fold != k)
  cal[fold == k] <- predict(m, data.frame(logit = logit[fold == k]), type = "response")
}
coef(glm(y ~ logit, binomial))["logit"]
round(c(brier_raw = mean((p - y)^2), brier_platt = mean((cal - y)^2),
        auc_raw = as.numeric(pROC::auc(y, p, quiet = TRUE)), auc_platt = as.numeric(pROC::auc(y, cal, quiet = TRUE))), 4)
09

Recap

Recap
  • Calibration asks whether the number means what it says. AUC can't see that.
  • A slope below 1 means too extreme. Boosted, class-weighted and resampled models often need fixing.
  • Recalibrate on out-of-fold predictions with cross-fitting, and judge the result on a proper score.

Concepts in this lesson