yt, yp = expand([[40, 20], [10, 30]]) # rows = actual (spam, ham), cols = predictedyt = [1 - t for t in yt]; yp = [1 - p for p in yp] # make "spam" the positive class (1)print(precision_score(yt, yp), recall_score(yt, yp), f1_score(yt, yp)) # 0.8 0.6667 0.7273
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 TP=15,FN=5,FP=30,TN=950. Compare accuracy, P, R, F.
Final answer: A has higher accuracy (0.98 vs 0.965) but is useless (F = 0); B is far better (F = 0.46).
Accuracy
P
R
F
A (always “legit”)
0.980
0
0
0
B
0.965
0.333
0.750
0.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 k pages, compute F for each k and choose the best k.
Asked:argmaxkF(k).
Concept:F=2TP+FP+FN2TP; threshold selection.
Approach: Track TP,FP cumulatively; FN=4−TP.
Solution:
k
TP
FP
FN
F
1
1
0
3
0.400
2
2
0
2
0.667
3
2
1
2
0.571
4
3
1
1
0.750
5
3
2
1
0.667
6
3
3
1
0.600
7
4
3
0
0.727
8
4
4
0
0.667
9
4
5
0
0.615
10
4
6
0
0.571
Final answer: Best k=4, F=0.75 (not k=7 where recall is 1).
Python check
labels = np.array([1, 1, 0, 1, 0, 0, 1, 0, 0, 0])for k in range(1, 11): print(k, round(f1_score(labels, [1] * k + [0] * (10 - k)), 3)) # peaks at k = 4 (0.75)
Key lesson
F is not monotone in the threshold; the best F 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.
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 ∑iFPi=∑iFNi. Hence Pmicro=Rmicro=N∑iTPi=accuracy.
Derivation
Let Mab = count with actual a, predicted b. FPb=∑a=bMab, FNa=∑b=aMab. ∑bFPb=∑b∑a=bMab=∑a=bMab, and ∑aFNa 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: TP=15,FN=5,FP=30,TN=950. Sensitivity and specificity?
Asked: Both.
Concept: Definitions.
Approach: Direct.
Solution: Sensitivity =2015=0.75 (3 of 4 sick people found). Specificity =950+30950=0.9694.
Final answer:0.75 and 0.969.
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):
50545222534. Compute TPi,FPi,FNi 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.
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 R, macro R, and the sensitivity and specificity of the defective class.
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 [1,2,7] (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.
Connections: C11, class imbalance, cross-validation (C13), clustering evaluation (C41).
Mastery checklist
Extract TPi,FPi,FNi from a multiclass matrix.
Compute macro vs micro.
Prove micro P = micro R = accuracy.
C13. Cross-Validation: Leave-One-Out and k-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 k in kNN, C 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 Z={X1,…,Xn}, labels yi∈{1,…,c}.
Leave-One-Out (LOO): for i=1..n: train on Z∖{Xi}, predict yi′ for Xi. Score using {yi} vs {yi′} (e.g. F-measure).
k-fold CV: partition Z into Z1,…,Zk with (i) Zi=∅, (ii) Zi∩Zj=∅, (iii) ⋃Zi=Z, (iv) sizes (nearly) equal. For i=1..k: train on Pi=Z∖Zi, predict Zi. Score on the pooled predictions.
Mathematical formulation
Number of trainings: LOO =n; k-fold =k. k=n ⇒ k-fold = LOO.
Each training set has n−n/k=n(1−1/k) samples.
LOO is deterministic (exhaustive); k-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 n trainings; k-fold is cheaper.
The folds must be disjoint and cover everything.
Worked examples
Example 1 — Very Easy · Fold sizes
Problem:n=10 points, 3-fold CV. Possible fold sizes? How many models are trained?
Asked: Sizes and count.
Concept: Near-equal folds.
Approach:10=4+3+3.
Solution: Sizes 4,3,3 (any order). One model per fold → 3 models.
Final answer:4,3,3; 3 models.
Key lesson
Folds differ in size by at most one element.
Example 2 — Easy · Cost of LOO
Problem:n=100. For 5-fold CV and for LOO give training-set size and number of trainings.
Example 3 — Moderate · Cats and dogs by weight, LOO with 1-NN
Problem: Animals weighed in kg: x=1,2,3,10,11 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.
from sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import LeaveOneOut, cross_val_scoreX = np.array([[1], [2], [3], [10], [11]]); y = np.array([0, 0, 0, 1, 1])for k in (1, 3): print(k, cross_val_score(KNeighborsClassifier(k), X, y, cv=LeaveOneOut()).mean()) # 1.0 0.6
Key lesson
A k larger than the size of the smaller class (2 dogs) forces errors. Tune k by CV.
Example 5 — Very Hard · Average of folds vs pooled predictions
Problem: A 2-fold CV gives fold 1: TP=2,FP=0,FN=2; fold 2: TP=8,FP=4,FN=0. Compute F (a) per fold then averaged; (b) on the pooled predictions as the lecture prescribes (“using the actual labels of Z”). Explain the difference.