Sub topic 3
Computing ROC and AUC with scikit-learn
Assume binary classification, confusion-matrix terms, NumPy, and predicted scores are familiar. A ROC curve evaluates every possible decision threshold. AUC summarizes the resulting ranking performance.
Compute ROC and AUC
roc_curve returns false positive rates (FPR), true positive rates (TPR), and thresholds. roc_auc_score computes the area under the ROC curve.
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)
auc_value = roc_auc_score(y_true, y_score)
print(auc_value) # 0.75Each threshold predicts class 1 when y_score >= threshold. The curve starts near (0, 0) and ends at (1, 1).
Choose an operating threshold
AUC does not choose the threshold used in production. One criterion is Youden’s J statistic:
j = tpr - fpr
best = np.argmax(j)
print(thresholds[best], tpr[best], fpr[best])This selects the point farthest above the diagonal. Use it only when false positives and false negatives have similar costs. In practice, choose a threshold from business, safety, or capacity requirements.
Imbalance and multiclass data
With heavy class imbalance, ROC AUC can look strong even when precision is poor. A precision-recall curve focuses on performance among predicted positives. Inspect it, and consider average precision, when the positive class is rare.
For multiclass classification, one-vs-rest AUC treats each class as positive against all others:
from sklearn.metrics import roc_auc_score
# proba has one probability column per class
auc_ovr = roc_auc_score(y_test, proba, multi_class="ovr")Limitations and uncertainty
AUC measures ranking across all thresholds. It does not measure calibration, expected cost, or performance at your chosen operating region. Curves can cross, so one AUC may hide a poor high-recall or low-FPR region.
A bootstrap estimates uncertainty by repeatedly resampling examples with replacement:
rng = np.random.default_rng(0)
values = []
for _ in range(2000):
i = rng.integers(0, len(y_true), len(y_true))
if len(np.unique(y_true[i])) == 2:
values.append(roc_auc_score(y_true[i], y_score[i]))
print(np.percentile(values, [2.5, 97.5]))The percentile range is a bootstrap confidence interval. It can be wide when the dataset has few positive or negative examples.
Exercise
Why can a high ROC AUC coexist with poor precision?
Show answer
ROC AUC averages ranking performance across thresholds, while precision is sensitive to the number of false positives and therefore to class prevalence.