Sub topic 16
Calibrating predicted probabilities
This chapter assumes you know binary logistic regression, train/validation/test splits, and the multiclass and multilabel setups from the earlier chapters. You should be able to read the output of predict_proba and understand per-label thresholds.
What calibration means
A model is calibrated when its stated confidence matches how often it is right. If a model gives 0.8 to 1,000 predictions, about 800 of them should be correct.
Softmax and sigmoid outputs look like probabilities because they lie in [0, 1], and softmax rows sum to 1. That does not make them calibrated. Training minimizes a loss, and the loss does not force confidence to match frequency. Many models are overconfident (large neural networks, boosted trees with many rounds). Others are underconfident (random forests, which average votes and so avoid extreme values). Naive Bayes pushes scores toward 0 and 1 because it multiplies feature likelihoods as if they were independent.
Calibration matters in three situations:
- You report the probability to a person or pass it to a downstream decision, such as expected cost.
- You use one shared threshold across several labels, which only makes sense if the scores mean the same thing for each label.
- You compare or combine models by averaging their probabilities.
Calibration is not needed if you only rank items or pick the argmax. A monotone increasing transform does not change the ranking or the argmax of a single score. It also does not change the best threshold, because the threshold simply moves with the transform.
Measuring calibration
Three measures are common.
| Measure | What it captures | Notes |
|---|---|---|
| Log loss | Quality of the full probability vector | Sensitive to overconfident mistakes |
| Brier score | Mean squared error between probability and outcome | Bounded, easier to interpret than log loss |
| Expected calibration error (ECE) | Gap between confidence and accuracy, averaged over confidence bins | Depends on the number of bins |
Log loss and Brier score are proper scoring rules. They reward both calibration and sharpness (how decisive the probabilities are), so they cannot be gamed by always predicting the base rate. ECE isolates the calibration gap but can be fooled: a model that always predicts the base rate has an ECE near zero and is useless.
A reliability diagram plots mean predicted probability against observed frequency per bin. A perfect model lies on the diagonal. A curve below the diagonal at high confidence means overconfidence.
Multiclass: top-label calibration
For multiclass, the usual check is top-label calibration. Take the maximum probability in each row as the confidence and compare it with whether the argmax was correct. A stricter definition requires every class probability to be calibrated, which needs far more data to estimate.
Multilabel: per-label calibration
For multilabel, each label is a binary problem. Check calibration separately for each label, because rare labels and common labels are often miscalibrated in different directions.
Calibration methods
All methods fit a small mapping from raw scores to probabilities, using data the base model did not train on.
- Sigmoid (Platt scaling). Fits
p = 1 / (1 + exp(a*s + b))on the scores. It has two parameters, so it works with little data. It assumes the distortion is sigmoid-shaped. - Isotonic regression. Fits a non-decreasing step function. It is flexible but needs more data, roughly a thousand or more calibration samples per label, and can overfit below that.
- Temperature scaling. Divides the logits by a single scalar
Tbefore softmax.T > 1softens overconfident output, andT < 1sharpens it. It preserves the argmax exactly and has one parameter. It is common for neural networks and is not built into scikit-learn.
Calibrating a multiclass model
CalibratedClassifierCV wraps a classifier. With cv=5 it trains five clones on training folds, calibrates each on its held-out fold, and averages them at prediction time. For multiclass problems it calibrates each class one-vs-rest, then renormalizes each row so it sums to 1.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import log_loss
def top_label_ece(y_true, proba, n_bins=10):
conf = proba.max(axis=1)
correct = (proba.argmax(axis=1) == y_true).astype(float)
edges = np.linspace(0.0, 1.0, n_bins + 1)
ids = np.digitize(conf, edges[1:-1]) # bin index 0..n_bins-1
ece = 0.0
for b in range(n_bins):
mask = ids == b
if mask.any():
ece += mask.mean() * abs(correct[mask].mean() - conf[mask].mean())
return ece
X, y = make_classification(
n_samples=6000, n_features=20, n_informative=6, n_redundant=6,
n_classes=3, n_clusters_per_class=2, random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=0
)
raw = GaussianNB().fit(X_train, y_train)
iso = CalibratedClassifierCV(GaussianNB(), method="isotonic", cv=5).fit(X_train, y_train)
for name, model in (("raw", raw), ("isotonic", iso)):
proba = model.predict_proba(X_test)
print(name,
"log loss", round(log_loss(y_test, proba), 3),
"top-label ECE", round(top_label_ece(y_test, proba), 3),
"accuracy", round((proba.argmax(axis=1) == y_test).mean(), 3))Expect log loss and ECE to drop for the calibrated model. Accuracy may change slightly, because calibration is applied per class and can change which class is largest.
Calibrating a multilabel model
Multilabel problems need one calibrator per label. The example below fits the base model on a training split, fits an isotonic calibrator per label on a separate validation split, and scores on a test split. Keeping the three splits apart avoids calibrating on data the model has already memorized.
import numpy as np
from sklearn.datasets import make_multilabel_classification
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.multiclass import OneVsRestClassifier
from sklearn.isotonic import IsotonicRegression
from sklearn.metrics import brier_score_loss
X, Y = make_multilabel_classification(
n_samples=6000, n_features=20, n_classes=5, n_labels=2, random_state=0
)
X_train, X_rest, Y_train, Y_rest = train_test_split(X, Y, test_size=0.5, random_state=0)
X_val, X_test, Y_val, Y_test = train_test_split(X_rest, Y_rest, test_size=0.5, random_state=0)
model = OneVsRestClassifier(GaussianNB()).fit(X_train, Y_train)
p_val = model.predict_proba(X_val)
p_test = model.predict_proba(X_test)
calibrated = np.zeros_like(p_test)
for j in range(Y.shape[1]):
iso = IsotonicRegression(out_of_bounds="clip", y_min=0.0, y_max=1.0)
iso.fit(p_val[:, j], Y_val[:, j])
calibrated[:, j] = iso.predict(p_test[:, j])
for j in range(Y.shape[1]):
print("label", j,
"Brier raw", round(brier_score_loss(Y_test[:, j], p_test[:, j]), 3),
"calibrated", round(brier_score_loss(Y_test[:, j], calibrated[:, j]), 3))Because each isotonic map is non-decreasing, within one label the ranking is unchanged apart from ties: isotonic regression produces flat steps, so previously distinct scores can become equal.
Interaction with threshold tuning
Calibration and threshold tuning solve different problems.
- Tuning a per-label threshold on a validation set directly optimizes F1 (or another metric) for that label. It works on uncalibrated scores.
- Calibration makes the score interpretable. After calibration, a single threshold has a shared meaning across labels, and a cost-based rule becomes available: predict the label when
p > cost_FP / (cost_FP + cost_FN).
Calibration does not make a threshold of 0.5 optimal for F1. For an F1-optimal decision on a calibrated model the best threshold is typically below 0.5 and depends on the label's base rate, so you still tune it.
Common errors
- Calibrating on the training set. The model's training scores are already optimistic, so the calibrator learns nothing useful. Use a held-out split or cross-validation inside
CalibratedClassifierCV. - Reusing the test set. If you pick the method or bins by looking at test ECE, the test estimate is biased. Keep a final untouched split.
- Isotonic on small or rare labels. A label with 20 positives gives a jagged step function that overfits. Prefer sigmoid there, or pool the data with cross-validation.
- Trusting ECE alone. Report log loss or Brier score alongside it, and plot the reliability diagram. With few samples per bin, ECE is noisy.
- Resampling for imbalance, then reading probabilities literally. Oversampling or class weights shift the predicted base rate. Calibrate on data with the original class distribution.
Exercise
A multilabel model has been calibrated with isotonic regression on a validation set, so every label's probabilities now match observed frequencies. Your teammate says the F1-optimal threshold for each label should therefore be 0.5. Is that right? What would you do instead?
Show answer
No. Calibration makes the probabilities match frequencies, but F1 does not reward a 0.5 cutoff. For a calibrated rare label the F1-optimal threshold is usually well below 0.5, and it differs by label base rate. Keep the calibrated scores and tune a threshold per label on a validation split by scanning candidate thresholds and picking the one that maximizes F1, then check the result on a separate test split.
Exercise
You have a naive Bayes multiclass model whose test accuracy is 0.84. After wrapping it in CalibratedClassifierCV the accuracy is 0.84 and the log loss falls sharply. Explain why log loss can improve while accuracy stays the same.
Show answer
Accuracy depends only on which class has the largest probability, while log loss depends on how much probability the model puts on the true class. Naive Bayes often assigns near-1 confidence to wrong predictions, which log loss penalizes heavily. Calibration pulls those overconfident values toward the observed frequencies without changing most argmax choices, so log loss falls while accuracy stays about the same.