Sub topic 11
Probability calibration after rebalancing
This chapter assumes you can fit a scikit-learn classifier, read predict_proba output, and use stratified cross-validation. It also assumes you have seen class weights, resampling, and threshold tuning from earlier chapters.
Rebalancing helps a model find the rare class. It can also make the model's probabilities wrong. A model trained on a 50/50 mix will report 0.5 for cases that are positive only 5% of the time in production. This chapter shows how to detect that, why it happens, and three ways to fix it.
Ranking versus probability
A classifier can do two jobs:
- Rank cases from most to least likely positive. Metrics such as average precision and ROC AUC measure this.
- Estimate probability: when it says 0.30, about 30% of those cases should be positive.
A model is calibrated if its predicted probabilities match observed frequencies. Calibration is separate from ranking. Any monotonic transformation of the scores, such as squaring them, leaves the ranking and the AUC unchanged. It can destroy calibration.
You can skip calibration if you only need a ranked list or a threshold picked from validation data. You need it when a downstream step reads the number as a probability. Examples are expected-cost calculations (p * cost_of_miss), risk scores shown to people, and combining outputs from several models.
Why rebalancing shifts probabilities
A model fitted on rebalanced data learns the positive rate of that data. If the real rate is 5% and you oversample the minority to 50%, the model behaves as if positives are as common as negatives. Its probabilities are inflated for the real population.
Class weights do the same thing. With class_weight="balanced", each positive example counts about 19 times as much as a negative one when the positive rate is 5%. The loss then behaves as if the classes were equal in size.
In odds terms, the shift is a constant multiplicative factor. Odds are p / (1 - p). Suppose the training prior is pi_train and the true prior is pi_true. The model's odds are too large by roughly this factor:
(pi_train / (1 - pi_train)) / (pi_true / (1 - pi_true))
For a 50/50 training mix and a 5% true prior, the factor is 1 / (0.05 / 0.95), which is 19. This is a prior shift. It is the cleanest case, and it can be corrected exactly if the model's other probabilities were right.
Undersampling and SMOTE behave the same way, because they also change the class ratio the model sees. A model that is flexible and fits the training data tightly, such as a deep tree or boosted trees with many rounds, adds its own distortion on top of the prior shift. In that case the correction below only removes part of the error.
Measuring calibration
Three tools are common.
- Mean predicted probability against observed rate. On an unbiased test set, the average of
predict_probashould be close to the fraction of positives. This single comparison catches a prior shift immediately. - Brier score. This is the mean squared error between probability and outcome (
brier_score_loss). Lower is better. It mixes ranking quality and calibration. - Reliability curve.
calibration_curvegroups predictions into bins and gives the observed positive rate per bin. A calibrated model lies on the diagonal.
With a 5% positive rate, equal-width bins leave most bins nearly empty. Use strategy="quantile" so each bin holds the same number of samples.
The code below trains an unweighted and a balanced logistic regression on the same data and compares them. It is self-contained, so you can run it without the earlier chapters.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, average_precision_score
from sklearn.calibration import calibration_curve
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
)
plain = LogisticRegression(max_iter=1000).fit(X_train, y_train)
balanced = LogisticRegression(class_weight="balanced", max_iter=1000).fit(
X_train, y_train
)
print("observed positive rate:", round(y_test.mean(), 4))
for name, model in [("plain", plain), ("balanced", balanced)]:
p = model.predict_proba(X_test)[:, 1]
print(
name,
"| mean predicted:", round(p.mean(), 4),
"| Brier:", round(brier_score_loss(y_test, p), 4),
"| AP:", round(average_precision_score(y_test, p), 4),
)
p_bal = balanced.predict_proba(X_test)[:, 1]
frac_pos, mean_pred = calibration_curve(
y_test, p_bal, n_bins=8, strategy="quantile"
)
for mp, fp in zip(mean_pred, frac_pos):
print(f"predicted {mp:.3f} -> observed {fp:.3f}")Expect the following. The balanced model's mean predicted probability is several times the observed rate, and its Brier score is worse than the plain model's. In the reliability table, the observed rate sits below the predicted value in most bins. Average precision should be similar for both models, because the weights change the scale of the scores far more than their order.
Fix 1: correct the prior analytically
If the only distortion is the shift in class prior, you can undo it with the odds factor from earlier. This costs nothing, needs no extra data, and keeps the model unchanged.
def correct_prior(p, train_prior, true_prior):
"""Map probabilities from a model trained at train_prior to true_prior."""
p = np.clip(p, 1e-12, 1 - 1e-12)
odds = p / (1 - p)
factor = (true_prior / (1 - true_prior)) / (train_prior / (1 - train_prior))
adjusted = odds * factor
return adjusted / (1 + adjusted)
true_prior = y_train.mean() # estimated from the unmodified training labels
train_prior = 0.5 # balanced class weights act like a 50/50 mix
p_fixed = correct_prior(p_bal, train_prior, true_prior)
print("mean predicted after correction:", round(p_fixed.mean(), 4))
print("Brier before:", round(brier_score_loss(y_test, p_bal), 4))
print("Brier after: ", round(brier_score_loss(y_test, p_fixed), 4))The correction preserves the ranking, so average precision does not change. For random oversampling or undersampling, set train_prior to the positive fraction after resampling. For SMOTE, use the same rule: the fraction of positives in the resampled training set.
This method assumes the true prior is known and stable. If production prevalence differs from your training data, use the production rate as true_prior. If you do not know it, estimate it from a recent random sample of labeled data.
Fix 2: fit a calibrator on held-out data
Prior correction cannot repair a model whose probabilities are distorted in other ways. For that, learn a mapping from scores to probabilities using data the model did not train on. CalibratedClassifierCV does this with cross-validation.
from sklearn.calibration import CalibratedClassifierCV
from sklearn.model_selection import StratifiedKFold
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
calibrated = CalibratedClassifierCV(
estimator=LogisticRegression(class_weight="balanced", max_iter=1000),
method="sigmoid",
cv=cv,
)
calibrated.fit(X_train, y_train)
p_cal = calibrated.predict_proba(X_test)[:, 1]
print("mean predicted:", round(p_cal.mean(), 4))
print("Brier:", round(brier_score_loss(y_test, p_cal), 4))
print("AP:", round(average_precision_score(y_test, p_cal), 4))For each fold, the wrapper fits the base model on the training part and fits a calibrator on the held-out part. The held-out part keeps the real class ratio, even though the base model was trained with weights. The calibrator therefore learns the correct prior as a side effect. predict_proba then averages the five calibrated models.
Two methods are available:
| Method | What it fits | Use when | Risk |
|---|---|---|---|
| `"sigmoid"` (Platt scaling) | Two parameters, a logistic curve on the score | Few positives, and the distortion is smooth | Cannot fix a non-sigmoid shape |
| `"isotonic"` | A free-form monotonic step function | Many positives (roughly a thousand or more in the calibration folds) | Overfits with few positives and produces flat steps and ties |
With a rare class, the number of positives in each calibration fold is what limits you, not the total row count. Here that number is about 75 per fold (7,500 training rows, 5% positive, five folds), so sigmoid is the safer choice.
Isotonic output can contain many tied probabilities. Ties can change a precision-recall curve and make threshold selection coarser.
Calibration with resampling in the pipeline
You can pass an imblearn pipeline that contains SMOTE as the estimator. The resampler runs only when the pipeline is fitted on the training part of each fold, so the calibration part stays untouched and keeps the real prior. This is the same leakage rule as in the pipeline chapter.
Never calibrate on resampled data. A calibrator fitted on a 50/50 set learns the 50/50 prior and repeats the original problem.
Calibration and threshold tuning
The two topics interact. A threshold is a cutoff on whatever score the model emits.
- If you tune the threshold on out-of-fold scores and apply it to the same type of score at test time, you do not need calibrated probabilities. The tuned threshold absorbs the shift. A balanced model might end up with a best threshold of 0.8.
- If you calibrate afterward, the score scale changes and the old threshold no longer applies. Tune the threshold on the calibrated scores, or transform the threshold with the same mapping.
- If the threshold is derived from costs, for example "flag when expected loss exceeds review cost", you need calibrated probabilities first. With a cost
C_fnfor a missed positive andC_fpfor a false alarm, the decision-theoretic threshold isC_fp / (C_fp + C_fn). That formula is only valid when probabilities are calibrated.
Common errors
- Calibrating on the test set. The test set must stay out of every fitting step, including the calibrator. Use cross-validation inside the training data, or a separate calibration split.
- Judging calibration by AUC or average precision. Both are unchanged by monotonic remapping, so they cannot reveal miscalibration.
- Reading a reliability curve built on a resampled test set. Evaluation data must have the real class ratio. If you resample the test set, the curve and Brier score describe the resampled world.
- Applying prior correction twice. If you used
CalibratedClassifierCVand then also applied the odds factor, you have overcorrected. Check the mean predicted probability against the observed rate after each step. - Isotonic with too few positives. A staircase fitted to 30 positives memorizes noise.
- Assuming tree ensembles are fixed by the prior correction. Random forests and boosted models often produce S-shaped distortions in addition to the prior shift. Use the held-out calibrator and verify with a reliability curve.
Summary of the workflow
- Train with weights or resampling, and judge ranking with average precision.
- If probabilities matter, compare mean predicted probability with the observed rate on an untouched, stratified test set.
- Apply the odds correction if the shift is purely prior, or fit
CalibratedClassifierCVfor anything else. - Re-run the reliability curve and the Brier score. Then choose the threshold on the final scores.
Exercise
A model trained with class_weight="balanced" on data with a true positive rate of 2% outputs 0.40 for a case. Treat the balanced weights as an effective 50/50 training prior. What is the prior-corrected probability?
Show answer
The model's odds are 0.40 / 0.60 = 0.667. The factor is (0.02 / 0.98) / (0.5 / 0.5) = 0.0204. The corrected odds are 0.667 * 0.0204 = 0.01361. The corrected probability is 0.01361 / 1.01361, which is about 0.0134, or 1.3%. The model's 0.40 was strongly inflated by the weighting.
Exercise
You balance your training data with SMOTE and then fit isotonic calibration on the same SMOTE-resampled data. The reliability curve on a stratified, unmodified test set still shows predicted probabilities far above observed rates. Why, and what should you change?
Show answer
The calibrator was fitted on data with an artificial class ratio, so it learned the inflated prior and kept it. Fit the calibrator on held-out data with the real class ratio. Put the SMOTE pipeline inside CalibratedClassifierCV so resampling happens only on each fold's training part. With few positives, also prefer method="sigmoid" over isotonic.