Machine Learning Slides 📂 Introduction · 4 of 17 44 min read

ROC Curve & AUC Explained

A visual, beginner-friendly guide to the ROC Curve and AUC built around a real fraud-detection scenario. Learn TPR vs FPR, how the curve is built by sweeping the threshold, what AUC actually measures, why it lies on imbalanced data, when to prefer PR-AUC, threshold selection with Youden's J and cost matrices, multi-class extensions, bootstrap confidence intervals, and six golden rules every practitioner must follow.

📈

ROC Curve & AUC

The threshold-independent lens on classifier quality — how the curve is built, what AUC really means, when it lies, and how to pick the right operating point for your business.
TPR vs FPR Threshold Sweep ROC vs PR Youden's J

Press Next → or use ← → arrow keys

Section 01

What is ROC & AUC?

Aisha, a fraud analyst, needs one number to compare three models
Aisha runs a fraud team at a large payments company. Every week her data-science group ships a new candidate model. Accuracy is useless — with 0.5% fraud, always predicting "not fraud" scores 99.5% and catches zero criminals.

She needs a metric that captures classifier quality across every possible threshold, so she can pick the model with the best overall discrimination — then tune the threshold to her operational reality afterwards. That metric is ROC-AUC.
💡
The Two Definitions

The ROC Curve plots True Positive Rate (y) vs False Positive Rate (x) as the decision threshold sweeps from 1 down to 0. The AUC is the area beneath that curve — a single number capturing overall separability.

0.5AUC — random guessing
1.0AUC — perfect classifier
∀τAll thresholds at once
P(·)Probability interpretation
Section 02

The Two Rates That Build The Curve

True Positive Rate (Recall / Sensitivity)
TPR = TP / (TP + FN) = TP / P
Of all actual fraud transactions, what fraction did we catch? Higher is better.
False Positive Rate (Fall-out)
FPR = FP / (FP + TN) = FP / N
Of all legitimate transactions, what fraction did we wrongly flag? Lower is better.
Predicted Legit Fraud Actual Legit Fraud TN correctly legit FP false alarm FN missed fraud TP caught fraud TPR = TP P FPR = FP N
🧮
Read Each Rate Along Its Own Row

TPR uses only the fraud row (P). FPR uses only the legit row (N). Each rate is normalised inside its own class — that's what makes the ROC curve robust to shifts in prevalence.

Section 03

The Threshold Sweep — What Actually Moves

score = 0 score = 1 Legit scores Fraud scores threshold τ ← predict LEGIT predict FRAUD →
🎚️
Every Threshold Is A Trade-off

Slide τ left → catch more fraud (TPR ↑) but flag more legit transactions (FPR ↑). Slide τ right → fewer false alarms (FPR ↓) but miss more fraud (TPR ↓). The ROC curve traces this exact trade-off across every possible τ.

Section 04

Building The Curve — Step By Step

0 1 0 1 False Positive Rate → True Positive Rate → random (AUC = 0.5) AUC ≈ 0.83
🪜
Vertical Jumps = Fraud Caught · Horizontal Moves = False Alarms

Sort predictions by descending score. Sweep the threshold from high to low. Each time a true positive gets added, the curve steps up. Each false positive steps it right. Perfect classifier: all steps up first, then all steps right.

Section 05

What AUC Actually Means

Probabilistic Interpretation
AUC = P( score(positive) > score(negative) )
The probability the model ranks a random fraud higher than a random legit transaction. Rank-based.
Trapezoidal Calculation
A = (FPR₂ − FPR₁) · (TPR₁ + TPR₂) / 2
Sum trapezoid areas between consecutive ROC points. Numerically stable, works for any curve.
AUC RangeMeaningWhat To Do
0.50Random guessingModel is broken — rebuild features or targets
0.50 – 0.70Poor discriminationNeeds work — check features, class balance
0.70 – 0.90Good to very goodProduction-ready in most domains
0.90 – 1.00ExcellentAudit for data leakage before shipping
🚨
"Too Good To Be True" Almost Always Is

AUC > 0.98 on a real-world problem usually means data leakage — a target-derived feature snuck into the training set, or your test set overlaps with training. Audit before celebrating.

Section 06

Comparing Models — One Chart, Instant Verdict

