Sub topic 14
Quantifying uncertainty in AUC with a bootstrap
This chapter assumes you can compute a ROC curve and AUC with scikit-learn, as in the earlier chapters. It also assumes you are comfortable with NumPy indexing and random number generators. No statistics beyond the idea of a confidence interval is required.
Why a single AUC is not enough
An AUC computed on a test set is an estimate. Draw a different test set from the same population and you get a different number. Suppose two models score 0.84 and 0.86 on the same 200 test examples. You cannot tell from those numbers alone whether the gap reflects a real difference or sampling noise.
The noise comes mostly from how many positives and negatives you have. AUC is built from positive-negative pairs, but those pairs are not independent. A single unusual positive affects every pair it belongs to. A test set with 20 positives is therefore much noisier than the total pair count suggests.
A confidence interval reports this uncertainty. The bootstrap is a simple way to get one without deriving a formula.
The bootstrap idea
The bootstrap treats your test set as a stand-in for the population. You repeat the following many times:
- Draw n examples from the test set with replacement, where n is the test set size. Some examples appear several times and others not at all.
- Recompute the AUC on that resampled set, keeping each example's original label and score.
- Store the result.
After B repetitions you have B AUC values. Their spread approximates how much the AUC would vary across fresh test sets. The percentile method takes the 2.5th and 97.5th percentiles of those values as a 95% interval.
The model is not retrained. Only the fixed test scores are resampled, so this interval reflects test-set sampling noise and nothing else.
A complete example
First, build a model and hold-out scores. The data is synthetic and imbalanced, so there are fewer positives than negatives. Your exact numbers may differ slightly across library versions.
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=1000, n_features=20, n_informative=5,
weights=[0.8, 0.2], class_sep=0.8, random_state=0,
)
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)
scores = model.predict_proba(X_test)[:, 1]
print("Test AUC:", roc_auc_score(y_test, scores))
print("Positives in test set:", y_test.sum())Now the bootstrap itself. This version resamples positives and negatives separately, which is called a stratified bootstrap. It keeps the class counts fixed in every resample, so you never draw a resample with only one class.
def bootstrap_auc(y_true, y_score, n_boot=2000, alpha=0.05, seed=0):
rng = np.random.default_rng(seed)
y_true = np.asarray(y_true)
y_score = np.asarray(y_score)
pos_idx = np.flatnonzero(y_true == 1)
neg_idx = np.flatnonzero(y_true == 0)
aucs = np.empty(n_boot)
for b in range(n_boot):
pos_b = rng.choice(pos_idx, size=len(pos_idx), replace=True)
neg_b = rng.choice(neg_idx, size=len(neg_idx), replace=True)
idx = np.concatenate([pos_b, neg_b])
aucs[b] = roc_auc_score(y_true[idx], y_score[idx])
lo, hi = np.percentile(aucs, [100 * alpha / 2, 100 * (1 - alpha / 2)])
return aucs, lo, hi
aucs, lo, hi = bootstrap_auc(y_test, scores)
print(f"AUC = {roc_auc_score(y_test, scores):.3f}")
print(f"95% CI = [{lo:.3f}, {hi:.3f}]")
print(f"Bootstrap std = {aucs.std(ddof=1):.3f}")Read the output as a range of plausible AUC values for this model on data like this test set. A wide interval means the test set is too small to say much. A narrow one means the estimate is stable.
Stratified versus plain resampling
The plain version resamples row indices from all n rows at once. It is simpler, but the number of positives varies from resample to resample. That adds variation that a fixed test set does not have, and a rare resample may contain no positives, which makes roc_auc_score raise a ValueError. With rare positives, prefer the stratified version. If you use the plain version, skip any resample where y_true[idx] has only one class, and count how many you skipped.
Comparing two models with a paired bootstrap
Two separate intervals are a poor way to compare models. Both models are scored on the same examples, so their errors are correlated, and overlapping intervals can hide a real difference. Instead, resample the rows once per iteration and score both models on the same resample. Then bootstrap the difference.
def paired_bootstrap_diff(y_true, score_a, score_b, n_boot=2000, seed=0):
rng = np.random.default_rng(seed)
y_true = np.asarray(y_true)
score_a = np.asarray(score_a)
score_b = np.asarray(score_b)
pos_idx = np.flatnonzero(y_true == 1)
neg_idx = np.flatnonzero(y_true == 0)
diffs = np.empty(n_boot)
for b in range(n_boot):
idx = np.concatenate([
rng.choice(pos_idx, size=len(pos_idx), replace=True),
rng.choice(neg_idx, size=len(neg_idx), replace=True),
])
diffs[b] = (roc_auc_score(y_true[idx], score_a[idx])
- roc_auc_score(y_true[idx], score_b[idx]))
lo, hi = np.percentile(diffs, [2.5, 97.5])
return diffs, lo, hi
# Model B uses only the first five features.
model_b = LogisticRegression(max_iter=1000).fit(X_train[:, :5], y_train)
scores_b = model_b.predict_proba(X_test[:, :5])[:, 1]
diffs, lo, hi = paired_bootstrap_diff(y_test, scores, scores_b)
print(f"AUC(A) - AUC(B): 95% CI = [{lo:.3f}, {hi:.3f}]")
print("Interval excludes zero:", lo > 0 or hi < 0)If the interval for the difference excludes zero, the data supports a real difference in AUC on this population. If it includes zero, you cannot rule out that the models are equally good. The paired design usually gives a tighter interval than comparing two separate ones.
Choosing the number of resamples
Use at least 1,000 resamples for a 95% interval, and 2,000 to 10,000 if the interval ends matter. The percentile ends are tail estimates, so they need more draws than the mean would. Fix the seed so results are reproducible. Each iteration recomputes a full ROC AUC, which sorts the scores, so cost grows as B times n log n. That is fast for thousands of rows and slow for millions.
Limits of the bootstrap interval
- Only test-set noise is captured. Retraining on a different training sample would also move the AUC. To include that, repeat the whole pipeline, for example with cross-validation, and look at the spread across folds.
- Correlated rows break the assumption. If one patient, user, or device contributes many rows, resampling single rows makes the interval too narrow. Resample whole groups instead.
- Small samples give unreliable intervals. With fewer than about 10 to 20 positives, the percentile interval can be badly off. Near AUC = 1 the distribution is skewed against the boundary, and the interval can be too short.
- The interval is not a probability about the true AUC. It describes how the procedure behaves over repeated sampling, not where the true value lies.
Reporting the result
Report the point estimate, the interval, the confidence level, the number of positives and negatives, and the resampling scheme. For example: "AUC 0.81 (95% percentile bootstrap CI 0.74 to 0.87; 60 positives, 240 negatives; 2,000 stratified resamples)." Counting positives is the most useful detail, because it tells readers how much to trust the interval.
Exercise
A colleague compares two models on the same test set. Model A has AUC 0.86 with 95% CI [0.80, 0.91]. Model B has AUC 0.84 with 95% CI [0.78, 0.89]. They conclude the models are indistinguishable because the intervals overlap. What is wrong with this reasoning, and what should they do instead?
Show answer
Both models were scored on the same examples, so their AUCs are positively correlated, and overlapping separate intervals can hide a real difference. They should run a paired bootstrap. Resample the test rows once per iteration, compute AUC(A) minus AUC(B) on that same resample, and take the percentile interval of the differences. If that interval excludes zero, the difference is supported. If it includes zero, the data cannot separate the models.
Exercise
You run a plain (non-stratified) bootstrap on a test set with only 6 positives out of 300 rows, and some iterations crash. Why, and how would you fix it?
Show answer
In some resamples none of the 6 positives is drawn, so the resampled labels contain one class and rocaucscore raises a ValueError. The chance of this is about (1 - 6/300)^300, which is small but not zero for each draw. Fix it by using a stratified bootstrap that resamples positives and negatives separately, so every resample has exactly 6 positives and 294 negatives. Also note that with only 6 positives the interval will be wide and the percentile method may be unreliable.