2.6.6Model Evaluation & Selection

Confusion matrix interpretation

2,598 words12 min readdifficulty · medium2 backlinks

Think of it like a medical test result breakdown: not just "90% accurate," but "90% of sick people correctly identified (sensitivity), 95% of healthy people correctly identified (specificity), 10% false alarms, 5% missed cases." The matrix forces you to see the asymetry in errors—missing a cancer case is not the same as a false alarm.

What It Is

Predicted PosPredicted NegActual PosTPFNActual NegFPTN\begin{array}{c|cc} & \text{Predicted Pos} & \text{Predicted Neg} \\ \hline \text{Actual Pos} & \text{TP} & \text{FN} \\ \text{Actual Neg} & \text{FP} & \text{TN} \end{array}
  • True Positive (TP): Correctly predicted positive
  • False Negative (FN): Missed positive (Type II error)
  • False Positive (FP): False alarm (Type I error)
  • True Negative (TN): Correctly predicted negative

WHY this structure? Rows = reality, columns = predictions. Entry (i,j)(i, j) = "true class ii, predicted as class jj." Perfect classifier → diagonal matrix (all off-diagonal = 0).

Deriving Core Metrics from First Principles

Every metric is a ratio of cell counts, designed to answer a specific question.

Accuracy

WHY? "What fraction of all predictions were correct?" Sum diagonal (correct) over total.

WHEN IT FAILS: Imbalanced classes. If 95% of emails are not spam, predicting "not spam" for everything gives 95% accuracy but misses all spam. Accuracy is blind to class importance.

Precision (Positive Predictive Value)

DERIVATION: You predicted positive (TP+FP)(\text{TP} + \text{FP}) times. How many were actually positive? TPTP+FP\frac{\text{TP}}{\text{TP} + \text{FP}}.

ANSWERS: "When I say 'positive,' how often am I right?" Measures trustworthiness of positive predictions.

WHY THIS MATTERS: Spam filter—if precision is low, many legitimate emails are marked spam (user frustration). Medical screening—low precision means many healthy people subjected to invasive follow-up tests.

Recall (Sensitivity, True Positive Rate)

DERIVATION: There are (TP+FN)(\text{TP} + \text{FN}) actual positives. How many did you catch? TPTP+FN\frac{\text{TP}}{\text{TP} + \text{FN}}.

ANSWERS: "Of all positives, how many did I find?" Measures completeness of detection.

WHY THIS MATTERS: Fraud detection—high recall means few frauds slip through. Cancer screening—high recall means few cases missed (critical for life-threatening conditions).

Specificity (True Negative Rate)

DERIVATION: There are (TN+FP)(\text{TN} + \text{FP}) actual negatives. How many did you correctly identify? TNTN+FP\frac{\text{TN}}{\text{TN} + \text{FP}}.

ANSWERS: "Of all negatives, how many did I correctly reject?" Measures ability to avoid false alarms.

COMPLEMENTS RECALL: High recall but low specificity = "crying wolf" (you catch everything but flag tons of false positives).

F1-Score

WHY HARMONIC MEAN? Arithmetic mean P+R2\frac{P + R}{2} is too forgiving. If P=100%,R=10%P = 100\%, R = 10\%, arithmetic mean = 55% (misleading). Harmonic mean = 18% (penalizes imbalance).

DERIVATION OF SECOND FORM: F1=21P+1R=2TP+FPTP+TP+FNTP=2TPTP+FP+TP+FN=2TP2TP+FP+FNF_1 = \frac{2}{\frac{1}{P} + \frac{1}{R}} = \frac{2}{\frac{\text{TP} + \text{FP}}{\text{TP}} + \frac{\text{TP} + \text{FN}}{\text{TP}}} = \frac{2\text{TP}}{\text{TP} + \text{FP} + \text{TP} + \text{FN}} = \frac{2\text{TP}}{2\text{TP} + \text{FP} + \text{FN}}

WHY THIS STEP? Harmonic mean definition: 21a+1b\frac{2}{\frac{1}{a} + \frac{1}{b}}. Substitute precision and recall, simplify denominators, multiply through byTP.

