Classification Metrics: Confusion Matrices, PR & ROC-AUC
Defeating the 99% Accuracy Paradox, Precision vs. Recall vs. F1, Macro vs. Micro F1, ROC-AUC vs. PR-AUC & Business Thresholding
Classification metrics (Confusion Matrix, Precision, Recall, F1, ROC-AUC, PR-AUC) measure how well a classifier separates positive and negative cases across decision thresholds.
Plain accuracy is a trap on imbalanced datasets—a lazy model predicting 'not fraud' 100% of the time gets 99.9% accuracy while catching zero criminals.
Picking the wrong evaluation metric ships completely broken models — like a 99%-accurate fraud detector that catches ZERO fraud!
Tuning the classification threshold τ (instead of blindly leaving τ = 0.50!) is the fastest zero-retraining lever to match real business costs.
Knowing when ROC-AUC hides false alarms on 0.1% fraud (and switching to PR-AUC + Precision@K) is what separates production DS leaders from juniors.
'Explain Precision vs. Recall with real examples', 'ROC-AUC vs. PR-AUC on imbalanced data', and 'What is the probabilistic meaning of ROC-AUC?' are guaranteed DS/ML screens!
You are building a Cancer Screening AI (missing a real cancer patient can be fatal; a false alarm just means an inexpensive follow-up test). Which metric should you prioritize?
- Read any 2×2 Confusion Matrix instantly to compute Accuracy, Precision, Recall (Sensitivity), Specificity, and F1 / F_β.
- Choose Precision-focused vs. Recall-focused thresholds based on real asymmetric business costs (e.g., spam vs. cancer screening).
- Explain why PR-AUC beats ROC-AUC on heavily imbalanced datasets (1% fraud/rare disease) and interpret ROC-AUC probabilistically!
- Distinguish Macro, Micro, and Weighted F1 for multiclass classification.
A classifier outputs a probability score (e.g. 0.73), NOT a hard Yes/No! You turn that score into a decision by picking a Threshold (default 0.50, yet rarely optimal!). Every metric in this chapter simply scores how well your model ranks positives above negatives AND how clean your errors are at your chosen threshold.
1. The 99% Accuracy Paradox & 2×2 Confusion Matrix
Click between the Lazy Dummy and the Trained Fraud Detector below on 1,000 swipes (10 real frauds). Notice how Accuracy barely budges (99.0% vs 99.4%) while Recall jumps from 0% to 80% and F1 jumps from 0% to 72.7%! Never trust raw Accuracy on imbalanced data!
The Harmonic Mean Trick Behind F1
Why does use the harmonic mean instead of (P + R) / 2? Because harmonic mean is pulled sharply toward the SMALLER number — you can ONLY score high F1 when BOTH Precision AND Recall are strong! Need Recall to matter times more than Precision? Use !
99.0% Accuracy yet catches ZERO fraudsters — completely useless!
A classifier gets TP = 40, FP = 10, FN = 60, TN = 890. Compute its Precision, Recall, and F1 Score.
2. ROC-AUC vs. PR-AUC (When ROC Lies on Rare Classes!)
Suppose 1,000,000 normal swipes and 1,000 fraud swipes occur. Your model flags 900 real frauds (TPR = 90%) AND 10,000 innocent shoppers (FP = 10,000). What is the False Positive Rate FPR = 10,000 / 1,000,000? Just 1% — so ROC-AUC looks like a glowing 0.95! Yet what is your Precision? Only 900 / 10,900 = 8.3% (over 91% of your alerts are angry innocent customers!!). PR-AUC uses Precision instead of FPR, exposing that disaster immediately!
Probabilistic Meaning of ROC-AUC (Interview Gold!)
ROC-AUC = !
- Notice ROC-AUC depends ONLY on rank order — multiplying all probabilities by
0.1leaves ROC-AUC 100% unchanged (even though calibration is ruined!).
Pause & Check: If you divide every single predicted probability of your model by 2 (e.g., 0.8 → 0.4, 0.6 → 0.3), what happens to ROC-AUC?
3. Multiclass Metrics: Macro vs. Micro vs. Weighted F1
With 3+ classes (e.g., 85% Normal, 14% Warning, 1% Critical), averaging F1 the wrong way hides total failure on the 1% Critical class! Look at the 3 averaging modes:
- Macro F1: Compute F1 for each class separately, then take the unweighted average . If Critical gets
F1 = 0, Macro F1 drops dramatically — best when rare classes matter! - Micro F1: Pool global TP, FP, FN across all classes (in single-label multiclass, Micro F1 = Overall Accuracy!).
- Weighted F1: Weight each class's F1 by its frequency share.
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Almost NEVER in real business problems! τ = 0.50 implicitly assumes False Positives and False Negatives cost the exact same dollar amount. If a missed fraud costs $500 and a quick SMS verification check costs $0.50, your Bayes-optimal threshold is way lower (around τ ≈ 0.05!) — always tune τ on your Validation set to maximize business profit!
Watch Threshold τ Glide Across Class Scores & Trace the ROC Curve Live
Lowering τ catches more Positives (TPR ↑) at the cost of more False Alarms (FPR ↑)!
Fraud & Trust/Safety Alert Queues
Ops teams have fixed review capacity (e.g. 500 alerts/day) → optimize Recall@Precision≥80% and PR-AUC.
Cancer & Rare Disease Triage
Tuned to ≥98% Recall (low threshold τ) so practically zero sick patients are sent home unchecked.
Email Spam & Abuse Filtering
Tuned to ≥99.5% Precision (high threshold τ) so important user emails almost never get buried in Spam.
Multiclass Intent Classification
Uses Macro F1 to ensure rare high-value customer intents ('cancel_enterprise') aren't drowned out by common 'hello' queries.
import numpy as np
from sklearn.metrics import average_precision_score, confusion_matrix, f1_score, roc_auc_score
y_true = np.array([1, 1, 1, 0, 1, 0, 0, 0, 0, 0])
y_prob = np.array([0.92, 0.81, 0.45, 0.72, 0.63, 0.35, 0.21, 0.14, 0.09, 0.03])
# Threshold-free ranking metrics
print("ROC-AUC:", round(roc_auc_score(y_true, y_prob), 3))
print("PR-AUC: ", round(average_precision_score(y_true, y_prob), 3))
# Tune threshold τ to maximize F1 on Validation!
best_t, best_f1 = max(
((t, f1_score(y_true, (y_prob >= t).astype(int))) for t in np.linspace(0.1, 0.9, 81)),
key=lambda x: x[1],
)
print(f"Best threshold τ={best_t:.2f} -> F1={best_f1:.3f}")