Module 2 — Evaluating Classifiers and Tuning Parameters

Sources: Lec 5 — Evaluation Criteria for Data Classification; Lec 6 — Parameter Tuning (Cross-Validation). · Prev: Module 1 · Next: Module 3 — Bayes · Index: 00_INDEX_and_Coverage


C11. The Confusion Matrix, Accuracy, Precision, Recall, F-measure

Intuition

A classifier can be wrong in two different ways: crying wolf (false alarm) and missing the wolf (miss). The confusion matrix counts all four outcomes.

  • Accuracy lumps everything together.
  • Precision: “when I say positive, am I right?”
  • Recall: “of all real positives, how many did I find?”
  • F-measure combines the two.

Formal definition

Predicted +Predicted −
Actual +TPFN
Actual −FPTN

Memory aid

Precision looks down the predicted-positive column (TP + FP). Recall looks along the actual-positive row (TP + FN). TN appears in neither.

Mathematical properties

  • is the harmonic mean of precision and recall : .
  • ; iff ; if or .
  • Equivalent count form: .
  • .

Derivation of the count form

, . Then

Key insights

  • TN does not appear in precision, recall, or — they ignore the (often huge) negative class.
  • Closer and ⇒ higher for a given sum.
  • Convention: if precision is taken as (undefined ).

Worked examples

Example 1 — Very Easy · A spam filter’s accuracy

  • Problem: A spam filter handles 100 emails: spam caught, good mails wrongly flagged, spam missed, good mails delivered. Compute accuracy.
  • Asked: Accuracy.
  • Concept: Accuracy formula.
  • Approach: Correct / total.
  • Solution: Correct ; total .
  • Final answer: .

Key lesson

Accuracy uses the diagonal of the confusion matrix.

Example 2 — Easy · Precision and recall of the same filter

  • Problem: Same matrix. Compute precision and recall.
  • Asked: .
  • Concept: Definitions.
  • Approach: Row / column totals of the positive class.
  • Solution: (of 50 flagged, 40 really spam). (of 60 spam, 40 caught).
  • Final answer: , .

Key lesson

Precision divides by the predicted-positive column; recall by the actual-positive row.

Example 3 — Moderate · F two ways

  • Problem: Same matrix. Compute two ways and verify .
  • Asked: .
  • Concept: Harmonic mean.
  • Approach: Formula and count form.
  • Solution: . Count form: ✓. Bounds: ✓.
  • Final answer: .

Key lesson

The harmonic mean sits below the arithmetic mean, pulled toward the smaller value.

Example 4 — Hard · The accuracy paradox (fraud detection)

  • Problem: Out of 1000 transactions, 20 are fraud. Classifier A predicts “not fraud” for everything. Classifier B has . Compare accuracy, , , .
  • Asked: Which is better.
  • Concept: Accuracy paradox.
  • Approach: Fill matrices.
  • Solution: A: . Accuracy . ; by convention; . B: accuracy ; ; ; .
  • Final answer: A has higher accuracy (0.98 vs 0.965) but is useless (F = 0); B is far better (F = 0.46).
Accuracy
A (always “legit”)0.980000
B0.9650.3330.7500.462

Key lesson

On imbalanced data, accuracy hides total failure on the rare class.

Example 5 — Very Hard · Where to cut a ranked list

  • Problem: A search engine ranks ten pages by score (highest first). Their true relevance is P,P,N,P,N,N,P,N,N,N (4 relevant). Predicting “relevant” for the top pages, compute for each and choose the best .
  • Asked: .
  • Concept: ; threshold selection.
  • Approach: Track cumulatively; .
  • Solution:
TPFPFN
11030.400
22020.667
32120.571
43110.750
53210.667
63310.600
74300.727
84400.667
94500.615
104600.571
  • Final answer: Best , (not where recall is 1).

Key lesson

is not monotone in the threshold; the best balances precision and recall.

Common mistakes

  • Mixing the roles of FP and FN in precision / recall.
  • Quoting accuracy alone on imbalanced data.

Exam traps

  • “Precision = TP/(TP+FN)” is wrong — that is recall.
  • is when .

Connections: Sensitivity / specificity and averaging (C12), clustering F-measure (C41), cross-validation scoring (C13).

Mastery checklist

  • Draw the confusion matrix and fill it.
  • Compute and the count form.
  • Explain the accuracy paradox.

C12. Macro/Micro Averaging, Sensitivity & Specificity, Class Imbalance

Intuition

