ROC Curves & AUC
A logistic model, or a single biomarker, produces a score. How well does that score separate patients who have the disease from patients who do not? The ROC curve shows the answer at every possible cutoff, and its area, the AUC, condenses the curve into one number. This page scores a biomarker against disease status in R and Python.
When to use ROC and AUC
Section titled “When to use ROC and AUC”Use them to judge a continuous score or a classifier on a binary outcome. The AUC measures how well the score ranks the two classes, and it does not depend on a cutoff, which makes it a common way to compare biomarkers or models.
Get the data
Section titled “Get the data”Download roc_data.csv into your working directory. The invented table has 150 rows, one per patient sample, and two columns. score is a continuous biomarker score, and disease is 1 for a diseased sample and 0 for a healthy one.
When pROC loads, it reports that it masks cov, smooth and var from the stats package. This page uses none of the three.
library(pROC)library(ggplot2)
samples <- read.csv("roc_data.csv")dir.create("outputs", showWarnings = FALSE)cat(sprintf("%d samples: %d diseased, %d healthy\n", nrow(samples), sum(samples$disease == 1), sum(samples$disease == 0)))150 samples: 71 diseased, 79 healthyfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom sklearn.metrics import roc_auc_scorefrom sklearn.metrics import roc_curve
samples = pd.read_csv("roc_data.csv")labels = samples["disease"].to_numpy()scores = samples["score"].to_numpy()output = Path("outputs")output.mkdir(exist_ok=True)print(f"{len(samples)} samples: {(labels == 1).sum()} diseased, " f"{(labels == 0).sum()} healthy")150 samples: 71 diseased, 79 healthyCompute the AUC and its interval
Section titled “Compute the AUC and its interval”The AUC is the probability that the score ranks a random diseased sample above a random healthy one. A value of 1.0 means that every diseased sample scores above every healthy sample, and 0.5 means that the score ranks no better than a coin. A value below 0.5 is possible. It means that the score ranks in the wrong direction, so healthy samples tend to score higher.
By default, roc() in pROC chooses the direction of the comparison from the medians of the two groups and prints a message about it. A score that ranks backwards then still shows an AUC above 0.5. Set both arguments yourself: levels = c(0, 1) names the healthy class first, and direction = "<" states that healthy samples score lower than diseased ones.
ci.auc() returns the DeLong interval by default, an analytic interval built from the standard error of the AUC. roc_auc_score() in scikit-learn returns the AUC alone, so the Python tab draws a bootstrap percentile interval with a fixed seed. The helper resamples the diseased and the healthy samples separately, which keeps both class sizes fixed in every resample. ci.auc() offers the same stratified bootstrap, and the R tab prints it for comparison.
roc_obj <- roc(samples$disease, samples$score, levels = c(0, 1), direction = "<")delong_ci <- ci.auc(roc_obj)set.seed(2026)bootstrap_ci <- ci.auc(roc_obj, method = "bootstrap", boot.n = 2000)cat(sprintf("AUC = %.3f\n", auc(roc_obj)))cat(sprintf("DeLong 95%% CI: %.3f to %.3f\n", delong_ci[1], delong_ci[3]))cat(sprintf("Bootstrap 95%% CI: %.3f to %.3f\n", bootstrap_ci[1], bootstrap_ci[3]))AUC = 0.832DeLong 95% CI: 0.766 to 0.898Bootstrap 95% CI: 0.765 to 0.893def bootstrap_auc_interval(labels, scores, n_resamples=2000, seed=2026): """Compute a stratified bootstrap percentile interval for the AUC.
The positive and the negative class are resampled separately, so every resample keeps the class sizes of the data.
Args: labels: Array of 0 and 1, with 1 for the positive class. scores: Array of scores, in the order of ``labels``. n_resamples: Number of bootstrap resamples. seed: Seed of the random number generator.
Returns: The 2.5th and 97.5th percentiles of the resampled AUC values. """ rng = np.random.default_rng(seed) cases = scores[labels == 1] controls = scores[labels == 0] resampled_labels = np.repeat([1, 0], [len(cases), len(controls)]) resampled_aucs = np.empty(n_resamples) for i in range(n_resamples): resampled_scores = np.concatenate([ rng.choice(cases, size=len(cases)), rng.choice(controls, size=len(controls)), ]) resampled_aucs[i] = roc_auc_score(resampled_labels, resampled_scores) return np.percentile(resampled_aucs, [2.5, 97.5])
auc = roc_auc_score(labels, scores)bootstrap_ci = bootstrap_auc_interval(labels, scores)print(f"AUC = {auc:.3f}")print(f"Bootstrap 95% CI: {bootstrap_ci[0]:.3f} to {bootstrap_ci[1]:.3f}")AUC = 0.832Bootstrap 95% CI: 0.763 to 0.893Both languages give an AUC of 0.832: the score ranks a diseased sample above a healthy one in about 83% of the possible pairs. The DeLong interval runs from 0.766 to 0.898, so the data are compatible with a ranking probability from about 77% to 90%.
The bootstrap limits differ from the DeLong limits for two reasons. The first is the shape of the interval. The DeLong interval is the AUC plus or minus 1.96 standard errors, so both limits lie 0.066 from 0.832. The percentile interval reads its limits from the resampled AUC values. Their distribution has a longer tail toward low values, because no AUC can exceed 1.0, and the upper limit lands lower, at 0.893.
The second reason is the random draw. The R and the Python bootstrap use the same method with different random numbers, and their lower limits are 0.765 and 0.763. More resamples shrink that gap. Name the method when you report the interval, because a reader who recomputes it with the other method gets different limits.
Draw the ROC curve
Section titled “Draw the ROC curve”The curve plots the true positive rate, which is the sensitivity, against the false positive rate, which is 1 minus the specificity, as the cutoff moves from strict to lenient. A curve that rises steeply toward the top left corner separates the classes well. The dashed diagonal is a score that ranks at random.
pROC stores the curve from the lowest cutoff to the highest, so the R code reverses both vectors to draw the path from the bottom left.
roc_points <- data.frame(fpr = rev(1 - roc_obj$specificities), tpr = rev(roc_obj$sensitivities))roc_plot <- ggplot(roc_points, aes(fpr, tpr)) + geom_abline(linetype = "dashed", color = "grey60") + geom_path(color = "#1f4e5f", linewidth = 1) + labs(x = "False positive rate", y = "True positive rate", title = sprintf("ROC curve (AUC = %.3f)", auc(roc_obj))) + coord_equal() + theme_minimal(base_size = 13)ggsave("outputs/roc-r.png", roc_plot, width = 5, height = 4, dpi = 150)
fpr, tpr, thresholds = roc_curve(labels, scores)
figure, axes = plt.subplots(figsize=(5, 4))axes.plot([0, 1], [0, 1], linestyle="--", color="grey")axes.plot(fpr, tpr, color="#1f2a44", linewidth=1.5)axes.set_xlabel("False positive rate")axes.set_ylabel("True positive rate")axes.set_title(f"ROC curve (AUC = {auc:.3f})")axes.set_aspect("equal")figure.tight_layout()figure.savefig(output / "roc-python.png", dpi=150)plt.close(figure)
Choose a cutoff
Section titled “Choose a cutoff”The AUC judges the score across all cutoffs. To classify a patient you must pick one, and every choice trades missed cases against false alarms. Youden’s index is sensitivity plus specificity minus 1, and the cutoff that maximizes it is a common default. The code finds that cutoff and then evaluates a second, stricter cutoff of 5 for comparison.
metrics <- c("threshold", "sensitivity", "specificity")youden_cutoff <- coords(roc_obj, "best", best.method = "youden", ret = metrics)strict_cutoff <- coords(roc_obj, 5, input = "threshold", ret = metrics)cutoffs <- rbind(youden_cutoff, strict_cutoff)cutoffs$youden_index <- cutoffs$sensitivity + cutoffs$specificity - 1cat(sprintf("Cutoff %g: sensitivity %.3f, specificity %.3f, Youden %.3f\n", cutoffs$threshold, cutoffs$sensitivity, cutoffs$specificity, cutoffs$youden_index), sep = "")Cutoff 4.3085: sensitivity 0.887, specificity 0.646, Youden 0.533Cutoff 5: sensitivity 0.732, specificity 0.797, Youden 0.530def sensitivity_specificity(labels, scores, cutoff): """Classify the scores at one cutoff and score the classification.
Args: labels: Array of 0 and 1, with 1 for the positive class. scores: Array of scores, in the order of ``labels``. cutoff: A sample is called positive when its score is at or above this value.
Returns: A tuple of the sensitivity and the specificity. """ called_positive = scores >= cutoff sensitivity = called_positive[labels == 1].mean() specificity = 1 - called_positive[labels == 0].mean() return sensitivity, specificity
youden_cutoff = thresholds[np.argmax(tpr - fpr)]for cutoff in (youden_cutoff, 5): sensitivity, specificity = sensitivity_specificity(labels, scores, cutoff) print(f"Cutoff {cutoff:g}: sensitivity {sensitivity:.3f}, " f"specificity {specificity:.3f}, " f"Youden {sensitivity + specificity - 1:.3f}")Cutoff 4.322: sensitivity 0.887, specificity 0.646, Youden 0.533Cutoff 5: sensitivity 0.732, specificity 0.797, Youden 0.530The two tabs report different cutoffs for the same classification. pROC places each cutoff midway between two neighboring scores and reports 4.3085. scikit-learn reports 4.322, the lowest score that is still called positive. No sample lies between the two values, so both give a sensitivity of 0.887 and a specificity of 0.646. This cutoff finds 88.7% of the diseased samples and clears 64.6% of the healthy ones.
The cutoff of 5 has almost the same Youden index, 0.530 against 0.533, and it describes a different test: sensitivity falls to 0.732 and specificity rises to 0.797. Youden’s index gives the miss rate among the diseased and the false alarm rate among the healthy equal weight, whatever the prevalence, so it barely separates these two cutoffs. The cost of each error should set the cutoff. A screening test that feeds a cheap confirmatory assay can accept false alarms to miss fewer cases. A test that sends patients to an invasive procedure needs the higher specificity.
A cutoff that maximizes an index on these 150 samples also fits their noise, so its sensitivity and specificity usually look worse in new samples. Confirm both in an independent set before you report them as the performance of the test.
Once the cutoff is fixed, sensitivity and specificity are fixed, and the next question is what a positive result means for one patient. The Bayes’ theorem tutorial calculates positive predictive value from prevalence, sensitivity, and the false positive rate at a fixed threshold. Its count table explains why predictive value also depends on the tested population.
Pitfalls
Section titled “Pitfalls”- A high AUC does not choose a cutoff, and two scores with the same AUC can behave differently at the cutoff you use. Report sensitivity and specificity at the chosen cutoff next to the AUC.
- The AUC ignores prevalence. When the disease is rare, most positive calls can be false at an AUC that looks high. A precision-recall curve shows that problem, and a ROC curve does not.
- An AUC computed on the data that trained a model is optimistic. The score on this page is one measured biomarker, so nothing was fitted. For a score from a fitted model, compute the AUC on samples that the model did not see.
- An automatic direction hides a score that ranks backwards. Keep
levelsanddirectionfixed in pROC, so that an AUC below 0.5 stays visible.
Key points
Section titled “Key points”- The AUC is the probability that the score ranks a diseased sample above a healthy one. A random ranking gives 0.5, a perfect ranking gives 1.0, and a value below 0.5 means that the score ranks backwards.
- Report the AUC with an interval, and name the method, DeLong or bootstrap.
- The ROC curve shows the trade between sensitivity and specificity at every cutoff.
- Youden’s index gives a default cutoff. The cost of a missed case and the cost of a false alarm should set the cutoff you use.
- For a rare outcome, add a precision-recall curve.
Scientific references
Section titled “Scientific references”Robin and colleagues, 2011 describe pROC, which analyzes and compares ROC curves.
DeLong, DeLong, and Clarke-Pearson, 1988 describe the nonparametric variance estimate of the AUC behind the DeLong interval.
Further reading
Section titled “Further reading”The pROC documentation page links the package manual and FAQ for R curve comparisons and confidence intervals. The scikit-learn ROC reference explains positive-class labels, score inputs, and returned thresholds.
The scikit-learn AUC reference documents how scores determine the area. The Logistic Regression lesson shows how a binary model produces those scores.