When a model says “70% chance of rain”, it should rain on about 70% of those days. A model whose probabilities match reality like this is well calibrated. Many models rank cases well but give probabilities that are too extreme or too timid. This lesson shows how to check calibration and how to fix it with CalibratedClassifierCV.
In this lesson you will learn
- What calibration means and when it matters
- Reading a calibration curve with
calibration_curve - Scoring probabilities with the Brier score and log loss
- Fixing probabilities with sigmoid and isotonic calibration
You should know logistic regression, Naive Bayes and ROC curves.
Why Probabilities Need to Be Honest
Accuracy and AUC only care about the order of the scores. Often you need the number itself:
- A bank multiplies the chance of default by the loan amount to estimate expected loss.
- A hospital tells a patient their risk is 15%.
- A shop sends a coupon only when the chance of buying is above 30%, because coupons cost money.
In all these cases, a model that says 0.9 when the truth is 0.7 leads to bad decisions, even if its accuracy is high.
Checking Calibration
calibration_curve groups the test rows by predicted probability and compares each group’s average prediction with the share of rows that were actually positive.
from sklearn.calibration import calibration_curve
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
X, y = make_classification(n_samples=6000, n_features=12, n_informative=4,
n_redundant=6, random_state=2)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, random_state=0)
for model in [LogisticRegression(), GaussianNB()]:
p = model.fit(X_tr, y_tr).predict_proba(X_te)[:, 1]
frac_pos, mean_pred = calibration_curve(y_te, p, n_bins=5)
print(type(model).__name__)
print(" said P(yes) ≈", mean_pred.round(2))
print(" actually yes ", frac_pos.round(2))
Output
LogisticRegression
said P(yes) ≈ [0.06 0.3 0.5 0.71 0.92]
actually yes [0.04 0.29 0.6 0.78 0.91]
GaussianNB
said P(yes) ≈ [0.05 0.28 0.5 0.7 0.96]
actually yes [0.19 0.31 0.63 0.78 0.85]
- For logistic regression, the two rows are close: when it says about 0.30, about 29% of those cases are positive. It is reasonably well calibrated, which is common for this model.
- Gaussian Naive Bayes is overconfident at the ends. When it says 0.05, 19% are actually positive; when it says 0.96, only 85% are.
- Naive Bayes assumes the features are independent. This data has redundant, correlated features, so the model counts the same evidence several times and pushes its probabilities toward 0 and 1.
On a chart, you would plot the “said” values on the x-axis and the “actually” values on the y-axis. A perfectly calibrated model lies on the diagonal.
Fixing It With CalibratedClassifierCV
CalibratedClassifierCV learns a mapping from the model’s raw scores to better probabilities. It uses cross-validation, so the mapping is learned on rows the model did not train on.
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
from sklearn.datasets import make_classification
from sklearn.metrics import accuracy_score, brier_score_loss, log_loss
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
X, y = make_classification(n_samples=6000, n_features=12, n_informative=4,
n_redundant=6, random_state=2)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, random_state=0)
models = {
"GaussianNB": GaussianNB(),
"+ sigmoid": CalibratedClassifierCV(GaussianNB(), method="sigmoid", cv=5),
"+ isotonic": CalibratedClassifierCV(GaussianNB(), method="isotonic", cv=5),
}
print(f"{'model':11} {'accuracy':>8} {'Brier':>6} {'log loss':>8}")
for name, model in models.items():
p = model.fit(X_tr, y_tr).predict_proba(X_te)[:, 1]
acc = accuracy_score(y_te, p > 0.5)
print(f"{name:11} {acc:8.3f} {brier_score_loss(y_te, p):6.3f} {log_loss(y_te, p):8.3f}")
frac_pos, mean_pred = calibration_curve(y_te, p, n_bins=5)
print("Isotonic said:", mean_pred.round(2))
print("Actually yes :", frac_pos.round(2))
Output
model accuracy Brier log loss
GaussianNB 0.800 0.165 0.646
+ sigmoid 0.801 0.153 0.482
+ isotonic 0.799 0.152 0.478
Isotonic said: [0.13 0.26 0.49 0.71 0.87]
Actually yes : [0.17 0.26 0.61 0.75 0.86]
- Accuracy barely moves (about 0.80 for all three). Calibration changes the probabilities, not the ranking, so the yes/no predictions at 0.5 stay almost the same.
- The Brier score is the mean squared difference between the probability and the true 0/1 label. Lower is better. It drops from 0.165 to about 0.152.
- Log loss punishes confident wrong answers hard. It falls from 0.646 to under 0.49, because the calibrated model makes far fewer confident mistakes.
- After isotonic calibration, the predicted and actual columns are much closer than before, especially at the ends.
Sigmoid or Isotonic?
| Method | How it maps scores | Use when |
|---|---|---|
method="sigmoid" | Fits an S-shaped curve (Platt scaling) | Small datasets; the error is a simple stretch or squeeze |
method="isotonic" | Fits any curve that only goes up | Plenty of data (roughly 1,000+ rows); the error has an odd shape |
Isotonic is more flexible but can overfit when data is scarce. If in doubt, try both and compare the Brier score with cross-validation.
Common Mistakes
- Calibrating on the training data. The model is overconfident on rows it has already seen. Let
CalibratedClassifierCVuse cross-validation, or calibrate on a separate set. - Judging calibration by accuracy. Use the calibration curve, Brier score or log loss.
- Calibrating after resampling for imbalance. If you oversampled the rare class, the probabilities reflect the new class balance, not the real one.
- Using too few bins. With few bins the curve hides problems; with too many each bin is noisy. Five to ten is usually a good range.
Practice Exercises
Exercise 1. Compute the Brier score by hand for true labels [1, 0, 1] and predictions [0.9, 0.2, 0.6].
Show answer
((0.9 − 1)² + (0.2 − 0)² + (0.6 − 1)²) / 3 = (0.01 + 0.04 + 0.16) / 3 = 0.07.
Exercise 2. Calibrate a random forest with sigmoid calibration and 3 folds.
Show answer
from sklearn.ensemble import RandomForestClassifier
cal = CalibratedClassifierCV(RandomForestClassifier(random_state=0),
method="sigmoid", cv=3)
cal.fit(X_tr, y_tr)
print(cal.predict_proba(X_te[:3]).round(3))
Frequently Asked Questions
Which models are usually well calibrated?
Logistic regression often is, because it is trained with log loss. Naive Bayes tends to be overconfident. Random forests tend to avoid probabilities very close to 0 and 1. Support vector machines do not output probabilities by default at all.
Does calibration improve AUC?
Usually not by much. AUC depends only on the ranking of scores, and calibration mostly keeps that ranking. Isotonic calibration can create ties, which may change AUC slightly.
Summary
- Calibrated probabilities match how often events really happen.
- Check with
calibration_curve, the Brier score and log loss. CalibratedClassifierCVfixes probabilities using cross-validation.- Sigmoid suits small data; isotonic suits larger data.
