Sub topic 17
Checking whether probabilities can be trusted
This chapter assumes you can fit a logistic regression in scikit-learn, know log loss and ROC AUC, and can split data into train and test sets. It covers how to test whether a predicted probability of 0.8 means the event happens about 80% of the time.
Why ranking quality is not enough
ROC AUC only measures ranking: do positives tend to score higher than negatives? A model can rank perfectly and still output probabilities that are far off. If every score is squeezed into the range 0.6 to 0.9, AUC is unchanged, but the numbers are wrong as probabilities.
Calibration matters when you use the number itself:
- Expected-cost decisions, such as "act if probability times cost exceeds the price of acting".
- Risk scores shown to people.
- Combining the output with other probabilities.
If you only need a ranked list, or a threshold tuned on held-out data, calibration matters much less.
A model is calibrated if, among all examples given a predicted probability near p, about a fraction p are actually positive.
Why logistic regression is often well calibrated
Log loss is a proper scoring rule, meaning it is minimized in expectation by the true probabilities. A plain logistic regression fitted by maximum likelihood tends to give reasonable probabilities when its linear log-odds form roughly matches the data. At the optimum without regularization, the average predicted probability equals the observed positive rate on the training data. This holds because the bias gradient, the mean of (p − y), is zero.
Several common choices break this:
- Class weights.
class_weight="balanced"makes the model act as if positives were as common as negatives. Probabilities are shifted upward relative to the real base rate. - Strong regularization. A small
Cshrinks coefficients, so predictions are pulled toward the base rate and become underconfident. - Resampling. Oversampling or undersampling changes the class prior the model sees.
- Model misspecification. If the true log-odds curve is not linear in the features, the sigmoid fits it poorly in some ranges.
- Distribution shift. Probabilities calibrated on last year's data may not hold now.
Measuring calibration
Two tools are standard: a reliability table (or plot) and a scalar score.
The reliability curve groups test predictions into bins. For each bin it compares the mean predicted probability to the observed fraction of positives. Points on the diagonal mean perfect calibration.
The Brier score is the mean squared difference between predicted probability and the 0/1 outcome. Lower is better. Like log loss, it mixes calibration and ranking quality, so use it to compare models, not as a pure calibration test.
The next example shows the effect of class weights on an imbalanced problem.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score
X, y = make_classification(
n_samples=5000, n_features=10, n_informative=5,
weights=[0.9, 0.1], random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.4, stratify=y, random_state=0
)
print("true positive rate:", y_test.mean())
for cw in [None, "balanced"]:
model = make_pipeline(
StandardScaler(), LogisticRegression(class_weight=cw, max_iter=1000)
)
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
print(
cw,
"mean p:", round(proba.mean(), 3),
"brier:", round(brier_score_loss(y_test, proba), 4),
"log loss:", round(log_loss(y_test, proba), 4),
"auc:", round(roc_auc_score(y_test, proba), 4),
)Compare the mean predicted probability with the true positive rate for each setting. With "balanced", the mean should sit well above the true rate, and Brier score and log loss should be worse. AUC should change little, because reweighting mostly shifts scores without reordering them.
Reading a reliability curve
calibration_curve returns the observed fraction of positives and the mean predicted probability per bin. With strategy="quantile", each bin holds the same number of examples. Equal-width bins would leave most bins nearly empty when predictions pile up near 0.
from sklearn.calibration import calibration_curve
model = make_pipeline(
StandardScaler(), LogisticRegression(class_weight="balanced", max_iter=1000)
)
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
frac_pos, mean_pred = calibration_curve(
y_test, proba, n_bins=8, strategy="quantile"
)
for predicted, observed in zip(mean_pred, frac_pos):
print(f"predicted {predicted:.2f} observed {observed:.2f}")Read each row as "when the model said this, the event happened this often". If observed is below predicted, the model is overconfident in that range. If observed is above predicted, it is underconfident.
Fixing miscalibration
Calibration repairs learn a mapping from the model's scores to better probabilities. Scikit-learn's CalibratedClassifierCV supports two:
| Method | Form | Best when | Risk |
|---|---|---|---|
| `"sigmoid"` (Platt scaling) | Fits a logistic curve on the scores | Little calibration data, simple distortion | Too rigid for odd distortions |
| `"isotonic"` | Fits a non-decreasing step function | Thousands of calibration examples | Overfits small samples |
CalibratedClassifierCV uses cross-validation, so the calibrator never sees the same examples the base model was trained on. The estimator= argument name needs scikit-learn 1.2 or later (older versions used base_estimator).
from sklearn.calibration import CalibratedClassifierCV
base = make_pipeline(
StandardScaler(), LogisticRegression(class_weight="balanced", max_iter=1000)
)
calibrated = CalibratedClassifierCV(estimator=base, method="sigmoid", cv=5)
calibrated.fit(X_train, y_train)
p_cal = calibrated.predict_proba(X_test)[:, 1]
print("mean p:", round(p_cal.mean(), 3), "true rate:", round(y_test.mean(), 3))
print("brier before:", round(brier_score_loss(y_test, proba), 4))
print("brier after: ", round(brier_score_loss(y_test, p_cal), 4))Because the base model was trained with balanced weights, the sigmoid calibrator learns to shift the scores back down toward the real base rate. The Brier score should improve.
Common mistakes
- Calibrating when you only threshold. If you choose a threshold from a precision-recall analysis, the raw scores already work. Monotonic recalibration does not change the ranking, so the best achievable trade-off is unchanged.
- Reading sparse bins. A bin with 12 examples gives a noisy observed fraction. Use fewer bins or quantile bins, and treat small deviations as noise.
- Fixing the wrong problem. If a class-weight or resampling choice caused the shift, you can instead train without it, then handle imbalance through the threshold.
- Ignoring drift. Recheck calibration on recent data after deployment. A change in the base rate shifts true probabilities even if the ranking holds.
Exercise
A logistic regression trained with class_weight="balanced" on data with 5% positives gives a test AUC of 0.91. A colleague says the model's output of 0.7 means a 70% chance of the event. Is that claim safe? How would you check and fix it?
Show answer
No. Balanced weights make the model behave as if positives were far more common, so its probabilities are inflated relative to the real 5% base rate. AUC measures ranking only and says nothing about this. Check by comparing the mean predicted probability with the true positive rate and by drawing a reliability curve (calibration_curve with quantile bins) on held-out data. To fix it, either retrain without class weights or wrap the model in CalibratedClassifierCV (sigmoid for small data, isotonic for thousands of examples), then recheck the reliability curve and Brier score on a separate test set.