With classes there is one per class (treat class as “positive”, the rest “negative”). Two ways to summarise:

  • Macro — average the per-class scores: every class counts equally, so rare classes matter.
  • Micro — pool the counts, then compute: every data point counts equally, so big classes dominate.

Formal definitions

Mathematical result (derived)

In single-label multiclass classification, every misclassified item is a false positive for exactly one class and a false negative for exactly one class, so . Hence .

Derivation

Let = count with actual , predicted . , . , and is the same off-diagonal sum. ∎

Key insights

  • Macro: “per-class average”, insensitive to class frequency. Micro: “per-data-point average”.
  • Sensitivity and specificity are the standard medical pair: how many sick patients are found, how many healthy ones are cleared.

Worked examples

Example 1 — Very Easy · A disease screening test

  • Problem: A test on 1000 people: . Sensitivity and specificity?
  • Asked: Both.
  • Concept: Definitions.
  • Approach: Direct.
  • Solution: Sensitivity (3 of 4 sick people found). Specificity .
  • Final answer: and .

Key lesson

High specificity can coexist with mediocre sensitivity.

Example 2 — Easy · Per-class counts for support tickets

  • Problem: A model sorts support tickets into A = billing, B = technical, C = legal. Confusion matrix (rows actual, columns predicted): . Compute and per-class precision / recall.
  • Asked: Per-class counts and scores.
  • Concept: One-vs-rest counts.
  • Approach: Diagonal; column sums minus diagonal; row sums minus diagonal.
  • Solution: Row totals: . Column totals: . . . .
classTPFPFNprecisionrecall
A billing509100.84750.8333
B technical22780.75860.7333
C legal4860.33330.4000
  • Final answer: As in the table.

Key lesson

Class C (rare, 10 tickets) is much worse than A — the overall number hides it.

Example 3 — Moderate · Macro vs micro

  • Problem: For the matrix of Example 2 compute macro and micro precision and recall.
  • Asked: Four numbers.
  • Concept: Averaging.
  • Approach: Macro: mean of per-class; micro: pooled.
  • Solution: Macro . Macro . Micro: , , → .
  • Final answer: Macro ; micro .

Key lesson

Macro is lower because the weak rare class gets a full third of the weight.

Example 4 — Hard · A defect detector that never says “defect”

  • Problem: A factory line has 980 “good” and 20 “defective” items; the detector labels everything good. Compute accuracy, micro , macro , and the sensitivity and specificity of the defective class.
  • Asked: Five numbers.
  • Concept: Which metric exposes imbalance.
  • Approach: Per-class recalls.
  • Solution: Good: → . Defective: → . Accuracy . Micro . Macro . Sensitivity (defective) ; specificity (defective) .
  • Final answer: Accuracy , micro , macro , sensitivity , specificity .

Key lesson

Macro averaging (and sensitivity) reveal failure on the rare class; accuracy and micro do not.

Example 5 — Very Hard · Improving only the rare class

  • Problem: Starting from the matrix of Example 2, an improved model re-labels 3 class-C tickets that were predicted A as predicted C: the C row becomes (rows A, B unchanged). Recompute micro and macro recall and precision, and compare the improvement.
  • Asked: New metrics and change.
  • Concept: Sensitivity of macro vs micro to a rare class.
  • Approach: Recount.
  • Solution: New matrix . Column totals: . , , . Precision: → macro . Recall: → macro . Micro: → .
beforeafterchange
micro 0.760.79+0.03
macro 0.6460.706+0.060
macro 0.6560.756+0.100
  • Final answer: Micro (+3 pts); macro (+6 pts), macro (+10 pts).

Key lesson

Improving one small class barely moves micro scores but visibly moves macro scores.

Common mistakes

  • Averaging per-class accuracies and calling it macro precision.
  • Expecting micro micro in single-label problems.

Exam traps

  • Sensitivity ≡ recall ≡ TPR; specificity is not precision.
  • Micro = per-data-point average; macro = per-class average.

Connections: C11, class imbalance, cross-validation (C13), clustering evaluation (C41).

Mastery checklist

  • Extract from a multiclass matrix.
  • Compute macro vs micro.
  • Prove micro = micro = accuracy.

C13. Cross-Validation: Leave-One-Out and -Fold

Intuition

