AI Logic

Evaluation Metrics

ROC AUC

Updated:

Computing ROC AUC. On the left, a table that sorts 5 positives and 5 negatives by descending score and gives the true positive rate and false positive rate as the threshold is lowered; on the right, the ROC curve connecting those points with the area under it (AUC 0.84) and the diagonal representing random guessing; at the bottom, 21 of the 25 positive–negative pairs in which the positive has the higher score (0.84)

Background and overview

ROC AUC is an evaluation metric that expresses, as a single number from 0 to 1 and independently of any threshold, whether a binary classifier gives positive examples higher scores than negative ones. It is named for being the Area Under the Curve of the ROC curve (Receiver Operating Characteristic curve).

The ROC curve is drawn by moving the threshold for predicting positive and plotting the false positive rate on the horizontal axis and the true positive rate on the vertical axis.

TPR=TPTP+FN,FPR=FPFP+TN\mathrm{TPR} = \frac{TP}{TP + FN}, \qquad \mathrm{FPR} = \frac{FP}{FP + TN}

The true positive rate (TPR) is the fraction of positives correctly predicted as positive (the same as recall), and the false positive rate (FPR) is the fraction of negatives wrongly predicted as positive.

AUC has an intuitive reading: AUC equals the probability that, when one positive and one negative example are picked at random, the positive one receives the higher score. A value of 1 means positives and negatives are perfectly separated, and 0.5 is the same as random guessing.

The ROC curve originally came from signal detection theory, where it described the trade-off between hits and false alarms. It became widely used in medical diagnosis and was later adopted in machine learning. There is no single original paper for this metric; this article follows explanations such as Fawcett (2006).

Definition and procedure

The ROC curve and AUC are computed with the following steps.

  1. Assign a score (how positive it looks) to every evaluation example with the model. It need not be a probability; it is enough that the ordering is meaningful.
  2. Sort the examples by descending score.
  3. Lower the threshold one step at a time, starting above the highest score. Examples with scores at or above the threshold are predicted positive.
  4. For each threshold, compute TPR and FPR and plot the point (FPR,TPR)(\mathrm{FPR}, \mathrm{TPR}). Each positive passed moves the curve up and each negative passed moves it right, so the curve is a staircase from (0,0)(0, 0) to (1,1)(1, 1).
  5. Compute the area under the curve as a sum of trapezoid areas. This is the AUC.

In the example in the figure at the top (5 positives and 5 negatives), the AUC is 0.84. There are 5×5=255 \times 5 = 25 positive–negative pairs, and in 21 of them the positive has the higher score, so 21/25=0.8421 / 25 = 0.84, the same as the area. As a formula:

AUC=1n+n−∑i∈positives∑j∈negatives1[si>sj]\mathrm{AUC} = \frac{1}{n_+ n_-} \sum_{i \in \text{positives}} \sum_{j \in \text{negatives}} \mathbf{1}[s_i > s_j]

n+n_+ and n−n_- are the numbers of positives and negatives, and ss is the score. This relation is the same as the Wilcoxon rank test (the Mann–Whitney U statistic).

Points on the ROC curve have the following meanings. (0,1)(0, 1) is perfect classification: every positive is caught and no negative is predicted positive. The diagonal from the bottom left to the top right is random guessing (changing the fraction predicted positive only moves along the diagonal). A model below the diagonal ends up above it if its predictions are inverted, so the AUC of a real model should be at least 0.5.

When examples with the same score include both positives and negatives, advance over them in a single step, making the curve a diagonal segment. Processing them one at a time makes the staircase shape and the AUC depend on the order. Using a diagonal segment is equivalent to counting tied pairs as 0.5 pairs.

What it measures and its limitations

AUC measures how well positives and negatives are separated by the ranking of scores. Because it looks only at the ranking, it has the following properties.

  • Independent of the threshold: Performance across all thresholds can be evaluated together without choosing a specific threshold.
  • Independent of the score scale: Transforming scores in a rank-preserving way (a monotonically increasing transformation) does not change the AUC. Converting logits to probabilities with a sigmoid gives the same value.
  • Independent of the class ratio: TPR is computed only from positives and FPR only from negatives, so the ROC curve does not change when the positive-to-negative ratio of the test data changes. Accuracy, precision, and the F1 score use the counts of both positives and negatives, so their values change with the ratio.

It also has the following limitations.

  • With very many negatives, it can make practical performance look optimistic: Saito and Rehmsmeier (2015) point out that on data with far more negatives than positives, the visual appearance of the ROC curve can give a misleading impression of classification reliability. For example, even with an FPR of 0.01, if negatives outnumber positives 100 to 1, the number of false detections equals the total number of positives. They argue that the precision–recall curve, which looks at the fraction of predicted positives that are actually positive (precision), conveys the reality better on such data.
  • It does not reveal superiority in part of the curve: A model with a higher AUC can be worse than one with a lower AUC in some range (for example, the low-FPR range). For applications that use only the top few, look at the curve in that range directly or use a partial AUC restricted to the range.
  • It does not measure the correctness of confidence: Because it looks only at the ranking, it cannot tell whether scores match the actual probability of being positive (whether they are calibrated).
  • It is for two classes: For three or more classes, per-class AUCs are averaged according to a chosen aggregation (see the table below).