Multi-Class Confusion Matrix

For CC classes, the matrix is C×CC \times C. Entry M[i,j]M[i, j] = number of times true class ii was predicted as class jj.

Pred CatPred DogPred BirdTrue Cat85105True Dog8902True Bird3592\begin{array}{c|cc} & \text{Pred Cat} & \text{Pred Dog} & \text{Pred Bird} \\ \hline \text{True Cat} & 85 & 10 & 5 \\ \text{True Dog} & 8 & 90 & 2 \\ \text{True Bird} & 3 & 5 & 92 \end{array}

Reading this:

  • Diagonal (85, 90, 92) = correct predictions
  • Off-diagonal = confusion patterns
  • Row 1 (cat): 10 cats confused as dogs, 5 as birds
  • Column 1: 8 dogs, 3 birds misclassified as cats

PER-CLASS METRICS: For class "Cat" (i=1i = 1):

  • TPcat=85TP_{\text{cat}} = 85 (diagonal)
  • FNcat=10+5=15FN_{\text{cat}} = 10 + 5 = 15 (row 1, off-diagonal)
  • FPcat=8+3=11FP_{\text{cat}} = 8 + 3 = 11 (column 1, off-diagonal)
  • TNcat=(90+2+5+92)=189TN_{\text{cat}} = (90 + 2+ 5 + 92) = 189 (all entries not in row/column 1)

Precisioncat=8585+11=8596=0.885\text{Precision}_{\text{cat}} = \frac{85}{85 + 11} = \frac{85}{96} = 0.885 Recallcat=8585+15=85100=0.85\text{Recall}_{\text{cat}} = \frac{85}{85 + 15} = \frac{85}{100} = 0.85

WHY THIS STEP? For class ii, TPTP is diagonal entry, FNFN is row sum minus diagonal, FPFP is column sum minus diagonal, TNTN is everything else.

MACRO vs MICRO AVERAGING:

  • Macro: Compute metric per class, then average (treats classes equally)
  • Micro: Sum all TP, FP, FN across classes, compute once (weights by class size)

Worked Example: Medical Diagnosis

Model predictions:

  • 80 sick correctly identified (TP)
  • 20 sick missed (FN)
  • 50 healthy flaged as sick (FP)
  • 850 healthy correctly cleared (TN)

Confusion matrix:

Pred SickPred HealthyActually Sick8020Actually Healthy50850\begin{array}{c|cc} & \text{Pred Sick} & \text{Pred Healthy} \\ \hline \text{Actually Sick} & 80 & 20 \\ \text{Actually Healthy} & 50 & 850 \end{array}

Metrics:

Accuracy=80+8501000=0.93 (93%)\text{Accuracy} = \frac{80 + 850}{1000} = 0.93 \text{ (93\%)}

WHY THIS STEP? Sum diagonal (correct), divide by total. Looks great, but…

Precision=8080+50=80130=0.615 (61.5%)\text{Precision} = \frac{80}{80 + 50} = \frac{80}{130} = 0.615 \text{ (61.5\%)}

WHY THIS STEP? Of 130 "sick" predictions, only 80 were right. 61.5% trustworthiness—if you test positive, only ~62% chance you're actually sick.

Recall (Sensitivity)=8080+20=80100=0.80 (80%)\text{Recall (Sensitivity)} = \frac{80}{80 + 20} = \frac{80}{100} = 0.80 \text{ (80\%)}

WHY THIS STEP? Of 100 actual sick, caught 80. Missed 20% of cases—20 sick people sent home!

Specificity=850850+50=850900=0.944 (94.4%)\text{Specificity} = \frac{850}{850 + 50} = \frac{850}{900} = 0.944 \text{ (94.4\%)}

WHY THIS STEP? Of 900 healthy, correctly cleared 850. 5.6% false alarm rate.

TRADEOFF: High specificity (few false alarms), but moderate recall (mises 20% of sick). In medicine, you'd likely lower the threshold to catch more sick (boost recall), accepting more false alarms (lower precision/specificity).

