A weather forecaster says "70% chance of rain" on 100 different days. If it rains on about 70 of them, her forecasts are calibrated: her 70% means 70%. If it rains on only 40 of them, she ranks days fine (rainier days still get higher numbers) but her numbers can't be trusted as chances.
Classifiers have the same problem. predict_proba returns numbers between 0 and 1, but many models' numbers are not real probabilities: a model can say 99% and be right only 70% of the time. Probability calibration checks whether a classifier's probabilities mean what they say, and fixes them when they don't. It matters whenever someone acts on the number itself: a fraud team setting a cost-based threshold, a doctor reading a risk score, or a business multiplying probabilities by money, as in the customer churn project.
What you need first: Naive Bayes explained, confusion matrix, ROC and AUC, log loss from loss functions explained, and cross-validation.
Key terms
- Calibrated: among all predictions of about p, a share of about p turns out positive.
- Reliability diagram (calibration curve): a plot of predicted probability against the share of positives actually seen; a calibrated model follows the diagonal.
- Brier score: the mean squared difference between predicted probabilities and actual outcomes (0 or 1); lower is better.
- Platt scaling (sigmoid calibration): fitting an S-shaped curve that maps a model's scores to calibrated probabilities.
- Isotonic calibration: fitting a step-shaped curve that only ever goes up, which can correct any monotonic distortion.
The data
The Spambase emails from random forest explained: 4,601 emails, 57 word and character frequencies, 39% spam.
Download the data: spambase.csv (1.1 MB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("spambase.csv").
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
X, y = fetch_openml(data_id=44, as_frame=False, return_X_y=True)
y = y.astype(int)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
print(X_train.shape, f"spam share {y.mean():.3f}")
(3220, 57) spam share 0.394
fetch_openml(data_id=44) downloads Spambase from OpenML the first time and keeps a copy; as_frame=False returns plain NumPy arrays. The labels arrive as text, so astype(int) turns them into 0 and 1.
Step 1: is 99% really 99%?
Gaussian Naive Bayes assumes the 57 features are independent. They aren't: "free", "money" and "!" tend to appear together. So it counts the same evidence several times and becomes far too sure of itself. Predict first: of the test emails Naive Bayes calls more than 99% likely to be spam, what share really are spam?
from sklearn.naive_bayes import GaussianNB
nb = GaussianNB().fit(X_train, y_train)
p_nb = nb.predict_proba(X_test)[:, 1]
very_sure = p_nb > 0.99
print(f"{np.mean((p_nb < 0.01) | (p_nb > 0.99)):.0%} of test emails get a probability below 1% or above 99%")
print(f"emails called over 99% spam: {very_sure.sum()}, of which really spam: {y_test[very_sure].mean():.1%}")
98% of test emails get a probability below 1% or above 99%
emails called over 99% spam: 715, of which really spam: 71.5%
[:, 1] takes the probability of the second class, spam. | means "or" for arrays of True and False.
Naive Bayes almost never hedges: 98% of test emails get a probability below 1% or above 99%. And of the 715 emails it calls more than 99% likely to be spam, only 71.5% really are. Nearly 3 in 10 of its "certain" spam calls are wrong. Anyone who deleted every email above 99% would delete about 200 real emails from this test set alone.
Step 2: reliability diagrams
A reliability diagram checks the whole range at once. Sort the test emails by predicted probability, cut them into 10 groups of equal size, and for each group plot the average prediction against the share that really is spam:
from sklearn.calibration import calibration_curve
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
models = {
"Naive Bayes": GaussianNB(),
"Logistic regression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)),
"Random forest": RandomForestClassifier(n_estimators=300, random_state=0, n_jobs=-1),
"Gradient boosting": HistGradientBoostingClassifier(random_state=0),
}
probabilities = {name: model.fit(X_train, y_train).predict_proba(X_test)[:, 1] for name, model in models.items()}
fig, ax = plt.subplots(figsize=(6.5, 6))
ax.plot([0, 1], [0, 1], "k--", label="Perfectly calibrated")
for name, p in probabilities.items():
share_spam, mean_pred = calibration_curve(y_test, p, n_bins=10, strategy="quantile")
ax.plot(mean_pred, share_spam, marker="o", label=name)
ax.set_xlabel("Mean predicted probability of spam")
ax.set_ylabel("Share actually spam")
ax.legend()
plt.show()
strategy="quantile" makes groups with equal numbers of emails, so every point rests on about 138 emails. calibration_curve returns the share of positives first and the mean prediction second.
Logistic regression, the random forest and gradient boosting all stay close to the diagonal: when they say 30%, roughly 30% of those emails are spam. None is perfect (the forest sits a little below the line at low probabilities and above it at high ones), but their numbers are usable as chances. Naive Bayes is a different story. Its points crowd into the corners, and at a predicted probability of about 1.0 there's a group of emails where only about 15% are spam. Its numbers say "certain" about emails it doesn't understand.
Step 3: put a number on it
Accuracy and AUC don't measure calibration: they only care whether predictions land on the right side of a threshold, or in the right order. The Brier score and log loss do, because they score the probabilities themselves:
from sklearn.metrics import accuracy_score, roc_auc_score, brier_score_loss, log_loss
print(f"{'model':20} {'accuracy':>8} {'AUC':>6} {'Brier':>7} {'log loss':>9}")
for name, p in probabilities.items():
print(f"{name:20} {accuracy_score(y_test, p >= 0.5):8.3f} {roc_auc_score(y_test, p):6.3f} "
f"{brier_score_loss(y_test, p):7.4f} {log_loss(y_test, p):9.3f}")
model accuracy AUC Brier log loss
Naive Bayes 0.830 0.949 0.1693 4.236
Logistic regression 0.926 0.969 0.0591 0.251
Random forest 0.959 0.989 0.0376 0.195
Gradient boosting 0.957 0.989 0.0324 0.125
:>8 right-aligns a value in 8 characters, so the columns line up.
Naive Bayes's AUC is 0.949: it ranks emails well, with spam mostly above non-spam. Its probabilities are the problem. Its Brier score (0.169) is several times worse than the others', and its log loss (4.236) is 17 to 34 times worse, because log loss punishes confident mistakes hardest: an email called 99.99% spam that isn't costs as much as dozens of mild mistakes. Gradient boosting has the best probabilities here, with the lowest Brier score and log loss, even though the random forest's accuracy is a touch higher.
Step 4: probability calibration in practice
CalibratedClassifierCV learns a mapping from the model's scores to probabilities, on data the model didn't train on. With cv=5 it splits the training data in five: it trains the model on four parts, fits the mapping on the fifth, repeats for each part, and averages. Experiment: try both mappings on Naive Bayes. Predict first: will calibration change the AUC?
from sklearn.calibration import CalibratedClassifierCV
calibrated = {}
for method in ["sigmoid", "isotonic"]:
model = CalibratedClassifierCV(GaussianNB(), method=method, cv=5).fit(X_train, y_train)
calibrated[method] = model.predict_proba(X_test)[:, 1]
print(f"{'Naive Bayes':20} {'accuracy':>8} {'AUC':>6} {'Brier':>7} {'log loss':>9}")
for name, p in [("uncalibrated", p_nb), ("sigmoid", calibrated["sigmoid"]), ("isotonic", calibrated["isotonic"])]:
print(f"{name:20} {accuracy_score(y_test, p >= 0.5):8.3f} {roc_auc_score(y_test, p):6.3f} "
f"{brier_score_loss(y_test, p):7.4f} {log_loss(y_test, p):9.3f}")
fig, ax = plt.subplots(figsize=(6.5, 6))
ax.plot([0, 1], [0, 1], "k--", label="Perfectly calibrated")
for name, p in [("Naive Bayes", p_nb), ("+ sigmoid", calibrated["sigmoid"]), ("+ isotonic", calibrated["isotonic"])]:
share_spam, mean_pred = calibration_curve(y_test, p, n_bins=10, strategy="quantile")
ax.plot(mean_pred, share_spam, marker="o", label=name)
ax.set_xlabel("Mean predicted probability of spam")
ax.set_ylabel("Share actually spam")
ax.legend()
plt.show()
Naive Bayes accuracy AUC Brier log loss
uncalibrated 0.830 0.949 0.1693 4.236
sigmoid 0.829 0.939 0.1240 0.389
isotonic 0.914 0.945 0.0734 0.266
Isotonic calibration transforms Naive Bayes's probabilities: the Brier score falls from 0.169 to 0.073 and the log loss from 4.236 to 0.266, close to logistic regression. Its reliability curve now follows the diagonal. Accuracy at the 0.5 threshold jumps from 0.830 to 0.914, because the overconfident scores no longer push hundreds of real emails above 0.5.
The AUC changes only a little (0.949 to 0.945): calibration mostly keeps the order. It isn't exactly unchanged, because CalibratedClassifierCV averages five models trained on different folds, and isotonic steps give some emails equal probabilities.
Sigmoid calibration helps much less, and its curve shows why. Naive Bayes gives 453 test emails a probability of exactly 1.0, and many more within a hair of it. A mapping can only look at the score, so every email with the same score gets the same calibrated probability: about 0.70. Inside that group are emails that are mostly spam and emails that mostly aren't, and no mapping of the score can tell them apart. Isotonic calibration can't separate them either, but it gives the whole group an honest average. Calibration repairs probabilities; it can't add information the model never had.
When to calibrate
| Situation | Calibrate? | Why |
|---|---|---|
| You only rank (top 100 leads, a ranked list) | No | Calibration barely changes the order |
| You use a cost-based threshold or multiply by money | Yes | The numbers must mean what they say |
| Naive Bayes, SVM scores, boosting with many trees | Check first | Often overconfident or squashed |
| Logistic regression on enough data | Check, often fine | It's trained on log loss, which rewards calibration |
| Small data (a few hundred rows) | Sigmoid | Isotonic needs more data and can overfit |
| Plenty of data (thousands of rows) | Isotonic | Corrects any monotonic distortion |
Practice
- Without running code: a model predicts 0.8 for 1,000 emails, and 500 of them are spam. Is it calibrated at 0.8? Over- or underconfident?
Show the answer
Not calibrated: it says 80% but only 50% are spam, so it's overconfident there. On a reliability diagram that point would sit below the diagonal.
- Compute the Brier score by hand for three emails: predictions 0.9, 0.2 and 0.6, actual 1, 0 and 0.
Show the answer
((0.9 − 1)² + (0.2 − 0)² + (0.6 − 0)²) ÷ 3 = (0.01 + 0.04 + 0.36) ÷ 3 ≈ 0.137.
print(round(brier_score_loss([1, 0, 0], [0.9, 0.2, 0.6]), 3))
0.137
- Why does calibration need data the model wasn't trained on?
Show the answer
On its own training rows, a model is more confident and more accurate than on new data. A mapping fitted there would learn "the model is about right", and would not correct the overconfidence that appears on new emails.
- Calibrate the random forest with isotonic calibration. Does its Brier score improve?
Show the answer
rf_cal = CalibratedClassifierCV(RandomForestClassifier(n_estimators=300, random_state=0, n_jobs=-1),
method="isotonic", cv=5).fit(X_train, y_train)
p_rf_cal = rf_cal.predict_proba(X_test)[:, 1]
print(round(brier_score_loss(y_test, probabilities["Random forest"]), 4), round(brier_score_loss(y_test, p_rf_cal), 4))
0.0376 0.034
A little: from 0.0376 to 0.0340. The forest was already reasonably calibrated, so there's less to fix. Calibration pays off most for models whose reliability curve is far from the diagonal.
- Why did isotonic calibration raise Naive Bayes's accuracy at the 0.5 threshold, when it barely changes the order of the emails?
Show the answer
Accuracy depends on which emails land above 0.5. Uncalibrated, many non-spam emails got probabilities above 0.5 because the model was overconfident. Calibration moves them below 0.5 without changing which emails rank above which. It's like choosing a better threshold for the old scores.
Interview questions
What does it mean for a classifier to be well calibrated?
Its predicted probabilities match observed frequencies: among cases predicted at about p, a fraction of about p are positive. It's checked with a reliability diagram and measured with the Brier score or log loss.
How do you calibrate a classifier?
Fit a monotonic mapping from the model's scores to probabilities on held-out data: Platt scaling (a sigmoid, good for small data) or isotonic regression (more flexible, needs more data). In scikit-learn, CalibratedClassifierCV does this with cross-validation.
Can a model have high AUC but poor calibration?
Yes. AUC depends only on the order of the predictions, so any monotonic distortion of the probabilities leaves it unchanged while ruining calibration. Naive Bayes is the classic example.
Key takeaways
- A calibrated model's 70% means about 70% of such cases are positive.
- A reliability diagram shows calibration at a glance; the Brier score and log loss measure it.
- Accuracy and AUC don't measure calibration: a model can rank well and still give meaningless probabilities.
- Naive Bayes is overconfident because it counts correlated evidence repeatedly.
CalibratedClassifierCVfixes it with a sigmoid or isotonic mapping fitted on held-out folds.
Frequently asked questions
Should I always calibrate my model?
Only if you use the probabilities as probabilities: for costs, risk scores or combining models. For ranking or a threshold chosen by validation, calibration adds little.
Does calibration change the model's predictions?
It changes the probabilities, and so it can change which side of a fixed threshold such as 0.5 some rows fall. The order of the predictions stays almost the same.
What's the difference between sigmoid and isotonic calibration?
Sigmoid fits two numbers, the slope and position of an S-curve, so it's stable on little data but can only fix S-shaped distortions. Isotonic fits a free-form increasing step function, which fixes any monotonic distortion but can overfit with fewer than about a thousand calibration rows.
What to learn next
- Combine several models into one in voting and stacking, the next lesson.
- Revisit why Naive Bayes counts evidence the way it does in Naive Bayes explained.
- Use calibrated probabilities to set a money-based threshold, as in the customer churn prediction project.