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.
What runs in CodeSplash
- Calibration of predicted risks Verified in Python and R
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
Do the words match the world?
ReadCalibrationCalibrationWhether 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.
View data
| mean predicted risk | observed readmission rate | patients | lower (Wilson) | upper (Wilson) |
|---|---|---|---|---|
| 0.0400 | 0.0722 | 97 | 0.0354 | 0.1415 |
| 0.1350 | 0.2439 | 82 | 0.1638 | 0.3469 |
| 0.2300 | 0.2442 | 86 | 0.1656 | 0.3446 |
| 0.3250 | 0.2990 | 97 | 0.2169 | 0.3963 |
| 0.4200 | 0.3494 | 83 | 0.2556 | 0.4566 |
| 0.5150 | 0.5341 | 88 | 0.4306 | 0.6347 |
| 0.6100 | 0.5541 | 74 | 0.4409 | 0.6618 |
| 0.7050 | 0.5963 | 109 | 0.5025 | 0.6836 |
| 0.8000 | 0.7802 | 91 | 0.6848 | 0.8530 |
| 0.8950 | 0.7841 | 88 | 0.6872 | 0.8572 |
Can AUC see it?
PredictPredict 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?
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.
Bend it yourself
ExploreDrag 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?
Above 1 the model is too extreme; below 1 it hedges. At 1 it is perfectly calibrated.
| Brier | ECE | Calibration slope | AUC |
|---|---|---|---|
| 0.175 | 0.087 | 0.50 | 0.835 |
Commit your prediction above to see the result
Make your prediction to see the result.
Who needs it?
ReadIf 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.
Four fixes
ReadEach learns a map from out-of-fold probabilities to observed outcomes. None retrains the model.
| Method | Parameters | Good for |
|---|---|---|
| Platt scalingPlatt scalingRecalibrates scores with a logistic curve fitted on held-out predictions; simple and stable with little data. | 2 | Steady with few rows; S-shaped errors |
| Beta calibration | 3 | Lopsided 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. | Many | Any 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. | 1 | Multiclass too; keeps the ranking |
Each fold is recalibrated by a map learned on the other folds, so the new run's scores are honest.
How much will it change?
PredictPredict first
You apply Platt scaling to an overconfident boosted model. What do you expect on the leaderboard?
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.
Check your understanding
CheckpointCheck 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.
Recalibrate a run
In the appOpen 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.
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))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)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