Sub topic 14
Calibration with more than two classes
This chapter assumes you know binary calibration (reliability diagrams, Brier score, log loss, ECE), Platt scaling, isotonic regression, and softmax. It extends them to K classes.
What "calibrated" means with K classes
A multiclass model outputs a vector of K probabilities. There are three common definitions of calibration for it, from weakest to strongest:
| Definition | Requirement |
|---|---|
| Top-label (confidence) | Among predictions with top probability 0.7, the predicted class is right about 70% of the time. |
| Classwise | For every class k, the probability assigned to k matches how often k occurs. |
| Full | The whole vector matches the true conditional distribution of labels. |
Top-label calibration is the cheapest to measure and the most common. Classwise calibration matters when you use the probability of a specific class, such as "fraud" among five categories.
Measuring it
The top-label ECE bins the maximum probability and compares it with the accuracy in each bin.
import numpy as np
def top_label_ece(y_true, probs, n_bins=10):
y_true = np.asarray(y_true)
probs = np.asarray(probs)
conf = probs.max(axis=1)
correct = (probs.argmax(axis=1) == y_true).astype(float)
edges = np.linspace(0.0, 1.0, n_bins + 1)
bin_ids = np.digitize(conf, edges[1:-1], right=True)
ece = 0.0
for b in range(n_bins):
mask = bin_ids == b
if mask.any():
ece += mask.mean() * abs(correct[mask].mean() - conf[mask].mean())
return eceFor a proper scoring rule, log loss works unchanged. The multiclass Brier score is the mean over samples of the squared distance between the probability vector and the one-hot label.
Calibrating with CalibratedClassifierCV
For K > 2, scikit-learn calibrates one-vs-rest. It fits one calibrator per class, treating that class as positive. It then renormalizes the K calibrated values so they sum to 1.
import numpy as np
from sklearn.calibration import CalibratedClassifierCV
from sklearn.datasets import make_classification
from sklearn.metrics import log_loss
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
def top_label_ece(y_true, probs, n_bins=10):
conf = probs.max(axis=1)
correct = (probs.argmax(axis=1) == y_true).astype(float)
edges = np.linspace(0.0, 1.0, n_bins + 1)
bin_ids = np.digitize(conf, edges[1:-1], right=True)
ece = 0.0
for b in range(n_bins):
mask = bin_ids == b
if mask.any():
ece += mask.mean() * abs(correct[mask].mean() - conf[mask].mean())
return ece
X, y = make_classification(
n_samples=20000, n_features=20, n_informative=5, n_redundant=10,
n_classes=3, random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=0)
models = {"raw": GaussianNB().fit(X_train, y_train)}
for method in ("sigmoid", "isotonic"):
models[method] = CalibratedClassifierCV(GaussianNB(), method=method, cv=5).fit(X_train, y_train)
for name, model in models.items():
p = model.predict_proba(X_test)
print(f"{name:<9} ECE={top_label_ece(y_test, p):.3f} log loss={log_loss(y_test, p):.3f}")Temperature scaling and the argmax
Temperature scaling divides all K logits by one scalar T before the softmax. It has one parameter, so it rarely overfits, and it never changes which class has the highest score. Accuracy stays identical. It fixes top-label calibration well but cannot repair class-specific distortions.
One-vs-rest calibrators can change the argmax. Accuracy may shift slightly after calibration, so check it.
Common errors
- Reading a one-vs-rest reliability diagram for class 2 as if it covered the whole model.
- Evaluating ECE with many bins on a small test set. Mass concentrates in the top bin, and the other bins are noisy.
- Fitting isotonic regression per class on rare classes. A class with few positives gives a jagged, overfit step function. Prefer sigmoid or temperature scaling there.
Exercise
A three-class model has 90% accuracy and a top-label ECE of 0.01. A colleague wants to use its probability for the rarest class in a cost-sensitive decision. Why is the low ECE not enough, and what should you check?
Show answer
Top-label ECE only tests the maximum probability. The probability of a specific rare class can still be miscalibrated. Check classwise calibration: build a one-vs-rest reliability diagram for that class and compute its binary ECE or Brier score.