Multiclass extensionComputationEffect of class ratio
One-vs-rest (Provost and Domingos)Compute AUC with each class as positive and the rest as negative, then sum weighted by that class's shareAffected
One-vs-one (Hand and Till's M)Compute the binary AUC for every pair of classes and take the unweighted meanNot affected

Where it is used

ROC AUC is mainly used in the following situations.

  • Medical diagnosis: Before deciding which test value counts as positive, it compares the discriminative power of the tests themselves. This is a field where ROC curves have long been widely used.
  • Comparing binary classifiers: It compares the ranking ability of models without fixing a threshold. It is also convenient when the positive ratio can differ between testing and production, because the ROC curve does not change.
  • Anomaly detection and fraud detection: In applications that investigate cases in descending order of score, it summarizes the discriminative power of the model. However, negatives are extremely numerous, so precision–recall curves should be checked as well.

On the other hand, it is no longer used for evaluating object detection. According to the PASCAL VOC paper (Everingham et al. 2010), the VOC2006 classification task used ROC AUC, but because many methods exceeded 95% and differences became hard to see, it switched to mAP based on precision–recall curves from VOC2007 onward.

Comparison with similar metrics

The following table compares ROC AUC and related metrics from the same perspectives.

MetricWhat it comparesThresholdEffect of class ratioSuited to
ROC AUCArea under the TPR–FPR curve (probability that a positive ranks above a negative)IndependentNot affectedComparing the discriminative power of binary classifiers
Area under the precision–recall curve (AP)Area under the precision–recall curveIndependentAffected (the random baseline equals the positive rate)Data with few positives, retrieval, object detection (mAP)
F1 scoreHarmonic mean of precision and recall at one thresholdFixed to oneAffectedEvaluation at the operating threshold
AccuracyFraction classified correctly at one thresholdFixed to oneAffectedWhen classes are balanced

Rough guidelines for choosing among them:

  • To compare discriminative power without being swayed by the threshold or class ratio: Use ROC AUC.
  • When positives are rare and the hit rate among predicted positives matters: Use the precision–recall curve and its area (AP). The AP of a random classifier equals the positive rate, so read it against that baseline.
  • To know performance at the threshold actually used in operation: Look at precision, recall, and the F1 score at that point. Use AUC for comparisons before the threshold is decided.

PyTorch example

Show code
python
import torch


def roc_auc(scores, labels):
  """Compute binary ROC AUC as "the fraction of pairs in which the positive has a higher score than the negative" (ties count as 0.5).
  scores: (N,) scores (probabilities or logits; only the ranking is used)
  labels: (N,) 1 = positive, 0 = negative
  """
  pos = scores[labels == 1]
  neg = scores[labels == 0]
  diff = pos[:, None] - neg[None, :]  # all (positive, negative) pairs. Uses O(n+ × n−) memory, so for small data
  wins = (diff > 0).float().sum() + 0.5 * (diff == 0).float().sum()
  return (wins / (pos.numel() * neg.numel())).item()


# Example from the figure at the top: 5 positives, 5 negatives
scores = torch.tensor([0.95, 0.90, 0.82, 0.75, 0.68, 0.55, 0.47, 0.40, 0.30, 0.20])
labels = torch.tensor([1, 1, 0, 1, 1, 0, 1, 0, 0, 0])
print(roc_auc(scores, labels))  # 0.84

# torchmetrics: if preds fall outside [0, 1], they are treated as logits and passed through a sigmoid (AUC uses only the ranking, so the result is the same)
# thresholds=None computes it exactly. Passing an integer gives an approximation over binned thresholds (constant memory)
from torchmetrics.classification import BinaryAUROC

metric = BinaryAUROC(thresholds=None)
print(metric(scores, labels))  # tensor(0.8400)

# scikit-learn: pass as y_score the probability or score of "the class with the larger label (positive)"
# for multiclass, always specify multi_class="ovr" (one-vs-rest) or "ovo" (one-vs-one, Hand and Till)
from sklearn.metrics import roc_auc_score, roc_curve

print(roc_auc_score(labels.numpy(), scores.numpy()))  # 0.84
fpr, tpr, thresholds = roc_curve(labels.numpy(), scores.numpy())  # when plotting the curve's points

FAQ

Q. What AUC counts as a good model?
A.

There is no fixed threshold, because it varies greatly with the difficulty of the task. Since 0.5 is random guessing and 1 is perfect classification, first see how far above 0.5 it is, then judge by comparing with existing models on the same data.

Q. When does AUC fall below 0.5?
A.

When the direction of the scores is reversed. If a model tends to give positives lower scores, inverting its predictions turns its AUC into 1 − AUC, which is above 0.5. Check whether the positive label or the sign of the scores has been mixed up.

Q. Can ROC AUC be used on data with very few positives?
A.

Yes, but do not rely on it alone. The ROC curve does not depend on the class ratio, but when negatives are extremely numerous, the number of false detections can be large even if the false positive rate is small. Check the precision–recall curve and its area (AP) as well.

References

  1. Fawcett, T. (2006). An introduction to ROC analysis. Pattern Recognition Letters, 27(8), 861–874.
  2. Saito, T., & Rehmsmeier, M. (2015). The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets. PLOS ONE, 10(3), e0118432.
  3. Everingham, M., et al. (2010). The PASCAL Visual Object Classes (VOC) Challenge. International Journal of Computer Vision, 88(2), 303–338 (Section 4.2: switch from ROC AUC to AP).
  4. scikit-learn developers. sklearn.metrics.roc_auc_score (API reference).
  5. Lightning AI. torchmetrics.classification.BinaryAUROC (API reference).