Sub topic 11
Probability calibration after rebalancing
This chapter assumes you can fit scikit-learn classifiers, read a predict_proba output, and know the rebalancing tools from earlier chapters (class weights, resampling, SMOTE). It builds on the threshold-tuning chapter.
Why rebalancing distorts probabilities
A model is calibrated when its predicted probabilities match observed frequencies. Among all cases scored 0.2, about 20% should be positive.
Rebalancing breaks this. Class weights, oversampling and SMOTE make the model behave as if the rare class were common. If the real positive rate is 5% and class_weight="balanced" makes the training signal look 50/50, the scores shift upward. A score of 0.7 no longer means "70% likely to be positive".
This matters only when you use the number as a probability. Examples are expected-cost calculations, risk scores shown to people, and combining model outputs. If you only rank cases, or tune a threshold on out-of-fold predictions, miscalibration is mostly harmless.
Measuring calibration
Two checks are enough here:
- Mean predicted probability versus prevalence. On a well-calibrated model the average predicted probability is close to the true positive rate.
- Brier score. This is the mean squared difference between predicted probability and the 0/1 outcome. Lower is better.
calibration_curve bins predictions and returns the observed positive fraction per bin. Plot it against the mean predicted value per bin. A calibrated model lies near the diagonal.
Fixing it with a calibrator
The usual fix is to fit a small mapping from raw scores to probabilities, using data the base model did not train on. CalibratedClassifierCV does this with cross-validation. Its two methods are:
"sigmoid"(Platt scaling) fits a logistic curve. It has few parameters, so it suits small positive counts."isotonic"fits a flexible step function. It needs more positives, often well over a thousand, or it overfits.
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_samples=10000, n_features=20, n_informative=5,
weights=[0.95, 0.05], flip_y=0.01, random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
balanced = LogisticRegression(class_weight="balanced", max_iter=1000)
calibrated = CalibratedClassifierCV(
LogisticRegression(class_weight="balanced", max_iter=1000),
method="sigmoid",
cv=5,
)
print("prevalence:", y_test.mean())
for name, model in [("balanced", balanced), ("calibrated", calibrated)]:
model.fit(X_train, y_train)
p = model.predict_proba(X_test)[:, 1]
print(name, "mean prob:", p.mean(), "brier:", brier_score_loss(y_test, p))
frac_pos, mean_pred = calibration_curve(
y_test, calibrated.predict_proba(X_test)[:, 1], n_bins=10, strategy="quantile"
)
print(list(zip(mean_pred.round(3), frac_pos.round(3))))The balanced model's mean probability should sit far above the prevalence. The calibrated model's should land close to it, and its Brier score should be lower. Because the calibrator trains on the original class ratio, it undoes the shift the weights introduced.
Common errors
- Calibrating on resampled data. If the calibrator sees oversampled or SMOTE data, it learns the artificial class ratio and reproduces the distortion. Fit it on untouched data.
- Calibrating and evaluating on the same rows. Use separate data or cross-validation, and report metrics on a test set no step has seen.
- Using isotonic with few positives. The curve becomes jagged. Prefer
"sigmoid". - Keeping an old threshold. Calibration moves scores, so redo threshold tuning afterward.
- Expecting better ranking. Calibration fixes probability meaning, not discrimination.
For plain oversampling or weighting, a closed-form fix also exists. Multiply the odds by the ratio of true prior odds to training prior odds. A fitted calibrator is usually more reliable because it also corrects the model's own bias.
Exercise
A fraud model trained with class_weight="balanced" has an average predicted probability of 0.30, but only 2% of transactions are fraud. The team wants to multiply each probability by the transaction amount to estimate expected loss. Should they calibrate first? Which data should the calibrator be fitted on?
Show answer
Yes. The expected-loss calculation treats the score as a real probability, and this model overstates it roughly fifteen-fold on average. Fit the calibrator (sigmoid is a safe choice with few positives) on held-out or cross-validated data that keeps the natural 2% fraud rate, never on resampled data. Check the result with mean predicted probability versus prevalence and the Brier score on a separate test set.