0 1 1 FPR → TPR → Gradient Boost · 0.93 Random Forest · 0.79 Logistic Reg · 0.64
🏆
Higher & Further Left = Better

The model whose curve hugs the top-left corner dominates at every threshold. Aisha picks Gradient Boost (AUC 0.93) — then tunes the operating point to her fraud team's capacity.

Section 07

When ROC Lies — Meet PR-AUC

ROC Curve · AUC = 0.93 looks excellent — TN dominates the denominator FPR → TPR → "our model rocks!" PR Curve · PR-AUC = 0.18 reality — precision collapses on rare fraud Recall → Precision → 8% precision · 11 false alarms per hit
ScenarioUse ROC-AUCUse PR-AUC
Balanced classes (~50/50)BestAlso works
Severe imbalance (< 1% positive)Can misleadPreferred
Fraud / rare-disease / spamWith cautionMuch more informative
💡
Why ROC-AUC Deceives On Imbalance

FPR uses TN in its denominator. With 99,950 legit transactions, even hundreds of false positives leave FPR near zero — the ROC curve stays hugging the top-left corner while your analyst team drowns in false alarms. Precision ignores TN entirely — that's why PR-AUC tells the truth.

Section 08

Picking The Operating Point

AUC scores the model. It does not pick your threshold — that's a business decision, not a maths one.

📐
Youden's J Statistic
maximise TPR − FPR
Picks the point farthest above the random diagonal. Treats FP and FN as equally costly.
💰
Cost-Weighted
real ₹ per FP vs per FN
Missed £10k fraud vs 1-hour analyst review — build a cost matrix and minimise expected loss.
⚙️
Capacity-Constrained
"200 alerts/day max"
Team can review 200 alerts/day → pick the threshold that produces ≤ 200 predicted positives.
⚖️
F-Beta Maximisation
weighted P vs R
F2 weights recall 2× vs precision — perfect when a miss costs more than a false alarm.
🛡️
Minimum Recall Floor
regulatory / SLA-driven
"Catch ≥ 95% of fraud" is a compliance non-negotiable — pick lowest threshold that meets it.
🧪
A/B Test It
production is the judge
Shadow-deploy two thresholds. Measure downstream business impact — not just model metrics.
⚠️
Never Pick The Threshold On The Test Set

Selecting τ using test-set metrics is data snooping. Use a validation set (or nested cross-validation), then report final performance on the pristine test set.

Section 09

Beyond Binary — Multi-Class ROC

One-vs-Rest (OvR)
K binary classifiers · K ROC curves
For a K-class problem, treat each class as "positive" vs everything else. Get one ROC per class.
Macro-average AUC
AUC_macro = (1/K) · Σ AUCₖ
Unweighted average — treats every class equally, even rare ones. Good for imbalanced multiclass.
🎯
Macro vs Weighted — Pick Based On Your Question

Macro asks: "How well does the model discriminate the average class?" Weighted asks: "How well does it perform on the majority of samples?" Rare classes hide in the weighted average — always report both.

Section 10

Implementation — From Scratch & sklearn

# ── FROM SCRATCH · sweep threshold, plot points ──
def roc_curve_manual(y_true, y_scores):
    thresholds = np.sort(np.unique(y_scores))[::-1]
    P, N = np.sum(y_true == 1), np.sum(y_true == 0)
    tpr, fpr = [0.0], [0.0]
    for t in thresholds:
        y_pred = (y_scores >= t).astype(int)
        TP = np.sum((y_pred == 1) & (y_true == 1))
        FP = np.sum((y_pred == 1) & (y_true == 0))
        tpr.append(TP / P);  fpr.append(FP / N)
    return np.array(fpr), np.array(tpr)

auc = np.trapz(tpr, fpr)   # trapezoidal rule

# ── PRODUCTION · scikit-learn one-liner ─────────
from sklearn.metrics import roc_curve, roc_auc_score

y_proba = model.predict_proba(X_test)[:, 1]
fpr, tpr, thr = roc_curve(y_test, y_proba)
auc = roc_auc_score(y_test, y_proba)

# ── Pick threshold via Youden's J ────────────────
best_idx    = np.argmax(tpr - fpr)
best_thresh = thr[best_idx]
🧪
Bootstrap Before You Ship

