Sub topic 14
Calibration with more than two classes
This chapter assumes you know binary calibration from the earlier chapters: reliability diagrams, log loss, Brier score, ECE, Platt scaling, isotonic regression, and temperature scaling on held-out logits. It also assumes you know softmax and have used CalibratedClassifierCV. Here we extend those ideas to problems with K > 2 classes.
What "calibrated" means with K classes
With two classes there is one probability to check, because the other is 1 minus it. With K classes the model outputs a vector of K probabilities, and "calibrated" can mean several different things.
| Notion | Claim | Typical check |
|---|---|---|
| Top-label (confidence) calibration | Among predictions where the highest probability is about c, the predicted class is correct about c of the time. | Reliability diagram and ECE on the max probability |
| Class-wise calibration | For each class k, among samples where P(k) is about p, class k occurs about p of the time. | Binary reliability diagram and ECE per class, then averaged |
| Full-vector calibration | For any probability vector q the model outputs, the true class frequencies given that output match q. | Not directly measurable with realistic data |
Each notion is stronger than the one above it. Full-vector calibration implies the other two, but you cannot estimate it. There are too many possible vectors for any sample to cover.
In practice, top-label calibration is the most common target. It matches the question users ask: "the model says 92% sure, can I trust that?" Class-wise calibration matters when you use the probability of a specific class, for example a rare class that triggers an alert.
Measuring multiclass calibration
Log loss and the Brier score extend directly. Log loss is the mean of the negative log probability assigned to the true class. The multiclass Brier score is the mean squared distance between the probability vector and the one-hot label vector. Both are proper scoring rules. scikit-learn's brier_score_loss handles only binary targets, so compute the multiclass version yourself.
For ECE, you can bin the confidence only (top-label ECE) or evaluate each class column against the indicator y == k (class-wise ECE).
import numpy as np
def binary_ece(y_true, y_prob, n_bins=10):
edges = np.linspace(0.0, 1.0, n_bins + 1)
bin_ids = np.digitize(y_prob, 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(y_true[mask].mean() - y_prob[mask].mean())
return ece
def top_label_ece(y_true, proba, n_bins=10):
y_true = np.asarray(y_true)
confidence = proba.max(axis=1)
correct = (proba.argmax(axis=1) == y_true).astype(float)
return binary_ece(correct, confidence, n_bins)
def classwise_ece(y_true, proba, n_bins=10):
y_true = np.asarray(y_true)
scores = [
binary_ece((y_true == k).astype(float), proba[:, k], n_bins)
for k in range(proba.shape[1])
]
return float(np.mean(scores))
def multiclass_brier(y_true, proba):
onehot = np.eye(proba.shape[1])[np.asarray(y_true)]
return float(np.mean(np.sum((proba - onehot) ** 2, axis=1)))Top-label ECE reduces the problem to a binary one. The "label" is whether the prediction was correct, and the "probability" is the confidence. It ignores everything the model says about the other classes. A model can pass top-label calibration and still assign badly wrong probabilities to its second and third choices. Class-wise ECE catches that, but with many classes each column is dominated by near-zero probabilities, and most of the weight falls in the first bin.
Two ways to calibrate K classes
There are two families of post-hoc methods.
- Reduce to binary problems. Calibrate each class one-vs-rest, then renormalize so the probabilities sum to 1.
- Calibrate the whole vector. Fit a small parametric map from logits or log-probabilities to calibrated probabilities. Temperature scaling is the simplest case, with one parameter. Vector scaling uses one scale and one bias per class. Matrix scaling and Dirichlet calibration use a full linear map, which gives about K² parameters.
How CalibratedClassifierCV handles multiclass
When the target has more than two classes, CalibratedClassifierCV fits one binary calibrator per class. For class k the target is y == k and the input is the base model's score for class k. At prediction time it applies each calibrator and divides by the sum. If all calibrated values come out as zero for a row, which can happen with isotonic regression, the row falls back to a uniform distribution.
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
# Uses multiclass_brier, top_label_ece and classwise_ece defined above.
X, y = make_classification(
n_samples=20000,
n_features=20,
n_informative=6,
n_redundant=8,
n_classes=4,
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():
proba = model.predict_proba(X_test)
print(
f"{name:<9} log loss {log_loss(y_test, proba):.3f} "
f"Brier {multiclass_brier(y_test, proba):.3f} "
f"top-label ECE {top_label_ece(y_test, proba):.3f} "
f"class-wise ECE {classwise_ece(y_test, proba):.3f}"
)Run this and compare the four metrics across the three rows. Exact numbers depend on your scikit-learn version, but the raw naive Bayes model is usually overconfident. Both calibrated versions should reduce log loss and ECE.
Consequences of one-vs-rest plus renormalization
- The predicted class can change. Each class has its own calibrator, and each calibrator is monotone in its own score. Applying different monotone maps to different columns can reorder them. Accuracy may therefore move slightly after calibration. This differs from temperature scaling, which divides all logits by the same T and never changes the argmax.
- Each calibrator sees an imbalanced problem. With 20 classes, each binary target is about 95% negative. Isotonic regression gets few positive examples per class, so it overfits more easily than in the binary case. Prefer sigmoid for small or many-class datasets.
- Renormalization breaks per-class calibration slightly. Each column was calibrated before the division, and dividing by a row sum different from 1 shifts it. The effect is usually small, and the score metrics will show whether it matters.
Temperature scaling for K classes
If your model produces logits, as neural networks do, temperature scaling is the standard first choice. Fit a single T on held-out logits as in the previous chapter and compute softmax(logits / T).
It has one parameter, so it needs little data and rarely overfits. It preserves the argmax, so accuracy and AUC-style ranking within a row are untouched. The cost is its limited expressiveness. It can fix a uniform overconfidence, but it cannot fix a model that is overconfident on class A and underconfident on class B. Vector scaling and Dirichlet calibration can, at the cost of more parameters and more risk of overfitting. They are worth trying only when class-wise ECE stays high after temperature scaling and you have enough held-out data per class.
Choosing a method
Use these rules as a starting point, and let a held-out comparison decide.
- The model outputs logits (neural network) and you have a few thousand validation examples: temperature scaling.
- The model has no logits, such as a random forest, naive Bayes, or boosted trees:
CalibratedClassifierCVwithsigmoid. - Many samples per class (roughly thousands each) and the reliability curve is clearly non-sigmoid:
isotonic. - Many classes and few samples: temperature scaling or sigmoid only. Isotonic regression will overfit its flat steps.
Always compare against the uncalibrated model on log loss, multiclass Brier score, and both ECE variants. A method that lowers ECE but raises log loss deserves suspicion.
Pitfalls
- Reporting only top-label ECE and concluding the full probability vector is trustworthy.
- Checking accuracy after calibration and expecting it to be unchanged. This holds for temperature scaling but not for one-vs-rest calibration.
- Using equal-width bins when most confidences sit near 1. With a strong model, nearly every sample lands in the top bin. Quantile bins give a more informative curve.
- Computing class-wise ECE on rare classes with very few positives. The per-bin estimates are noisy, so look at the counts before reading the numbers.
Exercise
A 10-class image classifier produces logits. After you apply temperature scaling (T = 1.8) on a validation set, top-label ECE drops from 0.09 to 0.02, but class-wise ECE for two rare classes stays high. Does the argmax change after scaling? Name one next step and one risk of that step.
Show answer
The argmax does not change, because dividing all logits in a row by the same positive T preserves their order, so accuracy is identical. A next step is vector scaling (a per-class scale and bias) or Dirichlet calibration, which can correct classes differently. The risk is overfitting. These maps have many more parameters, and the rare classes have few validation examples, so you must check the result on a separate test split.