Model evaluation: ROC curves and tuning
ROC curves compare true positive rate and false positive rate as a classifier threshold moves; AUC measures ranking quality and is used for model selection and threshold tuning.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Engineers use ROC curves and AUC when they need a threshold-independent measure of a binary classifier's performance, for example when choosing a classifier for a fraud-detection or medical-diagnosis system. ROC analysis also guides threshold tuning (choose operating point) and model selection during hyperparameter search (optimise AUC), often before deployment.
Key ideas
True Positive (TP): positives correctly predicted
False Positive (FP): negatives predicted as positive
True Negative (TN): negatives correctly predicted
False Negative (FN): positives predicted as negative Draw a square with four boxes, using rows = actual (top = actual positive, bottom = actual negative) and columns = predicted (left = predicted positive, right = predicted negative): label top-left TP, top-right FN, bottom-left FP, bottom-right TN, and indicate actual vs predicted on the sides.
True Positive Rate (TPR), also called sensitivity or recall, is the fraction of actual positives correctly detected.
- Exact definition: TPR = TP / (TP + FN). Assumes (TP + FN) > 0.
False Positive Rate (FPR) is the fraction of actual negatives incorrectly labelled positive.
- Exact definition: FPR = FP / (FP + TN). Assumes (FP + TN) > 0.
Score and threshold: Many classifiers output a real-valued score (e.g. probability) rather than only labels. A threshold t converts scores to labels: predict positive if score ≥ t, else negative. Varying t changes TP, FP, FN, TN and thus TPR and FPR.
ROC curve (Receiver Operating Characteristic): the set of points (FPR(t), TPR(t)) as threshold t varies over all possible score values (including ±∞). By convention plot FPR on the x-axis (0→1) and TPR on the y-axis (0→1). Draw axes 0..1 and plot the curve from (0,0) to (1,1).
Area Under the ROC Curve (AUC): the area under the ROC curve, a scalar in [0,1]. Interpretation: the probability that the classifier will assign a higher score to a randomly chosen positive instance than to a randomly chosen negative instance (for continuous scores and no ties). This gives a ranking-quality interpretation.
- Exact statement (assumptions): If scores are continuous and independent, AUC = P(score(X_pos) > score(X_neg)) + 0.5·P(score(X_pos) = score(X_neg)).
Properties & assumptions:
- ROC is threshold-independent: it summarizes performance across thresholds.
- ROC and AUC are invariant under any monotonic increasing transformation of the score (rank-based).
- A classifier that randomly ranks instances has AUC = 0.5; a perfect classifier has AUC = 1.0; a perfectly inverted classifier has AUC = 0.0.
- ROC and AUC are insensitive to the class prior (class imbalance) in ranking quality, but FPR and TPR points do depend on the actual class counts.
- If costs (FP vs FN) differ, choose operating threshold using cost-sensitive analysis (Youden's J, minimum cost, or expected utility) rather than AUC alone.
Tuning thresholds:
- Youden's J statistic: J(t) = TPR(t) − FPR(t). Choose t that maximises J (equivalently maximises vertical distance from diagonal).
- Cost-based threshold: if cost_FP and cost_FN known, choose t minimizing expected cost = cost_FP·FP_rate·N_neg + cost_FN·FN_rate·N_pos (convert rates to counts). Requires prior class probabilities. Equivalently, expected cost per instance = cost_FP·P(neg)·FPR(t) + cost_FN·P(pos)·FNR(t), where FNR(t) = 1 − TPR(t).
- Precision–Recall (PR) curve: for highly imbalanced positive class, PR curve (precision vs recall) can be more informative than ROC.
Model selection and cross-validation:
- Use cross-validated AUC (mean AUC over folds) to compare models/hyperparameters. Use paired tests (e.g. DeLong) if you must test significance.
- When tuning hyperparameters to maximise AUC, avoid leaking test data into the model selection step.
Formulas
TPR = TP / (TP + FN) — TPR (unitless), applies when (TP+FN)>0.
FPR = FP / (FP + TN) — FPR (unitless), applies when (FP+TN)>0.
Precision = TP / (TP + FP) — precision (unitless), applies when (TP+FP)>0.
Youden J = TPR - FPR — unitless, used to pick threshold; higher is better.
AUC = ∫_{0}^{1} TPR(x) dx — AUC (unitless), area under the ROC curve; in practice compute by the trapezoidal rule.
AUC (empirical) = (1/(N_pos·N_neg)) · Σ_{i∈pos} Σ_{j∈neg} [ I(score_i > score_j) + 0.5·I(score_i = score_j) ] — applies for discrete samples.
Note: In code remember functions: sklearn.metrics.roc_curve(y_true, y_score) returns fpr, tpr, thresholds; sklearn.metrics.roc_auc_score(y_true, y_score) returns AUC.
Worked examples
Example 1 — Numerical confusion-matrix → ROC and AUC (step-by-step)
Given 4 test samples with true labels and classifier scores (score = higher means more likely positive):
- True labels (y): [0, 0, 1, 1] (0 = negative, 1 = positive)
- Scores (s): [0.1, 0.4, 0.35, 0.8]
- Sort unique score thresholds in descending order plus +∞: thresholds = [∞, 0.8, 0.4, 0.35, 0.1]. For each threshold t compute predicted positives (score ≥ t) and then TPR and FPR.
- Compute counts and rates:
- t = ∞: predicted positives = none → TP=0, FP=0 → TPR = 0/(2)=0.0, FPR = 0/(2)=0.0
- t = 0.8: predicted positives = {score 0.8} → TP=1, FP=0 → TPR=1/2=0.5, FPR=0/2=0.0
- t = 0.4: predicted positives = {0.8,0.4} → labels [1,0] → TP=1, FP=1 → TPR=1/2=0.5, FPR=1/2=0.5
- t = 0.35: predicted positives = {0.8,0.4,0.35} → labels [1,0,1] → TP=2, FP=1 → TPR=2/2=1.0, FPR=1/2=0.5
- t = 0.1: predicted positives = all → TP=2, FP=2 → TPR=1.0, FPR=1.0
- ROC points: (FPR, TPR) = (0.0,0.0), (0.0,0.5), (0.5,0.5), (0.5,1.0), (1.0,1.0).
- Compute AUC by trapezoidal rule (x=FPR, y=TPR):
- Areas between consecutive points: dx*(y1+y2)/2
- Non-zero contributions: between x=0→0.5 with y≈0.5 gives area 0.25; between x=0.5→1 with y≈1 gives area 0.5. Total AUC = 0.25 + 0.5 = 0.75.
Final answer: AUC = 0.75.
Example 2 — Python code (runs with scikit-learn) to compute and print ROC arrays and AUC
Python 3 code (requires scikit-learn and numpy):
import numpy as np
from sklearn.metrics import roc_curve, roc_auc_score
y_true = np.array([0, 0, 1, 1])
y_scores = np.array([0.1, 0.4, 0.35, 0.8])
fpr, tpr, thresholds = roc_curve(y_true, y_scores)
auc = roc_auc_score(y_true, y_scores)
print('fpr:', fpr)
print('tpr:', tpr)
print('thresholds:', thresholds)
print('auc:', auc)
Sample exact output (numpy formatting may vary slightly by version):
fpr: [0. 0. 0.5 0.5 1. ]
tpr: [0. 0.5 0.5 1. 1. ]
thresholds: [inf 0.8 0.4 0.35 0.1 ]
auc: 0.75
Note: verify threshold formatting on your sklearn/numpy versions; AUC value is 0.75.
Example 3 — Short derivation: AUC equals probability a random positive ranks higher than random negative
Let S+ be score of a random positive and S- score of a random negative. Empirical AUC counts pairs (i in pos, j in neg) where score_i > score_j (plus 0.5 for ties) and normalises by N_pos·N_neg. For continuous distributions without ties this equals P(S+ > S-). Standard derivation uses double integral over joint distribution and shows AUC = ∫∫ I(s+ > s-) dF+(s+) dF-(s-).
Common mistakes
- Using ROC when classes are highly imbalanced and rare positives are the main interest—PR curve may be more informative.
- Forgetting to use cross-validation when reporting AUC; reporting test-set AUC after fitting hyperparameters on the same test set is data leakage.
- Miscomputing TPR/FPR by mixing up denominators (must divide TP by positives, FP by negatives).
- Treating AUC changes of small magnitude as meaningful without statistical test or confidence intervals.
For your exam
Typical question types:
- Definitions: define ROC, AUC, TPR, FPR, Youden's J.
- Short notes: explain relation between AUC and ranking, precision–recall vs ROC, threshold tuning methods.
- Derivations: show that AUC = probability(S+ > S−) or derive formula for trapezoidal AUC from discrete ROC points.
- Numericals: given scores and labels, compute confusion matrix, ROC points and AUC by trapezoid rule (show steps and units not applicable).
- Programming: write Python code using sklearn to compute ROC and AUC, and show outputs.
- Diagrams: draw ROC axes (FPR x-axis, TPR y-axis), plot a sample curve, mark diagonal (random classifier) and the chosen operating threshold point.
What full-marks answers include:
- Precise definitions with formulas, required assumptions, and correct denominators; for numerical questions show each threshold, counts TP/FP/TN/FN and compute TPR and FPR; for AUC show trapezoidal calculation step-by-step or the pairwise counting method; for programming questions include runnable code and matched output.
Quick check
- Define TPR and give its formula.
- What does AUC = 0.5 mean for a classifier?
- Name one method to choose an operating threshold from ROC.
Answers: 1) TPR = TP/(TP+FN). 2) AUC = 0.5 means the classifier ranks positives and negatives no better than random (chance). 3) Youden's J statistic (maximise TPR − FPR).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?