Machine Learning Slides 📂 Introduction · 6 of 17 45 min read

Precision, Recall & F1 Score Explained — With Confusion Matrix, F-Beta & MCC

A visual, beginner-friendly guide to Precision, Recall and F1 Score built around a real TB-screening scenario. Learn why accuracy misleads on imbalanced data, how the confusion matrix drives every metric, when to prioritise precision vs recall, why F1 uses the harmonic mean, F-beta for domain-tuned balance, MCC and Balanced Accuracy for robust reporting, multi-class averaging strategies, and six golden rules.

🎯

Precision · Recall · F1

The three metrics that expose what accuracy hides — how they're built from the confusion matrix, when to prioritise each, and how the harmonic mean forces your model to be good at both.
Precision Recall F1 & F-Beta Trade-offs

Press Next → or use ← → arrow keys

Section 01

Why Accuracy Alone Is Dangerous

Dr. Meera's TB screening — 89.5% accuracy that fails patients
Dr. Meera runs a TB screening programme. Only 5% of the 1,000 patients screened actually have TB. Her new model reports a proud 89.5% accuracy. Impressive?

A trivial model that predicts "healthy" for everyone hits 95% accuracy — and misses every single TB case. Accuracy treats all correct answers equally, ignoring which class was right. On imbalanced data, it is a mirror that tells only pleasant lies.
🚨
Two Errors — Very Different Consequences

A false alarm means one extra test and some anxiety. A missed case means untreated disease and possibly contagion. Any single number that treats them equally is unfit for the decision. We need Precision and Recall.

89.5%Accuracy — misleading
5%Actual TB prevalence
2Errors that differ in cost
0TB cases caught by trivial baseline
Section 02

The Confusion Matrix — Foundation of Everything

Predicted Healthy TB Actual Healthy TB 850 TN — correctly cleared 100 FP — false alarm 5 FN — MISSED TB 45 TP — caught TB 1,000 patients · 50 TB · 950 healthy
💔
FN Is Almost Always The Costliest Error

In disease detection, fraud, and safety systems, a missed threat is far worse than a false alarm. Every metric that follows — precision, recall, F1, F-beta — is just a different way of asking: "Which type of error do I punish more?"

Section 03

Precision — Of My Alerts, How Many Were Real?

Of 145 patients FLAGGED positive by the model 100 FP · false alarms 45 TP · real TB Precision = 45 / 145 = 31% Only 3 in 10 alerts are correct
Precision
TP / (TP + FP)
Of everything I predicted positive, what fraction was actually positive?
Prioritise When…
FP is costly
Spam filters (losing real email), legal search, blocking a legit transaction.
Section 04

Recall — Of Actual Cases, How Many Did I Catch?

Of 50 patients who ACTUALLY have TB 45 TP · caught 5 FN · missed Recall = 45 / 50 = 90% Catches 9 of 10 TB patients — misses 1
Recall (Sensitivity)
TP / (TP + FN)
Of everything that was actually positive, what fraction did I find?
Prioritise When…
FN is catastrophic
Cancer screening, fraud detection, airport security, earthquake alerts.
Section 05

The Precision–Recall Trade-off

0 0.5 1 1 0 threshold → Recall Precision F1 sweet spot ≈ 0.6
↔️
They Move In Opposite Directions

Lower the threshold → catch more true positives (recall ↑) but flag more false alarms (precision ↓). Raise it → cleaner alerts (precision ↑) but miss more real cases (recall ↓). F1 peaks somewhere in the middle — but where is a domain decision, not a maths one.

Section 06

F1 — Why The Harmonic Mean Beats The Arithmetic

❌ Arithmetic Mean · misleads (P + R) / 2 P=0.05 R=1.00 Mean 52.5% "looks decent" · but precision is terrible ✅ Harmonic (F1) · honest 2·P·R / (P + R) P=0.05 R=1.00 F1 9.5% forces both to be reasonable · no free lunch
F1 Score
F1 = 2·P·R / (P + R)
Range 0–1. Dominated by the smaller of the two — hides nothing.
Dr. Meera's Model
2·(0.31)·(0.90) / (0.31 + 0.90) = 0.46
Precision drags F1 down despite 90% recall — exactly the honest signal.
Section 07

F-Beta — Tilt The Balance To Your Domain