Common Mistakes

Why it feels right: 95% correct sounds great.

The trap: Accuracy is class-blind. With 100 samples, 95 negative, 5 positive—predicting "all negative" = 95% accuracy, but 0% recall (missed every positive).

Example: Fraud detection with 1% fraud rate. "No fraud" everywhere = 99% accuracy, but useless (catches zero fraud).

FIX: Always check precision/recall/F1, especially with imbalanced data. Accuracy alone is meaningful only when classes are balanced.


Why it feels right: Both useTP, both are percentages, easy to mix up.

The trap:

  • Precision = "Of my positive predictions, how many were right?" (column view)
  • Recall = "Of actual positives, how many did I find?" (row view)

Mnemonic: Precision = **redicted positives (denominator). Recall = Real positives (denominator).

Example: Search engine—high precision = top results are relevant (few junk). High recall = most relevant docs found (few missed). You want both.

FIX: Anchor to the denominator. Precision = TPpredicted pos\frac{\text{TP}}{\text{predicted pos}}, Recall = TPactual pos\frac{\text{TP}}{\text{actual pos}}.


Why it feels right: Summary metrics (F1, accuracy) are easier to report.

The trap: You lose where the model fails. Maybe it confuses "cat" with "dog" but never with "bird"—this pattern is invisible a single F1 score.

Example: Multi-class classifier with F1 = 0.85. Confusion matrix reveals: never confuses A↔B, but always confuses C↔D. You'd focus retraining on C/D discrimination, but F1 alone wouldn't tell you.

FIX: Always visualize the matrix for multi-class. Look for systematic confusions (similar classes, data leakage patterns).

The Precision-Recall Tradeoff

WHY? Lower threshold = predict positive more liberally. You'll catch more true positives (↑ recall), but also flag more negatives as positive (↓ precision).

The curve: Plot precision vs recall at all thresholds Precision-Recall curve. Area under curve (AUC-PR) = single-number summary of model quality across thresholds.

Feynman Explanation

Recall

Imagine you're a lifeguard looking for drowning swimmers. The confusion matrix is your report card.

  • True Positive (TP): You saw someone drowning and saved them. ✓
  • False Negative (FN): Someone was drowning, but you missed them. ✗ (worst error—someone died)
  • False Positive (FP): You jumped in to "save" someone who was just swimming. ✗ (embarrassing, wastes time)
  • True Negative (TN): Person swimming safely, you left them alone. ✓

Accuracy = "What % of the time was I right?" (TP + TN) / total. But if only1 in 100 swimmers is drowning, you could just sit there, do nothing, and be 99% "accurate" while everyone drowns. Useless.

Recall = "Of people who were actually drowning, how many did I save?" If recall is 70%, you missed 30% of drowning people. That's bad.

