Sub topic 9
Computing ROC and AUC with scikit-learn
This chapter assumes you know what a ROC curve and AUC are. It also assumes you can read a confusion matrix, write basic Python and NumPy, and get probabilities or scores from a model such as logistic regression. It covers the scikit-learn functions that compute them, what each one returns, and the mistakes that produce wrong numbers without raising an error.
The functions you need
scikit-learn puts ROC tools in sklearn.metrics.
| Function | Returns | Use it for |
|---|---|---|
| `roc_curve(y_true, y_score)` | `fpr`, `tpr`, `thresholds` | The points of the curve |
| `roc_auc_score(y_true, y_score)` | One float | The area under the curve |
| `auc(x, y)` | One float | Trapezoidal area under any curve, such as `fpr` and `tpr` |
| `RocCurveDisplay.from_predictions(...)` | A plot object | Drawing the curve |
All of them take scores, not predicted labels. A score is any number where a higher value means "more likely positive". It need not be a probability.
A first run
Start with the four-example set used earlier in this tutorial.
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(fpr) # [0. 0. 0.5 0.5 1. ]
print(tpr) # [0. 0.5 0.5 1. 1. ]
print(thresholds) # [inf 0.8 0.4 0.35 0.1]
print(roc_auc_score(y_true, y_score)) # 0.75Each index describes one operating point. Index 1 means "predict positive when the score is at least 0.8". That gives a TPR of 0.5 and an FPR of 0.
The first threshold is inf in scikit-learn 1.3 and later. It stands for "predict nothing positive", which gives the point (0, 0). Older versions used max(score) + 1 there, which would be 1.8 here. Do not use that first threshold as a real cutoff.
How the pieces fit together
Getting the right score from a model
Which model method you call decides whether the result is correct. The three common choices are:
predict_proba(X)[:, 1]gives the estimated probability of the positive class. The column index matters. Column order followsmodel.classes_.decision_function(X)gives a signed distance or raw margin. It works for ROC because the metric only uses the ordering of scores. SVMs often offer only this.predict(X)gives hard 0 or 1 labels. Do not pass these.
Passing hard labels collapses the curve to a single interior point. You get a number, but it measures one threshold, not the ranking quality. The call raises no error, so you must check this yourself.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
X, y = make_classification(
n_samples=2000, n_features=10, n_informative=4,
weights=[0.8, 0.2], random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=0
)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
margin = model.decision_function(X_test)
labels = model.predict(X_test)
print("proba :", roc_auc_score(y_test, proba))
print("margin:", roc_auc_score(y_test, margin)) # same as proba
print("labels:", roc_auc_score(y_test, labels)) # usually lower, and wrong to reportThe first two values match. The sigmoid that turns a margin into a probability is strictly increasing, so it does not change the order of the examples. The labels value is usually lower, and it should not be reported as the model's AUC.
Plotting the curve
RocCurveDisplay.from_predictions draws the curve from labels and scores. The plot_chance_level argument needs scikit-learn 1.3 or later. It adds the diagonal for a random classifier.
import matplotlib.pyplot as plt
from sklearn.metrics import RocCurveDisplay
RocCurveDisplay.from_predictions(
y_test, proba, name="logistic regression", plot_chance_level=True
)
plt.show()Label the axes in your own report if the audience may not know the defaults. The display uses "False Positive Rate" on x and "True Positive Rate" on y.
Verifying scikit-learn by hand
Check a library result against a direct computation at least once. Here is a version that builds the curve by predicting positive at or above each distinct threshold, then integrates with the trapezoidal rule.
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(auc(fpr, tpr)) # 0.75The rank-based definition gives the same area. It counts the fraction of positive-negative pairs where the positive scores higher, and ties count as one half.
import numpy as np
y_true = np.array([0, 0, 1, 1])
y_score = np.array([0.1, 0.4, 0.35, 0.8])
pos = y_score[y_true == 1]
neg = y_score[y_true == 0]
diff = pos[:, None] - neg[None, :]
auc_rank = ((diff > 0).sum() + 0.5 * (diff == 0).sum()) / diff.size
print(auc_rank) # 0.75Three routes agree: roc_auc_score, the trapezoid area, and the pair count. If your own pipeline disagrees with all three, suspect the inputs before the metric.
Details of `roc_curve`
`drop_intermediate`
By default, roc_curve drops points that lie on a straight segment between their neighbors. This shortens the arrays and does not change the plot or the AUC. If you need one point per distinct threshold, for example to look up the exact TPR at a given cutoff, pass drop_intermediate=False.
Ties
Examples with equal scores share one threshold, so they move together. The curve then has a diagonal segment where a tied group contains both classes. This is the same as counting tied pairs as one half in the rank formula. Models that output coarse scores, such as a shallow decision tree, produce few distinct thresholds and a blocky curve.
Label conventions
By default, roc_curve treats labels {0, 1} or {-1, 1} as binary with 1 as positive. For other labels, such as strings, set pos_label explicitly. Otherwise scikit-learn raises an error, or in some cases picks a different class as positive than you intended.
from sklearn.metrics import roc_curve
y = ["no", "no", "yes", "yes"]
score = [0.1, 0.4, 0.35, 0.8]
fpr, tpr, thr = roc_curve(y, score, pos_label="yes")
print(tpr) # [0. 0.5 0.5 1. 1. ]roc_auc_score has no pos_label argument for binary targets. It takes the greater label, as ordered by numpy.unique, as positive. Encode labels as 0 and 1 first if you want no ambiguity.
One class only
If y_true contains only one class, AUC is undefined and roc_auc_score raises a ValueError. This often happens with a small validation fold on rare-event data. Use stratified splits.
Picking a threshold from the output
The thresholds array lines up index for index with fpr and tpr. That makes it easy to apply a stated criterion. Youden's J statistic is TPR minus FPR. It picks the point farthest above the diagonal. That is a reasonable choice when false positives and false negatives cost about the same.
import numpy as np
from sklearn.metrics import roc_curve
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)
j = tpr - fpr
best = np.argmax(j)
print(thresholds[best], tpr[best], fpr[best]) # 0.8 0.5 0.0Here J is 0.5 at both threshold 0.8 and threshold 0.35, and argmax returns the first one. Ties like this are common on small data. State which one you chose and why.
Multiclass and cross-validation
For more than two classes, pass one probability column per class and set multi_class. With "ovr", each class is scored against all the others, and the per-class AUCs are averaged.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0, stratify=y
)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
proba = model.predict_proba(X_test)
print(roc_auc_score(y_test, proba, multi_class="ovr"))The rows of proba must sum to 1, which predict_proba guarantees. To score a model during cross-validation, use the built-in scorer name:
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X, y, cv=5, scoring="roc_auc_ovr")
print(scores.mean(), scores.std())For a binary problem, use scoring="roc_auc". The scorer calls predict_proba or decision_function for you.
Common errors
- Passing
predict()output. The call succeeds and the AUC is wrong. Pass scores. - Using the wrong probability column.
predict_proba(X)[:, 0]is the probability of the first class. Using it gives an AUC of about 1 minus the true value. An AUC well below 0.5 usually means flipped scores or flipped labels. - Computing AUC on training data. Overfit models look excellent there. Use held-out data or cross-validation.
- Reading
thresholds[0]as a real cutoff. It isinformax + 1. - Averaging fold curves by averaging thresholds. Folds have different threshold sets. Interpolate TPR over a common FPR grid instead.
Exercise
A teammate reports an AUC of 0.91 from roc_auc_score(y_test, model.predict(X_test)) for a binary classifier. What is wrong with this call, and what should they pass instead?
Show answer
predict returns hard 0 or 1 labels, so the curve has only one interior point and the number reflects a single threshold, not the ranking of examples. They should pass continuous scores, such as model.predict_proba(X_test)[:, 1] or model.decision_function(X_test), and recompute.
Exercise
Using roc_curve(y_true, y_score) output, write one line of NumPy that returns the TPR at the point with the smallest FPR that has a TPR of at least 0.9. Assume fpr and tpr are already computed.
Show answer
tpr[np.argmax(tpr >= 0.9)]. Because fpr is non-decreasing, the first index where tpr >= 0.9 has the smallest FPR among those points. np.argmax on a boolean array returns the first True. Check first that (tpr >= 0.9).any() is true, since argmax returns 0 when there is no True.