Sub topic 11
Calibrating a model with CalibratedClassifierCV
This chapter assumes you know how to read a reliability diagram, how Brier score and log loss are computed, and why a calibrator must not be fit on the data used to train the base model. It also assumes you are comfortable with scikit-learn estimators and cross-validation. Here you will learn how CalibratedClassifierCV applies those ideas, what its options do, and where it can go wrong.
What the class does
CalibratedClassifierCV wraps a classifier and adds a post-hoc calibration step. It does two jobs:
- It splits the data so the calibrator never sees examples that trained the base model.
- It fits a calibrator, either
"sigmoid"(Platt scaling) or"isotonic", that maps the model's raw output to a probability.
The raw output is whatever the base estimator provides, decision_function or predict_proba. This is why the wrapper works on a LinearSVC, which has no predict_proba. The calibrator turns its margins into probabilities.
The constructor arguments that matter
| Argument | Meaning | Default |
|---|---|---|
| `estimator` | The base classifier. Unfitted, unless wrapped in `FrozenEstimator`. | `LinearSVC` if omitted |
| `method` | `"sigmoid"` or `"isotonic"` | `"sigmoid"` |
| `cv` | Integer, splitter object, or iterable of splits | 5-fold stratified |
| `ensemble` | Keep one calibrated copy per fold, or a single model | `True` |
| `n_jobs` | Parallel fitting across folds | `None` |
How `ensemble=True` and `ensemble=False` differ
The ensemble flag changes what you get back, and the difference affects both cost and quality.
With ensemble=True, there are k base models and k calibrators. Each calibrator sees the held-out part of one fold. Prediction averages the k calibrated probabilities. This costs k times the memory and prediction time. It gives a bagging-like average, and every base model trains on only (k-1)/k of the data.
With ensemble=False, the calibrator is fit on out-of-fold predictions from every row. The final base model is then trained on all the data. You get one model and one calibrator. The catch is a small mismatch: the calibrator learned the behavior of models trained on (k-1)/k of the data, but it is applied to a model trained on all of it. With a large k or a large dataset, the mismatch is usually negligible.
The following script compares both modes with isotonic calibration and shows what is stored.
from sklearn.calibration import CalibratedClassifierCV
from sklearn.datasets import make_classification
from sklearn.metrics import brier_score_loss
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
X, y = make_classification(
n_samples=20000, n_features=20, n_informative=5, n_redundant=10, random_state=0
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.5, random_state=0
)
raw = GaussianNB().fit(X_train, y_train)
print("raw :", brier_score_loss(y_test, raw.predict_proba(X_test)[:, 1]))
for ensemble in (True, False):
cal = CalibratedClassifierCV(
GaussianNB(), method="isotonic", cv=5, ensemble=ensemble
)
cal.fit(X_train, y_train)
p = cal.predict_proba(X_test)[:, 1]
print(
f"ensemble={ensemble!s:<6}:",
round(brier_score_loss(y_test, p), 4),
"| fitted pairs:",
len(cal.calibrated_classifiers_),
)The attribute calibrated_classifiers_ holds the fitted pairs: 5 with ensemble=True, 1 with ensemble=False. Compare the two Brier scores against the raw model. On a dataset this size they should be close to each other and better than the raw score.
Calibrating an already trained model
Sometimes retraining is expensive, or the base model was trained elsewhere. In that case you hold out a separate calibration set and calibrate the existing model on it. Older code did this with cv="prefit". That option is deprecated as of scikit-learn 1.6. The replacement is to wrap the fitted model in FrozenEstimator from sklearn.frozen, which turns fit into a no-op.
from sklearn.calibration import CalibratedClassifierCV
from sklearn.datasets import make_classification
from sklearn.frozen import FrozenEstimator
from sklearn.metrics import brier_score_loss
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
X, y = make_classification(n_samples=30000, n_features=20, n_informative=5, random_state=1)
X_train, X_rest, y_train, y_rest = train_test_split(X, y, test_size=0.5, random_state=1)
X_cal, X_test, y_cal, y_test = train_test_split(X_rest, y_rest, test_size=0.5, random_state=1)
svm = LinearSVC().fit(X_train, y_train)
calibrated = CalibratedClassifierCV(FrozenEstimator(svm), method="sigmoid")
calibrated.fit(X_cal, y_cal)
p = calibrated.predict_proba(X_test)[:, 1]
print("Brier score:", brier_score_loss(y_test, p))The three-way split is the point. X_train fits the base model, X_cal fits the calibrator, and X_test scores the result. If you reuse X_train for calibration, the base model's margins on those rows are overconfident. The calibrator then learns the wrong mapping.
Choosing `cv`
The default of 5 folds is a reasonable start. A few rules help you adjust it.
- Small positive class. Use stratified splits, which the integer default does for classifiers. With very few positives, a fold's held-out part may contain only a handful of them, and isotonic regression will produce step functions that jump on a few points.
- Grouped or time-ordered data. Pass a splitter such as
GroupKFoldorTimeSeriesSplit. If rows from the same user or the same period land in both the training and held-out parts of a fold, the held-out predictions are too confident. The calibrator then learns that the model is more reliable than it is. Note thatTimeSeriesSplitdoes not put every row in a held-out part, so with it you should check thatensemble=Trueis what you want. - Expensive base model. Each fold means one base-model fit. With
ensemble=False, add the final refit. For a model that takes hours to train, a single prefit calibration split is often cheaper than 5-fold cross-validation.
Behavior to know about
Multiclass is one-vs-rest. For more than two classes, the wrapper calibrates each class's score against the rest. It then normalizes the resulting probabilities so each row sums to 1. This works, but the normalization step can undo some of the per-class calibration. Evaluate with a multiclass log loss, and also inspect per-class reliability curves.
Predicted classes can change. Isotonic regression produces flat segments, so several inputs can map to the same probability. Ties then appear where the raw model ranked cases apart. Argmax of the calibrated outputs can also differ from the base model's prediction. In the binary case, a monotonic map leaves the ranking unchanged, but ties reduce AUC slightly. Check AUC before and after.
Base models that are already well calibrated. Logistic regression trained with log loss is often close to calibrated already. Wrapping it can add noise without benefit, especially with isotonic. Always compare against the raw model on held-out data.
Cross-validation tools see the wrapper as a classifier. You can pass it to cross_val_score, GridSearchCV, or a Pipeline. Nested use means an inner split inside each outer training fold. Use scoring="neg_brier_score" or "neg_log_loss" rather than accuracy, since accuracy will barely move.
A short checklist
- Measure the raw model first: reliability curve, Brier score, log loss on a held-out set.
- Calibrate with
cv=5andmethod="sigmoid"as the baseline. - Try
"isotonic"only if you have enough data, roughly thousands of calibration rows or more. - Score every variant on a test set that no step has touched.
- Keep the winner only if the improvement is larger than the noise across seeds or folds.
Exercise
You trained a gradient boosting model on 80% of your data and kept the other 20% as a test set. A colleague proposes calling CalibratedClassifierCV(FrozenEstimator(model), method="isotonic").fit(X_train, y_train) and then reporting the Brier score on the test set. What is wrong, and how would you fix it?
Show answer
The calibrator is fit on the same rows that trained the base model, so the model's predictions on them are overconfident and the calibrator learns a mapping that does not hold on new data. The test Brier score will then look worse than it should, or the calibration will not transfer. Fix it by splitting the 80% into a training part and a separate calibration part, fitting the base model on the first, fitting the calibrator on the second with FrozenEstimator, and keeping the original 20% untouched for the final score. Alternatively, pass the unfitted model with cv=5 and let CalibratedClassifierCV handle the folds.
Exercise
With ensemble=False and cv=5, on which data is the final base model trained, and on which data does the calibrator learn?
Show answer
The final base model is refit on all the training data passed to fit. The calibrator learns from the pooled out-of-fold predictions, where each row was predicted by a model that did not train on it.