Sub topic 5
Building a ROC curve by sweeping the threshold
This chapter assumes you know what a confusion matrix is, how true positive rate (TPR) and false positive rate (FPR) are defined, and how to use NumPy arrays. It builds on the previous chapters: a classifier gives each example a score, and a threshold turns scores into labels. Here you will see that moving the threshold traces a path through (FPR, TPR) space. That path is the ROC curve.
The idea in one sentence
A ROC curve is the set of (FPR, TPR) points you get by trying every useful decision threshold on the same scores and labels.
One threshold gives one confusion matrix and so one point. Lowering the threshold labels more examples positive. TPR and FPR can only stay the same or rise, so the path moves up and to the right.
A worked sweep by hand
Use four examples. The true labels are [0, 0, 1, 1] and the scores are [0.1, 0.4, 0.35, 0.8]. There are 2 positives and 2 negatives.
Predict positive when the score is at or above the threshold. Try each distinct score as a threshold, from highest to lowest.
| Threshold | Predicted positive | TP | FP | TPR = TP/2 | FPR = FP/2 |
|---|---|---|---|---|---|
| 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 four | 2 | 2 | 1.0 | 1.0 |
The curve connects (0, 0), (0, 0.5), (0.5, 0.5), (0.5, 1) and (1, 1). Every ROC curve starts at (0, 0), where nothing is predicted positive. It ends at (1, 1), where everything is.
Which thresholds matter? Only the observed score values. Any threshold between two neighbouring scores gives the same predictions as the lower neighbour. That is why you sweep over the distinct scores and not over a fine grid.
The algorithm
After sorting by descending score, the first k examples are exactly the ones predicted positive when the threshold equals the k-th score. So a cumulative sum of the sorted labels gives TP at every cut-off in one pass. A cumulative sum of the flipped labels gives FP.
Implementation from scratch
This version is O(n log n) because of the sort. The loop-per-threshold version is O(n × distinct scores), which gets slow on large test sets.
import numpy as np
from sklearn.metrics import auc, roc_curve
def roc_by_sorting(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()
order = np.argsort(-y_score, kind="mergesort")
s = y_score[order]
y = y_true[order]
tps = np.cumsum(y) # true positives if we cut after row i
fps = np.cumsum(1 - y) # false positives if we cut after row i
# Cut only where the score changes, plus after the last row.
distinct = np.where(np.diff(s))[0]
idx = np.r_[distinct, y.size - 1]
tpr = np.r_[0.0, tps[idx] / n_pos]
fpr = np.r_[0.0, fps[idx] / n_neg]
return fpr, tpr
y_true = np.array([0, 0, 1, 1])
y_score = np.array([0.1, 0.4, 0.35, 0.8])
fpr, tpr = roc_by_sorting(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.75
sk_fpr, sk_tpr, sk_thr = roc_curve(y_true, y_score, drop_intermediate=False)
print(np.allclose(fpr, sk_fpr), np.allclose(tpr, sk_tpr)) # True TrueThe drop_intermediate=False argument matters for the comparison. By default scikit-learn removes points that lie in the middle of a straight segment, because they add nothing to the picture. The curve is the same, but the arrays are shorter.
Tied scores
Tied scores are the most common source of bugs in hand-written ROC code. If two examples share a score, no threshold can separate them. They always flip from negative to positive together, so the curve must move by both of them in one step.
The np.diff(s) line handles this. It only allows a cut where the score actually changes. Here is an example with ties:
import numpy as np
from sklearn.metrics import roc_auc_score
y_true = np.array([0, 1, 0, 1, 1])
y_score = np.array([0.5, 0.5, 0.2, 0.9, 0.2])
fpr, tpr = roc_by_sorting(y_true, y_score)
print(fpr) # [0. 0. 0.5 1. ]
print(tpr) # [0. 0.33333333 0.66666667 1. ]
print(roc_auc_score(y_true, y_score)) # 0.666...This snippet reuses roc_by_sorting from the previous block, so run them in the same session. The points at score 0.5 and score 0.2 each move by one positive and one negative at once. The path between them is a diagonal segment, not a staircase.
If you cut between tied rows, the result depends on how the sort happened to order them. Your AUC would change with the input order, which makes no sense for a metric.
A model that outputs the same score for every example has one distinct score. The curve goes straight from (0, 0) to (1, 1), the diagonal, with AUC 0.5. Coarse scores cause the same effect in part. A decision tree with few leaves produces few distinct scores, so its ROC curve has few vertices.
What the thresholds array means
roc_curve returns a third array, thresholds. Entry i is the threshold that produced point i, under the rule "positive when score >= threshold". Scikit-learn adds a first threshold above every score so that the curve starts at (0, 0). Recent versions use np.inf for this entry. Older versions used max(score) + 1. Don't depend on that first value.
fpr, tpr, thresholds = roc_curve(y_true, y_score, drop_intermediate=False)
for f, t, th in zip(fpr, tpr, thresholds):
print(f"threshold={th} FPR={f:.2f} TPR={t:.2f}")Use this array when you need to turn a point on the curve back into a rule you can deploy. The chapter on choosing an operating threshold covers that.
Plotting the curve
ROC curves are drawn as step-like lines in an unscaled unit square. Draw the diagonal for reference and keep the axes equal so that the geometry stays honest.
import matplotlib.pyplot as plt
fpr, tpr = roc_by_sorting([0, 0, 1, 1], [0.1, 0.4, 0.35, 0.8])
fig, ax = plt.subplots(figsize=(4, 4))
ax.plot(fpr, tpr, marker="o", label="model")
ax.plot([0, 1], [0, 1], linestyle="--", label="chance")
ax.set_xlabel("False positive rate")
ax.set_ylabel("True positive rate")
ax.set_aspect("equal")
ax.legend()
plt.show()Properties worth knowing
- Monotone. Both coordinates never decrease as the threshold falls, so the curve never goes down or left.
- Rank-only. The curve depends on the order of the scores, not their values. Applying any strictly increasing function to the scores, such as a logarithm or a calibration map, leaves the curve unchanged.
- Class-conditional. TPR uses only the positives and FPR uses only the negatives. Changing the ratio of positives to negatives in the test set does not change the expected curve, as long as the score distributions within each class stay the same.
- Edge case. If the test set has no positives or no negatives, one of the denominators is zero. The curve is undefined. Scikit-learn warns and returns
nanvalues for the rates, androc_auc_scoreraises aValueError.
Common errors
- Passing hard labels instead of scores. If you give
roc_curvethe output ofpredict, there are only two distinct values. You get a single interior point and a curve with three vertices. Passpredict_proba(X)[:, 1]ordecision_function(X). - Using the wrong probability column.
predict_probareturns one column per class. Column 0 is the score for the negative class, so using it flips the curve and gives AUC below 0.5. - Scoring on training data. A flexible model can rank training examples almost perfectly. Build the curve on held-out data.
- Sweeping a fixed grid. A loop over
np.linspace(0, 1, 101)misses the real vertices and distorts the curve when the scores are bunched up.
Exercise
Scores are [0.9, 0.8, 0.7, 0.6] and labels are [1, 0, 1, 0]. List the (FPR, TPR) points of the ROC curve, from (0, 0) to (1, 1), and compute the area under it with the trapezoidal rule.
Show answer
There are 2 positives and 2 negatives. Sorted by score the labels are 1, 0, 1, 0. Cutting after each row gives: after 0.9, TP=1, FP=0, point (0, 0.5). After 0.8, TP=1, FP=1, point (0.5, 0.5). After 0.7, TP=2, FP=1, point (0.5, 1). After 0.6, TP=2, FP=2, point (1, 1). The full list is (0, 0), (0, 0.5), (0.5, 0.5), (0.5, 1), (1, 1). The area is 0 for the vertical step, then 0.5 × 0.5 = 0.25 for the flat piece at height 0.5, then 0 for the vertical step, then 0.5 × 1 = 0.5 for the flat piece at height 1. The total is 0.75.
Exercise
A model outputs only two distinct scores, 0.2 and 0.8, and both classes appear at each score. How many points does its ROC curve have, and why does the curve have no more than that?
Show answer
The curve has three points: (0, 0), the point after the threshold at 0.8, and (1, 1). Only the distinct score values are possible cut points, and tied examples always change label together, so no other threshold produces a new confusion matrix.