β = 0.5 F0.5 · precision-heavy spam · legal search Dr. Meera → 0.354 β = 1.0 F1 · balanced general purpose Dr. Meera → 0.461 β = 2.0 F2 · recall-heavy cancer · fraud Dr. Meera → 0.612 Precision Recall β F_β = (1 + β²) · P · R / (β²·P + R) β < 1 favours precision · β > 1 favours recall
🎚️
Dr. Meera Picks F2 — And Explains Why To Her Board

"Missing a TB case is four times as costly as a false alarm." That domain judgement translates directly into β = 2, and her primary metric becomes F2 = 0.612 — properly rewarding her model's 90% recall while still accounting for the flood of false alarms.

Section 08

Dr. Meera's Model — Every Metric At A Glance

MetricFormulaValueReading
Accuracy(TP+TN)/N89.5%Misleading on imbalance
PrecisionTP/(TP+FP)31.0%7 of 10 alerts are false
RecallTP/(TP+FN)90.0%Catches 9 of 10 TB cases
SpecificityTN/(TN+FP)89.5%Clears 9 of 10 healthy
F12PR/(P+R)46.1%Pulled down by precision
F25PR/(4P+R)61.2%Rewards high recall
Balanced Acc(Recall+Spec)/289.75%Class-balanced view
MCCsee slide 100.491Most robust single score
📋
Read The Full Story, Not One Number

No single metric captures classifier quality. Report a slate: accuracy for orientation, precision + recall for the trade-off, F-beta for a balanced summary aligned to cost, and MCC for the imbalance-robust single number.

Section 09

Advanced Metrics — MCC, Kappa & Balanced Accuracy

🧬
Matthews Correlation (MCC)
−1 to +1 · uses all 4 cells
The most robust single number for imbalanced binary problems. Not fooled by class distribution. Dr. Meera → 0.491.
🤝
Cohen's Kappa (κ)
agreement corrected for chance
A random baseline scores κ = 0, not high accuracy. Standard scale: <0.2 poor · 0.6–0.8 substantial · >0.8 near-perfect.
⚖️
Balanced Accuracy
(Recall + Specificity) / 2
Weights both classes equally. Interpretable, honest on imbalanced data. Dr. Meera → 89.75%.
MCC Formula
(TP·TN − FP·FN) / √[(TP+FP)(TP+FN)(TN+FP)(TN+FN)]
A correlation between predictions and truth. +1 perfect, 0 random, −1 perfectly inverse.
Kappa
κ = (pₒ − pₑ) / (1 − pₑ)
Observed agreement minus what chance predicts, normalised. Standard for annotator agreement too.
🥇
Prefer MCC For A Single-Number Report On Imbalanced Data

Precision/Recall/F1 each ignore the TN cell. MCC uses all four — that's why it's the most trustworthy summary when classes are skewed.

Section 10

Multi-Class — Macro vs Micro vs Weighted

ClassSupportPrecisionRecallF1
Benign6000.940.960.95
Type-A3000.820.780.80
Type-B1000.610.550.58
📐
Macro F1
unweighted mean
(0.95 + 0.80 + 0.58) / 3 = 0.777. Every class matters equally → Type-B's weakness shows.
🔢
Micro F1
pooled TP/FP/FN
Sums across classes, then computes globally. Dominated by frequent classes. Best for overall system performance.
⚖️
Weighted F1
by support
(600·0.95 + 300·0.80 + 100·0.58) / 1000 = 0.868. Hides Type-B's failure behind Benign's dominance.
👀
Always Show The Per-Class Breakdown

Divergence between Macro (0.78) and Weighted (0.87) is a red flag: a minority class is failing silently. Always report the per-class table alongside averages — it's the only view that catches this.

Section 11

Implementation — sklearn One-Liner To Full Report

from sklearn.metrics import (
    classification_report,
    precision_score, recall_score, f1_score, fbeta_score,
    matthews_corrcoef, cohen_kappa_score, balanced_accuracy_score,
    precision_recall_fscore_support,
)

# ── One line, full slate ─────────────────────────
print(classification_report(y_test, y_pred, target_names=['Healthy', 'TB']))

# ── Individual metrics ───────────────────────────
p  = precision_score(y_test, y_pred)
r  = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
f2 = fbeta_score(y_test, y_pred, beta=2)           # recall-heavy
mcc = matthews_corrcoef(y_test, y_pred)            # best single number

# ── Threshold tuning — trade P for R ─────────────
y_proba    = model.predict_proba(X_test)[:, 1]
y_pred_low = (y_proba >= 0.3).astype(int)         # lower τ → higher recall

