Sub topic 9
Computing ROC and AUC with scikit-learn
This chapter assumes you can read a confusion matrix, know that a classifier can output a score or probability for each example, and can write basic Python and NumPy. You already know that a ROC curve comes from sweeping a threshold. Here you will get the curve and the area from scikit-learn and check them against the definition.
The two functions
sklearn.metrics provides two main functions:
roc_curve(y_true, y_score)returns three arrays:fpr,tpr, andthresholds.roc_auc_score(y_true, y_score)returns the area under the curve as one number.
import numpy as np
from sklearn.metrics import roc_curve, roc_auc_score, auc
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.75
print(auc(fpr, tpr)) # 0.75Each index is one operating point. At thresholds[2], which is 0.4, the classifier predicts positive when the score is at least 0.4. That gives a TPR of 0.5 and an FPR of 0.5. The first threshold is inf in scikit-learn 1.3 and later, so the curve starts at (0, 0) because nothing is predicted positive. Older versions used the maximum score plus one.
auc(x, y) is a general trapezoidal-rule integrator. It gives the same answer as roc_auc_score when you pass it the curve points. roc_auc_score is the shorter route when you only need the number.
Using a real model
Pass scores, not predicted labels. For a probabilistic model, take the column for the positive class from predict_proba. For margin-based models such as an SVM, use decision_function.
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import RocCurveDisplay, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(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 = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
scores = model.predict_proba(X_test)[:, 1] # column for class 1
print(roc_auc_score(y_test, scores)) # close to 1 on this dataset
RocCurveDisplay.from_predictions(y_test, scores)
plt.show()RocCurveDisplay.from_predictions draws the curve and writes the AUC in the legend. The from_estimator method does the same from a fitted model and test data.
Verify the number by hand
Checking scikit-learn against the definition catches mistakes in how you passed the inputs. The AUC equals the fraction of positive-negative pairs where the positive example scores higher, with ties counting 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 of the four pairs are ranked correctly: 0.35 beats 0.1, and 0.8 beats both 0.1 and 0.4. The pair (0.35, 0.4) is ranked wrongly. That gives 3/4.
Common errors
- Passing hard labels.
roc_auc_score(y_test, model.predict(X_test))runs without error. It collapses the curve to a single point and gives a misleading value. Always pass scores. - Using the wrong column.
predict_probareturns one column per class, ordered as inmodel.classes_. Taking column 0 gives the score for the negative class, so the AUC becomes1 - AUC. - Unusual labels. If the positive class is not 1, such as the string
"spam", passpos_label="spam"toroc_curve. - A single class in
y_true. The curve is undefined without both classes. scikit-learn raises an error or warning. - Scoring on training data. The AUC is optimistic. Compute it on held-out data or with cross-validation, using
scoring="roc_auc".
Exercise
A teammate computes roc_auc_score(y_test, model.predict_proba(X_test)[:, 0]) for a binary model whose classes_ are [0, 1] and gets 0.08. What went wrong, and what is the correct AUC likely to be?
Show answer
Column 0 holds the probability of class 0, but the positive class is 1. Those scores rank the examples in reverse order, so the AUC is 1 minus the true value. The correct AUC is likely near 0.92, found by using [:, 1].