A single AUC number can vary wildly on small test sets. Resample the test set 1,000× with replacement and report the 95% confidence interval — e.g. "AUC = 0.89 [0.85–0.93]". Two models whose CIs overlap are statistically indistinguishable.

Section 11

Where ROC-AUC Earns Its Keep

💳
Fraud Detection
Compare model versions, then tune the threshold to the analyst team's daily review capacity.
🩺
Medical Diagnosis
Screen for rare diseases — set the threshold to guarantee a minimum recall (miss no cancers).
📧
Spam Filtering
Raise the threshold — false negatives (spam in inbox) are far cheaper than false positives (real email lost).
📊
Credit Scoring
Regulators want threshold-independent quality metrics; AUC is the industry-standard KPI.
🚨
Anomaly & IDS
Intrusion detection at extremely low base rates — pair ROC-AUC with PR-AUC to expose false-alarm reality.
🎯
Marketing Response
Rank customers by propensity, pick top-N by budget — AUC directly measures ranking quality.
Section 12

Common Pitfalls — What Bites Beginners

⚖️
ROC on Severe Imbalance
the classic trap
AUC = 0.93 while precision is 8%. Always pair with PR-AUC when positives are < 5%.
📏
No Confidence Interval
single number ≠ truth
Bootstrap resample 1,000× and report the 95% CI. Model A at 0.89 vs Model B at 0.87 may be pure noise.
🔍
Threshold On Test Set
data snooping
Never pick τ using test-set metrics. Use a validation split or nested CV — else your production number lies.
🔀
Comparing Across Test Sets
apples vs oranges
AUC = 0.90 on one dataset vs 0.85 on another says nothing. Only compare AUC on identical test data.
📉
Ignoring Calibration
rank ≠ probability
AUC measures ranking, not whether "0.8" really means 80%. Check calibration curves separately.
🔄
Inverted Positive Class
AUC = 0.15 ?!
If AUC comes out below 0.5, you almost certainly swapped labels. AUC = 0.15 means AUC = 0.85 for the other class.
Section 13 · Part 1

Golden Rules — 1 to 3

📈 ROC & AUC DISCIPLINE · RULES 1–3
1
Treat AUC as a ranking score, not a probability calibration. A model can rank samples brilliantly and still output miscalibrated probabilities. Inspect calibration curves separately when downstream cost depends on the actual number.
2
AUC scores the model; business criteria pick the threshold. Use Youden's J, F-beta, or a cost matrix on the validation set — never the test set. The default 0.5 is almost always the wrong operating point.
3
On imbalanced data (< 10% positives), always compute PR-AUC alongside ROC-AUC. If the two diverge, PR-AUC is telling the truth. ROC's TN-dominated denominator hides the false-alarm avalanche.
Section 13 · Part 2

Golden Rules — 4 to 6

📈 ROC & AUC DISCIPLINE · RULES 4–6
4
Never compare AUC across different test sets. AUC depends on the score distribution — identical evaluation conditions are non-negotiable. Use the same held-out fold for every candidate model.
5
Report a bootstrap 95% confidence interval, not a lone AUC. "0.89 [0.85–0.93]" tells the reader whether the difference between two models is real or noise. Resample the test set 1,000× — it's a two-line addition to your pipeline.
6
Cross-validate AUC across folds. A single holdout AUC of 0.89 tells you less than "0.87 ± 0.03 across 5 folds." Variance across folds reveals whether the metric is stable enough to trust.
🎯
The AUC Sanity Checklist

✅ PR-AUC also computed · ✅ Bootstrap CI reported · ✅ Threshold picked on validation ✅ Cross-validated · ✅ Calibration inspected · ✅ Positive class verified.

FINAL

ROC & AUC — Ranking Quality, Distilled

TPR × FPRThe two axes
0.5 → 1Random → perfect AUC
P(·)Ranking probability
PR-AUCThe rare-event partner
6Threshold strategies
6Golden rules
🎯
The Foundation Is Set

You now understand how the ROC curve is built, what AUC really measures, when it lies, and how to pick your operating point. Every classifier evaluation you do — logistic regression, XGBoost, neural networks — will rely on these ideas.

📚
Where To Go Next

Study calibration curves & Platt scaling, then PR-AUC and Average Precision in depth, then cost-sensitive learning. Practice by comparing three models on Kaggle's Credit Card Fraud dataset — exactly Aisha's problem at scale.

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