Part IV — Expert Production Engineering · Chapter 19 · Lesson 5 of 7 · 7 min read
Lesson 5: Multiclass Classification, Calibration, and Threshold Selection
Lesson level: Advanced
Purpose: Extend classification to more than two classes, make predicted probabilities trustworthy, and turn probabilities into decisions using explicit business costs.
Learning objectives
By the end of this lesson you will be able to:
- train multiclass classifiers with one-vs-rest and softmax approaches
- evaluate multiclass models with per-class metrics and macro and weighted averages
- read a multiclass confusion matrix
- assess calibration with reliability plots and calibration error
- recalibrate probabilities on held-out data
- choose decision thresholds by minimizing expected cost, including abstain-and-review bands
5.1 Multiclass classification
Many targets have more than two values: a support ticket routed to billing, technical, or account teams; a risk band of low, medium, or high. Two common approaches extend logistic regression:
- One-vs-rest: train one binary model per class ("billing versus everything else") and choose the class with the highest score. Simple and interpretable per class, but the scores are not naturally a probability distribution.
- Multinomial (softmax) regression: compute one linear score per class and convert them with the softmax function, pk = ezk / Σj ezj, so the probabilities are positive and sum to 1.
Prefer softmax when you need coherent probabilities across classes. If the classes are ordered (low < medium < high), consider whether a mistake of two bands is worse than a mistake of one, and reflect that in the evaluation.
5.2 Evaluating multiclass models
The confusion matrix becomes a k × k table: rows are actual classes, columns are predicted classes. Read it for systematic confusions — if many technical tickets are predicted as account tickets, the two classes may need better features or clearer labelling rules.
Precision, recall, and F1 are computed per class, treating each class as "positive" in turn. They are combined in two ways:
| Average | How | Emphasizes |
|---|---|---|
| Macro | Unweighted mean of per-class scores | Every class equally; exposes poor performance on small classes |
| Weighted | Mean weighted by class frequency | Overall volume; can hide failure on rare classes |
| Micro | Computed from pooled counts | Equivalent to accuracy for single-label problems |
Report the per-class table, the macro average, and the class counts. A weighted F1 of 0.88 with a macro F1 of 0.61 means at least one minority class is handled badly.
5.3 Calibration
A model is calibrated when its probabilities mean what they say: among all cases given a 30% probability, about 30% turn out positive. Ranking quality (AUC) and calibration are different properties. A model can rank perfectly yet be systematically overconfident, and probabilities are routinely miscalibrated after class weighting or resampling (Lesson 2).
Check calibration with a reliability plot: group predictions into bins (for example ten bins of predicted probability), then plot the mean predicted probability against the observed positive rate in each bin. Points on the diagonal indicate good calibration; points below it mean the model is overconfident in that range. Summarize with the expected calibration error: the bin-size-weighted average gap between predicted and observed rates. Always show bin counts, because sparse bins are noisy.
5.4 Recalibrating probabilities
If probabilities are miscalibrated, fit a small calibration model that maps raw scores to better probabilities, using data the main model was not trained on — a separate calibration split or cross-validated predictions:
- Platt scaling fits a logistic curve to the scores. It needs little data and suits mild, S-shaped miscalibration.
- Isotonic regression fits a flexible non-decreasing step function. It corrects more complex distortion but needs more data and can overfit small sets.
Illustrative listing.
from pealang.ml import CalibratedClassifier
from pealang.ml.metrics import reliability_table, brier
cal = CalibratedClassifier(pipe, method="platt", cv=5, seed=42)
cal.fit(X_train, y_train)
p_raw = pipe.predict_proba(X_test)
p_cal = cal.predict_proba(X_test)
print(brier(y_test, p_raw), brier(y_test, p_cal))
print(reliability_table(y_test, p_cal, bins=10))
Calibration changes probabilities, not ranking (for monotonic methods), so AUC stays essentially the same while log loss and Brier score improve.
5.5 Choosing a threshold from costs
A threshold turns a probability into an action. The right threshold depends on what each error costs. If acting on a case costs cFP when it was unnecessary and failing to act costs cFN when action was needed, then for calibrated probabilities it is worth acting whenever the expected cost of not acting exceeds the cost of acting, which gives the threshold:
threshold = cFP / (cFP + cFN)
Worked example. In the churn case of Lesson 3, a retention call that turns out unnecessary costs 20, and a missed churner costs 200. The cost-based threshold is 20 / 220 ≈ 0.09 — far below 0.5. Comparing three operating points on the same 1,000-customer test set:
| Operating point | TP | FN | FP | Expected cost (20 × FP + 200 × FN) |
|---|---|---|---|---|
| High threshold | 40 | 40 | 20 | 8,400 |
| Medium threshold (Lesson 3 example) | 56 | 24 | 64 | 6,080 |
| Low threshold | 70 | 10 | 180 | 5,600 |
The lowest threshold flags almost three times as many customers yet costs least, because missed churners are ten times as expensive as unnecessary calls. In practice, compute expected cost over a fine grid of thresholds on validation data (not the test set), choose the minimum, and check it against operational limits such as call-centre capacity.
5.6 Capacity limits and review bands
Costs are not the only constraint. If the team can make only 150 calls a week, the operating rule becomes "call the 150 highest-probability customers", and the useful metric is precision among the top 150. Ranking quality (Lesson 3) matters most in this setting.
For high-stakes decisions, use two thresholds and an abstain band: automatically approve below the lower threshold, automatically act above the upper threshold, and send the uncertain middle to a human reviewer. Size the band by reviewer capacity, monitor how often it is used, and record reviewer outcomes as new labelled data.
For multiclass problems, the simplest rule chooses the most probable class, but costs can differ by confusion. Routing a security ticket to billing is worse than the reverse. A cost matrix with one cost per actual-predicted pair, applied to the calibrated probabilities, picks the class with the lowest expected cost.
Common mistakes
- Using 0.5 by default: derive the threshold from costs or capacity.
- Choosing the threshold on the test set: tune it on validation data; the test set is for the final estimate.
- Cost thresholds with uncalibrated probabilities: calibrate first.
- Calibrating on training data: use held-out or cross-validated predictions.
- Reporting only weighted averages for multiclass: show per-class and macro scores.
- Ignoring capacity: a threshold that flags more cases than the team can handle will not be followed.
- Isotonic calibration on tiny data: prefer Platt scaling when data is limited.
Guided practice
- Compute softmax probabilities for scores 2.0, 1.0, and 0.1.
- Build a reliability table for a model trained with class weights, then recalibrate it and compare.
- Compute expected cost over thresholds from 0.02 to 0.6 in steps of 0.02 and plot the curve.
Hands-on lab: From scores to decisions
- Train a multinomial classifier that routes support tickets to three teams; report the confusion matrix, per-class precision and recall, and macro F1.
- For the binary churn model, draw a reliability plot and compute expected calibration error; recalibrate with Platt scaling and compare Brier scores.
- Using the costs supplied by your scenario, choose the cost-minimizing threshold on validation data and confirm it on the test set once.
- Add an abstain band sized for 50 reviews a week and report how many cases fall in each band.
- Write a decision policy document: thresholds, the reason for each, the expected cost, and the monitoring signals that would trigger a review.
Review questions
- How does softmax differ from one-vs-rest scoring?
- What do macro and weighted averages each emphasize?
- What does it mean for a model to be calibrated?
- How is a reliability plot constructed?
- When would you choose isotonic regression over Platt scaling?
- Derive the cost-based threshold from the costs of false positives and false negatives.
- Why might a capacity limit replace a probability threshold?
Applied challenge
An insurer screens claims for possible fraud. Investigating a claim costs 150; an undetected fraudulent claim costs on average 4,000; investigators can handle 300 claims a month out of 20,000. Design the full decision policy: calibration method, threshold or top-k rule, abstain band, and the monthly report the investigation manager will receive. Show the expected cost of your policy compared with investigating at random.
Lesson summary
Multiclass problems need per-class evaluation and macro averages that expose weak classes. Probabilities must be calibrated before they drive cost-based decisions; check with reliability plots and fix with Platt or isotonic calibration on held-out data. Choose thresholds from explicit costs and operational capacity, use abstain bands for uncertain high-stakes cases, and document the decision policy as part of the model.
Transition to Lesson 6
A model is now a chain of preprocessing, estimator, calibration, and decision policy. Lesson 6 packages that chain into a single pipeline that can be validated, saved, reloaded, and reproduced exactly.
Lesson status: Ready for review.