Foundations to Frontier
Tests
D. Classical Machine Learning › D0 Core Concepts (concept pages)

The Confusion Matrix and Threshold Selection

Most classifiers output a score or probability, and a decision needs a threshold. The confusion matrix shows what a given threshold does: how many cases of each true class end up in each predicted class. Moving the threshold trades false alarms against misses, so the right threshold depends on what each error costs, not on the default 0.5. This page covers binary and multiclass confusion matrices, threshold sweeps, criteria for choosing (maximum F1, Youden's J, a recall or precision constraint, minimum expected cost), and the Bayes-optimal rule for calibrated probabilities. In the exercises you implement the sweep and every criterion; then you compare threshold policies for a fault detector by their real expected cost when a missed fault costs 1 to 100 times as much as a false alarm.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Where to draw the line

A thermometer says 37.8 °C. Do you send the child home from school? If the line is 37.5, you catch more sick children but also send home some healthy ones. If the line is 38.5, fewer healthy children miss school but some sick ones stay. Where to draw the line depends on which mistake is worse. A classifier’s threshold is exactly this line.

Choosing a threshold from costs
optimum 1/(1+R) = 0.04800.250.50.751probability threshold
cost per 1 000 cases: at your threshold 688 · at 0.5 688 · at the optimum 309 · never alarm 1000
per 1 000: TP 16 · FN 34 · FP 6 · TN 944
With calibrated probabilities the best threshold depends only on the costs: alarm when p ≥ c_FP / (c_FP + c_FN). The default 0.5 is only optimal when both errors cost the same. When misses are expensive, accept many more false alarms.
Why engineers care

A missed engine fault may cost a mission. A false alarm costs an inspection. When the costs differ by a factor of 100, a detector left at the default threshold of 0.5 can cost several times more than necessary.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Lowering the threshold makes the classifier…
  2. 2. If missing a fault is very costly, the threshold should be…
  3. 3. The confusion matrix counts…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Reading the confusion matrix

Rows are true classes; columns are predictions; the diagonal holds correct decisions.

  • In the binary case the off-diagonal cells are false positives (false alarms) and false negatives (misses).
  • In the multiclass case each off-diagonal cell shows which classes get confused. Row-normalising gives recall per class; column-normalising gives precision per class.

Ways to choose a threshold:

Criterion Use when
0.5 on probabilities errors cost the same, probabilities calibrated
maximum F1 positives matter, no explicit costs
Youden’s J = TPR − FPR balanced sensitivity and specificity
fixed recall (e.g. ≥ 99%) or fixed precision safety or workload constraints
minimum expected cost costs known
c_FP / (c_FP + c_FN) on calibrated probabilities costs known, probabilities calibrated
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, precision_recall_curve
from sklearn.model_selection import TunedThresholdClassifierCV
model = TunedThresholdClassifierCV(base_model, scoring="f1", cv=5).fit(X, y)   # learns the threshold by CV
📝 Quick check (Level 1)
0/3 answered
  1. 1. In a confusion matrix, the diagonal holds…
  2. 2. Youden's J is…
  3. 3. A rule 'recall must be ≥ 99%' sets the threshold…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

The Bayes-optimal threshold

With a calibrated probability p = P(y = 1 | x):

  • predicting positive costs c_FP(1 − p) in expectation;
  • predicting negative costs c_FN·p.

Predict positive when c_FN·p ≥ c_FP(1 − p), that is when p ≥ c_FP / (c_FP + c_FN). With equal costs this gives 0.5; when a miss costs 99 times a false alarm, it gives 0.01. The threshold depends only on the costs, because the prevalence is already inside p.

If scores are not calibrated, choose the threshold empirically: sweep all distinct scores on a validation set and pick the one optimising the criterion. Tied scores must move together. The chosen threshold is noisy on small validation sets, so use cross-validation or a large hold-out.

🐍 Exercise 1: confusion matrices and threshold selection
Build multiclass confusion matrices and per-class precision, recall and F1; sweep thresholds over distinct scores; choose thresholds by maximum F1, Youden's J, minimum cost (including the option of never alerting) and best precision subject to a recall floor; implement the Bayes threshold for calibrated probabilities.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Bayes threshold when a miss costs 9 and a false alarm 1?
  2. 2. Why must tied scores move together in a sweep?
  3. 3. If probabilities are not calibrated, the threshold should be…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Thresholds in practice

  • Get costs from the domain: the price of an inspection against the expected cost of a missed failure, or analyst time per alert against the loss per missed fraud. A rough ratio is far better than none.
  • Operational constraints: a maximum number of alerts per day (choose the top k), or a minimum recall for safety cases.
  • Multiclass decisions: use a full cost matrix and predict the class with lowest expected cost Σ_y C(ŷ, y)·P(y | x).
  • Monitor after deployment: prevalence shifts change the optimal threshold when the model’s probabilities do not adapt; recalibrate (D0.10).
  • Abstention: add a “defer to a human” band between two thresholds when errors are costly and review is cheap.

Interview questions.

  • Your model outputs 0.3 for a case. Should it be flagged? It depends on the costs. With misses three times costlier than false alarms, the threshold is 0.25, so yes.
  • Why might maximising F1 be a poor choice? F1 ignores true negatives and real costs, and its optimal threshold depends on the prevalence.
📝 Quick check (Level 3)
0/3 answered
  1. 1. With a cost matrix C and probabilities, predict the class that…
  2. 2. Analysts can review 50 alerts a day. Thresholding strategy?
  3. 3. Prevalence doubles after deployment; uncalibrated threshold…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Threshold policies, priced

Exercise 1. On 10 scored cases (4 positives):

  • maximum F1 (0.857) and maximum Youden J (0.75) both occur at threshold 0.70;
  • with misses costing 10 false alarms, the minimum-cost threshold drops to 0.35 (total cost 2);
  • with false alarms costing 100 misses, it stays at 0.70 (cost 1);
  • requiring recall ≥ 0.75 gives precision 1.0 at 0.70.

Exercise 2: what each policy costs. Setup:

  • a fault detector with 5% faults and calibrated probabilities (Gaussian scores, separation 2);
  • a false alarm costs 1 and a missed fault costs R;
  • thresholds are chosen on a validation set of 5 000 cases (or 500) and costs measured on 20 000 test cases, averaged over 50 repetitions;
  • table values are cost per 1 000 cases.
Policy R = 1 R = 5 R = 20 R = 100
0.5 40 174 684 3 434
maximum F1 49 142 514 2 440
Youden’s J 155 187 311 990
Bayes c_FP/(c_FP + c_FN) 40 136 308 588
minimum cost on 500 validation cases 42 143 334 665
minimum cost on 5 000 validation cases 41 137 312 602
  • With calibrated probabilities, the one-line Bayes rule 1/(1 + R) is best at every cost ratio, with no validation data needed.
  • Leaving the threshold at 0.5 costs 5.8× more when misses cost 100.
  • Maximum F1 and Youden’s J ignore the costs and are each best only by coincidence (Youden happens to suit R = 20).
  • Tuning the cost directly on validation data is nearly optimal with 5 000 cases. With 500 cases (about 25 faults), the noisy threshold costs 13% more at R = 100.
🐍 Exercise 2 (research): what does each threshold policy cost?
Simulate a calibrated fault detector with 5% prevalence; for miss costs R = 1, 5, 20 and 100 compare thresholds set at 0.5, by maximum F1, by Youden's J, by the Bayes rule 1/(1 + R), and by minimising cost on validation sets of 500 or 5 000 cases; report the expected test cost per 1 000 cases.

Thresholds in AI, robotics and aerospace

  • Health monitoring: alarm thresholds are set from the cost of an unscheduled inspection against the risk of an in-flight failure.
  • Collision avoidance: very high recall is required; thresholds favour false alarms, and a human or second sensor confirms.
  • Perception: detection confidence thresholds trade missed obstacles against phantom braking.
  • Anomaly triage: top-k alerting matched to operator capacity.

References

  1. C. Elkan (2001). “The foundations of cost-sensitive learning.” IJCAI.
  2. W. J. Youden (1950). “Index for rating diagnostic tests.” Cancer 3(1).
  3. Z. C. Lipton, C. Elkan, B. Naryanaswamy (2014). “Optimal thresholding of classifiers to maximize F1 measure.” ECML PKDD.
  4. J. Hernández-Orallo, P. Flach, C. Ferri (2012). “A unified view of performance metrics: translating threshold choice into expected classification loss.” JMLR 13.
  5. scikit-learn developers. Tuning the decision threshold for class prediction (TunedThresholdClassifierCV), user guide.