Sub topic 8
Fitting a calibrator without leaking data
This chapter assumes you know train, validation and test splits, cross-validation, and basic scikit-learn usage. It covers where a calibrator's training data comes from, and which mistakes make a calibrated model look better than it is.
Why a calibrator needs its own data
A calibrator is a small model. It takes the base model's score as input and outputs a corrected probability. Like any model, it is fitted on labeled examples, and it will look good on those examples whether or not it generalizes.
The base model has the same problem in a sharper form. Once it is trained, its scores on its own training rows are unrepresentative. A flexible model such as a random forest or a gradient-boosted ensemble has often memorized those rows. Its training scores sit near 0 or 1 and are nearly always right. If you fit a calibrator on them, it learns that the model is almost perfectly reliable. On new data that is false, and the calibrator will leave the model overconfident, or even make it worse.
The rule is that the calibrator must be fitted on scores for rows that the base model did not train on.
Three ways to get honest scores
There are three common arrangements. They differ in how much data they use and in how much work they take.
| Scheme | How it works | Cost | Weakness |
|---|---|---|---|
| Separate calibration set | Split data into train, calibration and test. Fit the model on train, the calibrator on calibration. | One model fit | The calibrator sees only a slice of the data |
| Cross-validated scores | Produce out-of-fold scores for every training row, then fit one calibrator on all of them. | K model fits | The calibrator is fitted to scores from K different models, not the final one |
| Cross-validated ensemble | Fit one model and one calibrator per fold, then average their calibrated outputs at prediction time. | K model fits | Predictions need K models |
The first scheme is the simplest and the easiest to reason about. The other two spend more compute to avoid wasting data.
Scheme 1: a separate calibration set
Split the data three ways. A common starting point is 60% train, 20% calibration and 20% test, but the right sizes depend on the calibrator. Sigmoid calibration fits two parameters and works with a few hundred rows. Isotonic regression fits a step function and needs far more. The next chapters cover this in detail.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
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=20000, n_features=20, n_informative=5, random_state=0)
X_rest, X_test, y_rest, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
X_train, X_cal, y_train, y_cal = train_test_split(
X_rest, y_rest, test_size=0.25, random_state=0
) # 0.25 of the remaining 80% is 20% of the total
base = RandomForestClassifier(n_estimators=200, random_state=0).fit(X_train, y_train)
# Scores on data the forest never saw. Using a logit makes the sigmoid fit better behaved.
p_cal = np.clip(base.predict_proba(X_cal)[:, 1], 1e-6, 1 - 1e-6)
z_cal = np.log(p_cal / (1 - p_cal)).reshape(-1, 1)
calibrator = LogisticRegression().fit(z_cal, y_cal)
def calibrated_proba(X_new):
p = np.clip(base.predict_proba(X_new)[:, 1], 1e-6, 1 - 1e-6)
z = np.log(p / (1 - p)).reshape(-1, 1)
return calibrator.predict_proba(z)[:, 1]
print("raw :", brier_score_loss(y_test, base.predict_proba(X_test)[:, 1]))
print("calibrated:", brier_score_loss(y_test, calibrated_proba(X_test)))The calibrator is a one-feature logistic regression on the model's score. That is the idea behind Platt scaling, which the next chapter develops. The point here is the data flow: base never saw X_cal, and nothing was fitted on X_test.
The leak, shown directly
The following snippet makes the mistake on purpose. It fits the calibrator on the same rows the forest trained on.
p_train = np.clip(base.predict_proba(X_train)[:, 1], 1e-6, 1 - 1e-6)
z_train = np.log(p_train / (1 - p_train)).reshape(-1, 1)
leaky = LogisticRegression().fit(z_train, y_train)
p_test = np.clip(base.predict_proba(X_test)[:, 1], 1e-6, 1 - 1e-6)
z_test = np.log(p_test / (1 - p_test)).reshape(-1, 1)
print("leaky calibrator:", brier_score_loss(y_test, leaky.predict_proba(z_test)[:, 1]))
print("honest calibrator:", brier_score_loss(y_test, calibrated_proba(X_test)))Run it and compare the two numbers. The leaky calibrator is typically worse, because it learned from near-perfect training scores that high scores are always correct. It then amplifies the forest's overconfidence instead of correcting it. The exact values vary with the model and seed, but the direction is reliable for models that overfit their training data.
Scheme 2 and 3: cross-validation
When data is scarce, a held-out calibration set is expensive. Cross-validation reuses every row for both purposes, but never for both at once within a single fold.
CalibratedClassifierCV implements the third scheme by default. With cv=5, it does the following for each fold:
- Clone the base estimator and fit it on four fifths of the training data.
- Score the remaining fifth, which the clone has not seen.
- Fit a calibrator on those out-of-fold scores.
At prediction time it averages the calibrated probabilities from all five model and calibrator pairs. Setting ensemble=False changes this. The out-of-fold scores from all folds are pooled to fit a single calibrator, and the base model is refitted on all the data. That is the second scheme. It gives you one model to deploy, at the price of a slight mismatch: the calibrator was fitted to scores from models trained on 80% of the data, but it is applied to a model trained on 100%.
from sklearn.calibration import CalibratedClassifierCV
from sklearn.ensemble import RandomForestClassifier
cal_cv = CalibratedClassifierCV(
RandomForestClassifier(n_estimators=200, random_state=0),
method="sigmoid",
cv=5,
ensemble=True,
)
cal_cv.fit(X_rest, y_rest) # X_rest includes the training and calibration rows from above
print("cv calibrated:", brier_score_loss(y_test, cal_cv.predict_proba(X_test)[:, 1]))Note that fit receives only the development data. The test set is still untouched.
Pre-fitted models and `FrozenEstimator`
Sometimes you already have a trained model and want to calibrate it on a separate set. Older scikit-learn versions used cv="prefit" for this. That option was deprecated in version 1.6 and later removed. The replacement wraps the fitted model in FrozenEstimator, which stops fit from retraining it.
from sklearn.frozen import FrozenEstimator
cal_prefit = CalibratedClassifierCV(FrozenEstimator(base), method="sigmoid")
cal_prefit.fit(X_cal, y_cal)
print("prefit calibrated:", brier_score_loss(y_test, cal_prefit.predict_proba(X_test)[:, 1]))This requires scikit-learn 1.6 or newer. With an older version, use cv="prefit" instead. Either way, the data passed to fit must be rows the base model did not train on.
Other leaks to watch for
- Preprocessing fitted on everything. If you fit a scaler or imputer on the full dataset before splitting, information from the test set has leaked into the pipeline. Fit preprocessing inside a
Pipelineso it is refitted per split. - Tuning on the test set. Choosing between sigmoid and isotonic by looking at test Brier score makes the test score optimistic. Choose the method by cross-validation on development data, then report the test score once.
- Hyperparameter search and calibration together. If the search used the calibration set to pick hyperparameters, that set is no longer fresh. Give the search its own validation data, or put it inside the training fold.
- Duplicates and groups. If the same patient, user or document appears in several rows, a random split puts near-copies on both sides. Use
GroupKFoldor a group-aware split so the calibration rows are truly unseen. - Time ordering. For data that drifts over time, calibrate on a period that follows the training period, and test on a period after that. A random split hides the drift that will hurt you in production.
Checking your own pipeline
A short checklist helps when reviewing code, yours or someone else's.
- List every object that is fitted: scaler, model, calibrator, threshold.
- For each, write down exactly which rows it saw.
- Confirm that no row appears in both the base model's fit data and the calibrator's fit data, unless it is out-of-fold.
- Confirm that the final test rows appear in none of them.
Exercise
You train a gradient-boosted model on 10,000 rows, then fit a sigmoid calibrator on the model's predicted probabilities for those same 10,000 rows. On a held-out test set the calibrated model is no better than the raw one. Give the cause, and name two fixes that keep all the data in use.
Show answer
The calibrator was fitted on in-sample scores. The boosted model has partly memorized its training rows, so those scores look more reliable than the model's scores on new data, and the calibrator learns no useful correction. Two fixes: wrap the model in CalibratedClassifierCV with cv=5, so the calibrator sees only out-of-fold scores; or generate out-of-fold predictions with crossvalpredict and fit a single calibrator on them, then refit the base model on all the data. Holding out a separate calibration set also works, but it leaves fewer rows for the base model.
Exercise
With CalibratedClassifierCV(cv=5, ensemble=False), the calibrator is fitted on pooled out-of-fold scores, but the deployed model is trained on all the data. What mismatch does this create, and when does it matter most?
Show answer
The calibrator learned the score distribution of models trained on 80% of the data, but it is applied to a model trained on 100%. The final model's scores may be slightly more confident or better separated than the ones the calibrator saw. The effect is small for stable models and large datasets. It matters most for small datasets and for high-variance models, where the amount of training data changes the score distribution noticeably.