Evaluating on training data flatters the model; setting aside one test set wastes data and gives a lucky-or-unlucky estimate. Cross-validation (CV) rotates the roles: every point is a test point exactly once, while the model is never trained on the point it is tested on. CV is also how hyper-parameters (like in kNN, in SVM, tree depth) are chosen.

 3-fold CV on 9 points            round 1: [ TEST ][ train ][ train ]
 ┌─────┬─────┬─────┐              round 2: [ train ][ TEST ][ train ]
 │ Z1  │ Z2  │ Z3  │              round 3: [ train ][ train ][ TEST ]
 └─────┴─────┴─────┘              → pool the 9 predictions, then score once

Formal definition

Data , labels .

  • Leave-One-Out (LOO): for : train on , predict for . Score using vs (e.g. -measure).
  • -fold CV: partition into with (i) , (ii) , (iii) , (iv) sizes (nearly) equal. For : train on , predict . Score on the pooled predictions.

Mathematical formulation

  • Number of trainings: LOO ; -fold . ⇒ -fold = LOO.
  • Each training set has samples.
  • LOO is deterministic (exhaustive); -fold with random folds varies between runs. Repeating (e.g. 50 times) and averaging makes the estimate independent of the particular partition.

Key insights

  • Bias–variance of the estimate: LOO training sets are nearly the full data (low bias) but cost trainings; -fold is cheaper.
  • The folds must be disjoint and cover everything.

Worked examples

Example 1 — Very Easy · Fold sizes

  • Problem: points, 3-fold CV. Possible fold sizes? How many models are trained?
  • Asked: Sizes and count.
  • Concept: Near-equal folds.
  • Approach: .
  • Solution: Sizes (any order). One model per fold → 3 models.
  • Final answer: ; 3 models.

Key lesson

Folds differ in size by at most one element.

Example 2 — Easy · Cost of LOO

  • Problem: . For 5-fold CV and for LOO give training-set size and number of trainings.
  • Asked: Four numbers.
  • Concept: Counts.
  • Approach: Formulas.
  • Solution: 5-fold: test , train , 5 trainings. LOO: train , 100 trainings.
  • Final answer: and .

Key lesson

LOO is times more expensive than -fold.

Example 3 — Moderate · Cats and dogs by weight, LOO with 1-NN

  • Problem: Animals weighed in kg: with labels cat, cat, cat, dog, dog. Run LOO with 1-NN and report accuracy. (If two neighbours tie, both are cats.)
  • Asked: LOO accuracy of 1-NN.
  • Concept: LOO procedure.
  • Approach: Remove each point, classify by nearest remaining.
  • Solution: : nearest is 2 (cat) ✓. : neighbours 1 and 3 equidistant, both cats ✓. : nearest 2 (cat) ✓. : nearest 11 (dog) ✓. : nearest 10 (dog) ✓. 5 / 5.
  • Final answer: .

Key lesson

Well-separated clusters give perfect LOO accuracy for 1-NN.

Example 4 — Hard · Choosing by LOO

  • Problem: Same data. Use LOO to choose between and nearest neighbours (majority vote).
  • Asked: Best .
  • Concept: Parameter tuning by CV.
  • Approach: Compute LOO accuracy for .
  • Solution: : nearest others 2, 3, 10 → cat, cat, dog → cat ✓. : 1, 3, 10 → cat ✓. : 2, 1, 10 → cat ✓. : 11, 3, 2 → dog, cat, cat → cat ✗. : 10, 3, 2 → dog, cat, cat → cat ✗. Accuracy . gave .
  • Final answer: (LOO accuracy 1.0 vs 0.6).

Key lesson

A larger than the size of the smaller class (2 dogs) forces errors. Tune by CV.

Example 5 — Very Hard · Average of folds vs pooled predictions

  • Problem: A 2-fold CV gives fold 1: ; fold 2: . Compute (a) per fold then averaged; (b) on the pooled predictions as the lecture prescribes (“using the actual labels of ”). Explain the difference.
  • Asked: Two scores.
  • Concept: Pooling vs averaging.
  • Approach: .
  • Solution: (a) ; ; mean . (b) Pooled: → .
  • Final answer: Average-of-folds ; pooled .

Key lesson

is nonlinear in the counts: fold-averaging weights every fold equally, pooling weights every data point equally. Be explicit about which you use.

Common mistakes

  • Tuning on the test fold (data leakage) and reporting that score.
  • Overlapping folds.
  • Random folds with tiny classes (use stratified folds).

Exam traps

  • LOO is exhaustive and deterministic; -fold with a random partition is not.
  • ⇒ LOO.

Connections: Pruning (C8), in kNN (C23), in SVM (C32), parameters.

Mastery checklist

  • Write both algorithms.
  • State the folds’ four properties.
  • Use CV to pick a hyper-parameter.