Sub topic 5
Building a ROC curve by sweeping the threshold
This chapter assumes you know binary classification, the confusion matrix terms (true and false positives and negatives), basic NumPy, and that a model such as logistic regression outputs scores or probabilities. It also assumes you can compute TPR and FPR at one threshold, as covered in the previous chapter.
The idea
A single threshold gives a single confusion matrix, and so a single (FPR, TPR) point. A ROC curve is what you get when you try every useful threshold and plot all of those points. The x-axis is the false positive rate. The y-axis is the true positive rate.
Only thresholds that change a prediction matter. A prediction changes only when the threshold crosses one of the observed scores. So the distinct score values are the only thresholds you need.
A worked sweep
Take four examples with labels [0, 0, 1, 1] and scores [0.1, 0.4, 0.35, 0.8]. There are P = 2 positives and N = 2 negatives. Start with a threshold above every score, which predicts nothing positive and gives the point (0, 0). Then lower the threshold one distinct score at a time.
| Threshold | Predicted positive scores | TP | FP | TPR | FPR |
|---|---|---|---|---|---|
| above 0.8 | none | 0 | 0 | 0.0 | 0.0 |
| 0.8 | 0.8 | 1 | 0 | 0.5 | 0.0 |
| 0.4 | 0.8, 0.4 | 1 | 1 | 0.5 | 0.5 |
| 0.35 | 0.8, 0.4, 0.35 | 2 | 1 | 1.0 | 0.5 |
| 0.1 | all | 2 | 2 | 1.0 | 1.0 |
Each step lowers the threshold, so the set of predicted positives only grows. TPR and FPR therefore never decrease. The curve moves up when a positive joins the predicted set, and right when a negative joins.
The same sweep in code
This function follows the table exactly. It uses the rule "positive when score is at or above the threshold".
import numpy as np
from sklearn.metrics import auc
def roc_points(y_true, y_score):
y_true = np.asarray(y_true)
y_score = np.asarray(y_score)
n_pos = (y_true == 1).sum()
n_neg = (y_true == 0).sum()
fpr, tpr = [0.0], [0.0]
for t in np.unique(y_score)[::-1]:
pred = y_score >= t
tpr.append((pred & (y_true == 1)).sum() / n_pos)
fpr.append((pred & (y_true == 0)).sum() / n_neg)
return np.array(fpr), np.array(tpr)
y_true = np.array([0, 0, 1, 1])
y_score = np.array([0.1, 0.4, 0.35, 0.8])
fpr, tpr = roc_points(y_true, y_score)
print(fpr) # [0. 0. 0.5 0.5 1. ]
print(tpr) # [0. 0.5 0.5 1. 1. ]
print(auc(fpr, tpr)) # 0.75np.unique returns sorted values, and [::-1] reverses them to run from high to low. The starting point (0, 0) is added by hand. The final point is always (1, 1), because the lowest threshold predicts everything positive. The auc function applies the trapezoidal rule to the points. Its result is 0.75 here, which matches the area under the curve you would draw from the table.
Ties and common errors
- Tied scores move together. If a positive and a negative share a score, they cross the threshold at the same moment. The curve then has a diagonal segment instead of separate steps. Looping over distinct values, as above, handles this. Looping over every example one at a time does not, and gives a curve that depends on the sort order.
- Using
>instead of>=. The point for the highest score would then be (0, 0), and the top-scoring example would never be counted. - Passing hard labels as scores. If
y_scorecontains only 0 and 1, there is one real threshold. The curve has three points, and the AUC is crude. - Mixing up the axes. FPR belongs on the x-axis. Plotting TPR against thresholds gives a different curve.
Exercise
Scores are [0.9, 0.6, 0.6, 0.2] with labels [1, 0, 1, 0]. List the (FPR, TPR) points your sweep produces, starting from (0, 0), and say why the two 0.6 scores yield a single step.
Show answer
P = 2, N = 2. Threshold 0.9 gives TP=1, FP=0, so (0.0, 0.5). Threshold 0.6 adds one positive and one negative at once, giving TP=2, FP=1, so (0.5, 1.0). Threshold 0.2 gives (1.0, 1.0). The full list is (0,0), (0,0.5), (0.5,1), (1,1). The tied 0.6 scores cross the threshold together, so they produce one diagonal step instead of two axis-aligned steps.