Precision = "When I jumped in to save someone, how often were they actually drowning?" If precision is 50%, half your rescues were false alarms (you're wasting energy on safe swimmers).

The tradeoff: If you're paranoid and jump in every time someone splashes (low threshold), you'll save everyone (high recall) but annoy lots of safe swimmers (low precision). If you're cautious and only jump for obvious drowning (high threshold), fewer false alarms (high precision) but you miss subtle cases (low recall).

The confusion matrix shows you exactly how many of each type of mistake you made. Then you decide: in lifeguarding, missing a drowning person is worse than a false alarm, so you'd optimize for high recall (lower threshold), even if precision drops.

Mnemonic

Confusion matrix corners (clockwise from top-left): "TP, FP, TN, FN""True, False, True, False" + "Positive, Positive, Negative, Negative"

Or: "Two Pints, Two Notes" (TP, FP, TN, FN) if you like beer and music.

Connections

  • Precision and Recall – detailed derivations, F-beta score
  • ROC Curve and AUC – alternative evaluation for threshold-based models
  • Class Imbalance Handling – why accuracy fails, how to rebalance
  • Multi-class Classification Metrics – macro/micro averaging, per-class analysis
  • Cost-Sensitive Learning – assigning different costs to FP vs FN
  • Model Selection Criteria – how to choose between models with different confusion matrices
  • Binary Classification Thresholds – moving the threshold to optimize for business goals

#flashcards/ai-ml

What are the four cells of a binary confusion matrix? :: True Positive (TP), False Negative (FN), False Positive (FP), True Negative (TN)

How is accuracy computed from a confusion matrix?
(TP + TN) / (TP + TN + FP + FN) — fraction of correct predictions
Why does high accuracy fail with imbalanced classes?
A trivial "always predict majority class" model achieves high accuracy but zero recall for minority class
What does precision measure?
Trustworthiness of positive predictions: TP / (TP + FP) — "when I say positive, how often am I right?"
What does recall measure?
Completeness of positive detection: TP / (TP + FN) — "of all actual positives, how many did I find?"
Why use F1-score instead of arithmetic mean of precision and recall?
Harmonic mean penalizes imbalance; if P=100% and R=10%, arithmetic mean=55% (misleading), F1=18% (realistic)
What is specificity?
True negative rate: TN / (TN + FP) — fraction of actual negatives correctly identified
How do you extract per-class TP, FP, FN, TN from a multi-class confusion matrix?
TP = diagonal entry; FN = row sum - diagonal; FP = column sum - diagonal; TN = all other entries
What is the precision-recall tradeoff?
Lowering decision threshold increases recall (more positives caught) but decreases precision (more false alarms)
Why visualize the confusion matrix for multi-class problems?
Summary metrics hide where the model fails; matrix reveals systematic confusion patterns between specific class pairs
What is macro-averaging for multi-class metrics?
Compute metric per class, then average — treats all classes equally regardless of size
What is micro-averaging for multi-class metrics?
Sum all TP, FP, FN across classes, compute metric once — weights by class frequency
When should you optimize for high recall?
When false negatives are costly (missing cancer, fraud, drowning) — accept more false positives to catch all positives
When should you optimize for high precision?
When false positives are costly (spam filtering legitimate emails, invasive follow-up tests) — accept missing some positives to avoid false alarms

Concept Map

rows equal

columns equal

contains

diagonal correct

TP over TP plus FP

TP over TP plus FN

fails on

measures

measures

Type II error

Type I error

combined into

combined into

Confusion Matrix

Actual Class

Predicted Class

TP FP FN TN

Accuracy

Precision

Recall

Imbalanced Classes

Trustworthiness

Completeness

False Negative

False Positive

F1 Score

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Confusion matrix basically ek truth table hai jo dikhata hai ki apka classification model kahan sahi predictions kar raha hai aur kahan galat. Ek single accuracy number se kuch pata nahi chalta—95% accurate sunke lagta hai model perfect hai, lekin ho sakta hai ki wo sirf majority class predict kar raha ho aur minority class (jaise fraud, disease) ko completely miss kar raha ho. Matrix mein four cells hote hain: True Positive (sahi positives pakde), False Negative (positive cases miss kar diye, Type II error), False Positive (galat alarm bajaya, Type I error), aur True Negative (sahi negatives identify kiye).

Is matrix se hum precision aur recall nikalte hain. Precision bata hai ki jab model "positive" bolta hai, to kitni baar sahi hota hai—yani trustworthiness. Recall batata hai ki total actual positives mein se kitne pakad paye—yani completeness. Dono ka balance zaroori hai. Medical diagnosis mein agar recall low hai to bimar log chhut jayenge (dangerous), agar precision low hai to healthy log unnecessarily test karwayenge (costly aur stressful). F1-score inka harmonic mean hai jo imbalance ko penalize karta hai. Multi-class problems mein matrix dikhata hai ki model exactly kaunse classes ko confuse kar raha hai—jaise cat ko dog samajh raha hai ya bird ko. Ye detailed insight se tum model ko targeted tarike se improve kar sakte ho, instead of blindly tuning hyperparameters.

Go deeper — visual, from zero

Test yourself — Model Evaluation & Selection

Connections