Sub topic 2
Building a ROC Curve by Sweeping the Threshold
Assume you know binary classification, confusion-matrix terms, NumPy, and model scores such as predicted probabilities. This chapter uses a score where larger values indicate stronger evidence for the positive class.
Building the ROC curve
A classifier produces scores. A decision threshold converts each score into a label:
- score ≥ threshold: predict positive
- score < threshold: predict negative
Changing the threshold changes the confusion matrix. For each threshold, calculate:
- True positive rate (TPR): the fraction of actual positives detected.
- False positive rate (FPR): the fraction of actual negatives incorrectly marked positive.
A ROC curve plots TPR against FPR while sweeping through the distinct scores from high to low.
import numpy as np
from sklearn.metrics import roc_curve, roc_auc_score
y_true = np.array([0, 0, 1, 1])
y_score = np.array([0.1, 0.4, 0.35, 0.8])
fpr, tpr, thresholds = roc_curve(y_true, y_score)
print(list(zip(thresholds, fpr, tpr)))
print(roc_auc_score(y_true, y_score)) # 0.75For this data, the curve includes these important points:
| Threshold | FPR | TPR |
|---|---|---|
| 0.80 | 0.00 | 0.50 |
| 0.40 | 0.50 | 0.50 |
| 0.35 | 0.50 | 1.00 |
| 0.10 | 1.00 | 1.00 |
Reading the curve
The diagonal from (0, 0) to (1, 1) represents random ranking. A useful classifier rises toward the upper-left corner: high TPR with low FPR. Every point represents a trade-off. Lowering the threshold usually catches more positives but also creates more false positives.
AUC: summarizing the curve as one number
AUC, or area under the ROC curve, summarizes the curve. An AUC of 1 means perfect separation. An AUC of 0.5 matches random ranking. Values below 0.5 indicate that reversing the scores could improve ranking.
AUC evaluates ranking across all thresholds. It does not select the threshold your application should use.
AUC as a ranking probability
AUC equals the probability that a randomly selected positive example receives a higher score than a randomly selected negative example. Ties count as half a win. Here, three of four positive-negative pairs are correctly ordered, so AUC is 0.75.
Exercise
Why can a model with a high AUC still require careful threshold selection?
Show answer
AUC summarizes all thresholds, while an application uses one threshold whose false-positive and false-negative costs may differ.