# ── Multi-class averaging strategies ─────────────
for avg in ['macro', 'weighted', 'micro']:
    p, r, f, _ = precision_recall_fscore_support(y_test, y_pred, average=avg)
    print(f"{avg}: P={p:.3f}  R={r:.3f}  F1={f:.3f}")
🧪
Tune τ On Validation · Report Once On Test

The default 0.5 threshold rarely maximises what you actually care about. Sweep τ on a validation split to find the best operating point, then evaluate exactly once on the pristine test set.

Section 12

When To Use Which Metric

📧
Spam Filtering
FP = losing real email. Choose Precision / F0.5. Raise τ so only high-confidence spam is filtered.
🩺
Cancer / TB Screening
FN = missed disease → potentially fatal. Choose Recall / F2. Lower τ to catch every case.
💳
Fraud Detection
Missed fraud → direct loss. Choose Recall + PR-AUC. Accept extra investigations to catch more.
🔍
Search & IR
Bad results waste time. Choose Precision@K / F0.5 — top results must be relevant.
🚨
Airport Security
Missed threat = disaster. Choose Recall. Accept many secondary screenings to guarantee coverage.
📊
Balanced General ML
No strong cost asymmetry? F1 or MCC. Report both for a defensible summary.
⚖️
Only Business Can Break The Trade-off

Data science can plot every curve. But whether it is better to miss 5 TB patients or send 100 healthy people for extra tests is a medical ethics decision. Get the domain expert's judgement first — then pick the metric that encodes it.

Section 13

Common Pitfalls — What Silently Breaks Reports

📉
Accuracy On Imbalance
the classic trap
99% accuracy at 1% positive base rate → catches nothing. Always pair with P, R, F1 or MCC.
🎚️
Default 0.5 Threshold
rarely optimal
τ = 0.5 maximises F1 only by coincidence. Sweep it on validation — you'll usually find a better spot.
Arithmetic Instead Of Harmonic
optimistic bias
(P + R) / 2 hides a failing metric. F1 (harmonic) surfaces it. Always report the harmonic mean.
🔀
Confusing P and R
FP vs FN focus
Precision punishes false alarms · Recall punishes missed cases. Remember which cell each ignores.
👥
Multi-Class Averages Only
minority classes hidden
Weighted F1 = 0.87 while one rare class scores 0.58? Show the per-class table. Every time.
⚙️
Wrong F-Beta
β chosen from taste
Pick β from domain cost asymmetry, not gut feel. FN 4× worse than FP → β = 2, not "let's try a few".
Section 14

Golden Rules — Six Habits That Save Reports

🎯 PRECISION · RECALL · F1 DISCIPLINE
1
Never report accuracy alone on imbalanced data. Always include Precision, Recall and F1 — or promote MCC and Balanced Accuracy to the headline.
2
Define error cost before choosing the metric. Cost of FN vs FP decides whether you optimise Recall, Precision or F-beta. Ask the domain expert first.
3
Tune the threshold — don't accept 0.5 by default. Sweep τ on validation, evaluate once on test. The right operating point is rarely the middle.
4
Use MCC as your single-number summary for binary problems. It's the only common metric that uses all four confusion-matrix cells and doesn't wobble with class ratio.
5
In multi-class, always show the per-class breakdown. Macro vs Weighted divergence is the tell of a failing minority class. Averages alone will hide it.
6
Only the business can break the precision–recall tie. Data science plots the trade-off. Domain experts pick the point.
FINAL

Precision · Recall · F1 — Honest Numbers For Real Decisions

TP/(TP+FP)Precision · quality
TP/(TP+FN)Recall · coverage
2PR/(P+R)F1 · harmonic mean
βF-beta · tilt to domain
MCCAll 4 cells · robust
6Golden rules
🎯
The Foundation Is Set

You now understand the confusion matrix, the trade-off, F1's honest harmonic mean, F-beta's tunable bias, and the imbalance-robust MCC. Every classifier evaluation you do — from spam to sepsis — rests on the ideas you just learned.

📚
Where To Go Next

Study the Precision–Recall curve & PR-AUC, then ROC-AUC, then cost-sensitive learning. Practice on Kaggle's Credit Card Fraud or Pima Indians Diabetes — both properly imbalanced, both perfect for exercising every metric here.

🎯 End of tutorial · Press to review, or click Restart