Model Calibration in Python: Why a 0.8 Score Can Mean 50%
In a simulation with known true probabilities, three standard models were calibrated out of the box, but four common setups were not. Among cases a model scored near 0.8, only 48.4% to 54.6% were real events when the model used balanced class weights, naive Bayes or a small training set. Isotonic recalibration on 5,000 new labels brought them back to 74.6% to 81.1% and cut the cost of a balanced-weights model's decisions by a quarter.

A model that says 0.8 is making a promise: of all the cases it scores near 0.8, about 80% should turn out to be events. Model calibration in Python is the work of checking that promise and repairing it when it fails. I simulated a population where the true probability of every case is known, trained eight common setups on it, and counted how often a score near 0.8 came true. Logistic regression, gradient boosting and a random forest kept the promise, at 79.0% to 82.7%. Balanced class weights, naive Bayes and a 1,000-row training set did not: their 0.8 meant 48.4% to 54.6%.
Ranking was not the problem. All eight setups had AUCs from 0.822 to 0.868, and none of the broken ones would look wrong on a model card. Recalibrating on 5,000 fresh labels repaired the scores without retraining, and for a model trained with balanced class weights it lowered the cost of the decisions made from its scores by 25.5%. The code below runs in about ten seconds and prints every number in this piece.
What model calibration means
The scikit-learn user guide puts it plainly: among the cases a well calibrated binary classifier gives a probability close to 0.8, approximately 80% should belong to the positive class. Calibration is a separate property from ranking. A model can sort cases almost perfectly and still put the wrong numbers on them, because AUC only asks whether events score higher than non-events, not whether the scores are the right size.
The usual summary is the expected calibration error (ECE), defined in Guo and colleagues' 2017 paper on neural network calibration. Sort the n scored cases into M equal-width bins, compare each bin's event rate with its mean score, and weight the gaps by bin size:
With M = 10, an ECE of 0.193 means the scores miss the observed event rate by about 19 points on average. There is also a check that takes one line and no binning: the mean score should equal the base rate. A model whose average prediction is 0.382 on a population where 19.0% of cases are events is overstating risk by a factor of two, whatever its AUC.
The experiment: eight setups and a known truth
The simulated population has eight features, a nonlinear true risk with an interaction and a sine term, and a base rate of 18.9% in training. Each setup trains on 20,000 cases (or 1,000 for the small-data setup) and is scored on 50,000 new ones. Then each model is recalibrated with scikit-learn's CalibratedClassifierCV on 5,000 fresh labeled cases from the population it is scoring, without touching the trained model.
The last setup is drift: after training, the odds of an event halve for every case, which takes the base rate from 18.9% to 12.8%. The model and the distribution of its inputs stay the same, and only the outcome rates move.
It needs NumPy and scikit-learn (run here with Python 3.13, NumPy 2.5.3 and scikit-learn 1.9.1).
"""Model calibration in Python: what a 0.8 score really means, by setup.
Simulated data with a known true probability. Python 3, NumPy, scikit-learn 1.9.
"""
import numpy as np
from sklearn.calibration import CalibratedClassifierCV
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.frozen import FrozenEstimator
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.naive_bayes import GaussianNB
rng = np.random.default_rng(22)
INTERCEPT = -2.3 # sets the base rate near 15%
def make_data(n, shift=0.0):
"""Cases with a known true event probability; shift moves the base rate."""
X = rng.normal(size=(n, 8))
X[:, 1] = 0.7 * X[:, 0] + 0.3 * X[:, 1]
logit = (INTERCEPT + shift + 1.2 * X[:, 0] + 0.8 * X[:, 1] - 0.6 * X[:, 2]
+ 0.5 * X[:, 3] * X[:, 4] + 0.4 * np.sin(2 * X[:, 5]))
p = 1 / (1 + np.exp(-logit))
return X, rng.binomial(1, p), p
def ece(y, p, bins=10):
"""Expected calibration error over 10 equal-width bins."""
idx = np.minimum((p * bins).astype(int), bins - 1)
return sum(abs(p[idx == b].mean() - y[idx == b].mean()) * (idx == b).mean()
for b in range(bins) if (idx == b).any())
def hit_rate(y, p, lo=0.75, hi=0.85):
"""Share of real events among cases scored between lo and hi."""
m = (p >= lo) & (p < hi)
return (y[m].mean() if m.any() else float("nan")), int(m.sum())
C_FP, C_FN = 1.0, 4.0 # a false alarm costs 1, a missed event 4
T = C_FP / (C_FP + C_FN) # act when P(event) > 0.2
def cost(y, p):
act = p > T
return (C_FP * (act & (y == 0)).sum() + C_FN * (~act & (y == 1)).sum()) / len(y)
X_tr, y_tr, _ = make_data(20_000)
X_small, y_small, _ = make_data(1_000)
LATER = np.log(0.5) # deployment: the odds of an event halve
X_te, y_te, p_te = make_data(50_000)
X_new, y_new, p_new = make_data(50_000, shift=LATER)
gb = lambda **kw: HistGradientBoostingClassifier(random_state=0, **kw)
setups = [ # name, model, training data, test population
("logistic regression", LogisticRegression(max_iter=1000), "full", "same"),
("gradient boosting", gb(), "full", "same"),
("random forest", RandomForestClassifier(n_estimators=300, min_samples_leaf=5,
n_jobs=-1, random_state=0), "full", "same"),
("naive Bayes", GaussianNB(), "full", "same"),
("logistic regression, balanced weights",
LogisticRegression(max_iter=1000, class_weight="balanced"), "full", "same"),
("gradient boosting, balanced weights", gb(class_weight="balanced"), "full", "same"),
("gradient boosting, 1,000 training rows", gb(), "small", "same"),
("gradient boosting, after the odds of an event halve", gb(), "full", "later"),
]
print(f"base rate: training {y_tr.mean():.3f}, later {y_new.mean():.3f}")
print(f"cost per case using the true probabilities: now {cost(y_te, p_te):.4f}, "
f"later {cost(y_new, p_new):.4f}\n")
rows = []
for name, model, train, pop in setups:
Xf, yf = (X_tr, y_tr) if train == "full" else (X_small, y_small)
model.fit(Xf, yf)
Xt, yt = (X_te, y_te) if pop == "same" else (X_new, y_new)
p = model.predict_proba(Xt)[:, 1]
# recalibrate on 5,000 fresh labeled cases from the population being scored
Xc, yc, _ = make_data(5_000, shift=0.0 if pop == "same" else LATER)
q = (CalibratedClassifierCV(FrozenEstimator(model), method="isotonic")
.fit(Xc, yc).predict_proba(Xt)[:, 1])
hr, n = hit_rate(yt, p)
hq, nq = hit_rate(yt, q)
rows.append((name, hr, hq))
print(f"{name}\n AUC {roc_auc_score(yt, p):.3f} -> {roc_auc_score(yt, q):.3f} | "
f"ECE {ece(yt, p):.3f} -> {ece(yt, q):.3f} | "
f"Brier {brier_score_loss(yt, p):.4f} -> {brier_score_loss(yt, q):.4f}\n"
f" scored 0.75 to 0.85: {n} cases, {hr:.1%} events -> {nq} cases, {hq:.1%}\n"
f" mean score {p.mean():.3f} vs base rate {yt.mean():.3f} | "
f"cost per case {cost(yt, p):.4f} -> {cost(yt, q):.4f}")
What a 0.8 score meant in each setup
| Setup | AUC | ECE before, after | Events among cases scored 0.75 to 0.85, before | After recalibration | Mean score vs. base rate |
|---|---|---|---|---|---|
| Logistic regression | 0.851 | 0.003, 0.006 | 79.0% | 82.5% | 0.189 vs. 0.190 |
| Gradient boosting | 0.856 | 0.004, 0.011 | 80.3% | 74.3% | 0.188 vs. 0.190 |
| Random forest | 0.853 | 0.008, 0.011 | 82.7% | 81.3% | 0.192 vs. 0.190 |
| Naive Bayes | 0.844 | 0.070, 0.009 | 54.6% | 76.6% | 0.229 vs. 0.190 |
| Logistic regression, balanced weights | 0.851 | 0.193, 0.012 | 48.4% | 74.6% | 0.382 vs. 0.190 |
| Gradient boosting, balanced weights | 0.856 | 0.173, 0.009 | 51.9% | 77.7% | 0.363 vs. 0.190 |
| Gradient boosting, 1,000 training rows | 0.822 | 0.100, 0.011 | 50.9% | 81.1% | 0.160 vs. 0.190 |
| Gradient boosting, after the odds halve | 0.868 | 0.061, 0.008 | 68.0% | 78.8% | 0.188 vs. 0.128 |
The first three rows are the textbook case: plenty of data, a log-loss objective, no reweighting. The scikit-learn guide notes that logistic regression tends to return well calibrated probabilities on its own because its loss has a canonical link function, and here gradient boosting and the random forest did as well. Recalibrating them did not help: isotonic regression fit to 5,000 labels added a little noise to scores that were already right, and the ECE rose slightly in all three, which is a reason to measure calibration before fitting a calibrator.
Naive Bayes behaved the way Niculescu-Mizil and Caruana described in 2005: its independence assumption pushes probabilities toward 0 and 1, so its high scores run hot. Only 54.6% of its 0.8s were events.
Balanced class weights break calibration on purpose
The two worst setups are the most common in practice. When events are rare, a standard step is to weight the classes so the model sees them as balanced (class_weight="balanced" in scikit-learn, or downsampling the majority class). The ranking survives: AUC was 0.851 with or without weights for logistic regression. The scores do not. A model trained as if half of all cases were events learns a 50% base rate, and its mean score on the real population came out at 0.382 for logistic regression and 0.363 for gradient boosting, against a true 19.0%.
Among cases these models scored near 0.8, 48.4% and 51.9% were events. A 0.8 from a balanced model is roughly a coin flip, and the mean-score check catches it in one line before anyone looks at a reliability diagram.
The small training set fails in the other direction. Gradient boosting fit to 1,000 rows overfits, its scores spread too far toward the ends, and its 0.8 meant 50.9%. The drift case is quieter: after the odds of an event halved, the model's 0.8 meant 68.0%, and its mean score of 0.188 sat well above the new base rate of 12.8%. Nothing in the model changed, and AUC even rose, to 0.868.
Recalibration in Python with scikit-learn
CalibratedClassifierCV with FrozenEstimator fits a calibrator on top of a trained model without refitting it. The two methods are Platt's sigmoid, a two-parameter logistic curve on the model's scores, and isotonic regression, a free-form step function that only has to be increasing. The scikit-learn guide says isotonic will perform as well as or better than sigmoid when there are more than about 1,000 samples, and is more prone to overfitting on less. Both are monotone, so they barely move AUC (0.851 to 0.850 for balanced logistic regression).
With 5,000 labels from the population being scored, isotonic brought every broken setup back near the diagonal: ECE fell from 0.193 to 0.012 for balanced logistic regression, from 0.100 to 0.011 for the small-data model and from 0.061 to 0.008 after drift. The share of events among cases scored 0.75 to 0.85 moved to 74.6% to 81.1%. The labels have to come from the population the model scores now. A calibrator fit on last year's data inherits last year's base rate.
What miscalibration costs a decision
Scores matter when someone acts on them. Suppose a false alarm costs 1 unit and a missed event costs 4. Acting on a case costs (1 − p) × 1 in expectation and not acting costs p × 4, so the right rule is to act when
That rule assumes p is a real probability. Applied to the true probabilities, it costs 0.3389 units per case. Applied to the balanced logistic regression's scores, it costs 0.4934, because inflated scores push far too many cases over 0.2. After isotonic recalibration the same model, same features and same rule cost 0.3677, a cut of 25.5%. If a false alarm costs $50 and a miss $200, that gap is $62,850 per 10,000 cases. The balanced gradient boosting model dropped from 0.4526 to 0.3600, and the small-data model from 0.4233 to 0.3948.
Calibration matters most near the decision threshold. Naive Bayes is a useful counterexample: recalibration cut its ECE from 0.070 to 0.009, but its decision cost went from 0.3727 to 0.3769, because its scores were roughly right near 0.2 and wrong mainly near 0.8, where this rule makes no decisions. A model can be badly calibrated where nobody acts and fine where they do.
Where this shows up
The same arithmetic sits under every score that triggers an action: a sepsis alert, a readmission outreach list, a fraud review queue, an inspection camera's reject bin. Sepsis alert math works through what a base rate does to an alert's precision, the readmission program evaluation uses scores to choose whom to call, and the machine vision threshold sets a cutoff from costs. Each of them assumes the score is a probability. A Kansas City hospital, bank or manufacturer running any of these can check the assumption the same way: compare the mean score with the observed rate each month, and look at the event rate among the cases scored highest. More work like this is in the machine learning and analytics research hub at Vector 1 in Kansas City.
Limits of these numbers
Everything here comes from one simulated population with parameters I chose. Real data has label noise, delayed outcomes and segments with their own base rates, and a model can be calibrated overall while running hot in one segment and cold in another. The 0.75 to 0.85 band holds between 66 and 3,633 cases depending on the setup, so the smaller counts (66 cases after recalibration in the drift setup) carry more noise than the larger ones. Recalibration fixes the scale of the scores, not their ranking: a model that sorts cases badly stays bad. And a calibrator is only as current as its labels, so it needs the same monitoring as the model under it.
The paid edition
The paid edition on Substack goes further: how many labels sigmoid and isotonic need before they can be trusted (on this data sigmoid beat isotonic even at 10,000 labels), a label-free correction for balanced weights and base-rate drift and when it is safe to use, a model that is calibrated overall but off by 5.7 and 7.6 points in its bottom and top segments, and a reusable calibration_report() with a bootstrap interval on ECE. Subscribe free for new articles by email, or get a Team License for the whole data science team.
Sources
- scikit-learn developers, 1.16. Probability calibration, scikit-learn 1.9.1 user guide
- Alexandru Niculescu-Mizil and Rich Caruana, Predicting Good Probabilities with Supervised Learning, ICML 2005, pp. 625 to 632
- Chuan Guo, Geoff Pleiss, Yu Sun and Kilian Q. Weinberger, On Calibration of Modern Neural Networks, ICML 2017


