TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › ROC-AUC, PR-AUC and Average Precision

ROC-AUC, PR-AUC and Average Precision

Most classifiers do not output a class; they output a score (a probability, a margin, a log-odds) and a threshold turns it into a decision. Precision and recall from the previous lesson describe one threshold. But when you compare two models, you often do not know the threshold yet: the product team will set it later, or it will change with the season. Then you want a metric of the ranking itself: how well does the score put positives above negatives, over all thresholds? The ROC curve and the precision-recall curve answer that, each summarised by an area.

The lab

Below, 1000 examples get scores: negatives from N(0,1)\mathcal{N}(0, 1), positives from N(d,1)\mathcal{N}(d, 1), with 30 % positives. Everything at or above the threshold is predicted positive. Drag the threshold and watch the confusion matrix, the current point on the ROC curve (left) and on the PR curve (right). At the default threshold of 1 the readouts show precision 0.612, recall 0.663 and a false positive rate of 0.180; the areas, ROC AUC 0.844 and AP 0.710, do not move with the threshold because they summarise every threshold at once. Increase the separation dd and both curves bend towards the ideal corner.

05005scorecountScores by true classpositive →← negativenegativepositivepredicted +predicted −actual posactual neg199TP101FN126FP574TNprecision 0.612 recall 0.663 F1 0.6370.00.51.00.00.51.0false positive rateTPRROC curveAUC 0.844- - chance0.00.51.00.00.51.0recallprecisionPrecision-recallAP 0.710- - chance

ROC curve and its area

Sort the examples by score, highest first, and lower the threshold one example at a time. Each step adds one predicted positive: if it is a real positive, the true positive rate TPR=TPP\text{TPR} = \frac{TP}{P} goes up by 1P\frac{1}{P}; if it is a negative, the false positive rate FPR=FPN\text{FPR} = \frac{FP}{N} goes up by 1N\frac{1}{N}. The path from (0,0)(0, 0) to (1,1)(1, 1) is the ROC curve (receiver operating characteristic). A random score follows the diagonal; a perfect one goes straight up, then right.

Its area has a second meaning that is easier to remember:

AUC=P(s+>s−)+12P(s+=s−)=1P⋅N∑i∈pos∑j∈neg([si>sj]+12[si=sj])\text{AUC} = P(s^{+} > s^{-}) + \tfrac{1}{2} P(s^{+} = s^{-}) = \frac{1}{P \cdot N} \sum_{i \in \text{pos}} \sum_{j \in \text{neg}} \Big( [s_i > s_j] + \tfrac{1}{2} [s_i = s_j] \Big)

the probability that a randomly chosen positive gets a higher score than a randomly chosen negative. That is the Mann-Whitney UU statistic divided by P⋅NP \cdot N, and it can be computed from ranks in O(nlog⁡n)O(n \log n):

AUC=R+−P(P+1)/2P⋅N\text{AUC} = \frac{R_{+} - P(P + 1)/2}{P \cdot N}

where R+R_{+} is the sum of the ranks (1 = lowest score, ties get their average rank) of the positives.

python · try it yourself
import numpy as np
from scipy.stats import rankdata
from sklearn.metrics import roc_auc_score, roc_curve

y = np.array([1, 1, 0, 1, 0, 1, 0, 0, 1, 0])
s = np.array([0.95, 0.85, 0.80, 0.70, 0.55, 0.45, 0.40, 0.30, 0.20, 0.10])
P, N = y.sum(), len(y) - y.sum()

# sweep the threshold down through the sorted scores (no ties here)
order = np.argsort(-s)
tpr = np.r_[0, np.cumsum(y[order]) / P]
fpr = np.r_[0, np.cumsum(1 - y[order]) / N]
print("FPR:", fpr.round(2).tolist())
print("TPR:", tpr.round(2).tolist())

auc_trapezoid = np.sum(np.diff(fpr) * (tpr[1:] + tpr[:-1]) / 2)
pairs = np.mean([[1.0 if a > b else 0.5 if a == b else 0.0 for b in s[y == 0]] for a in s[y == 1]])
ranks = rankdata(s)
auc_ranks = (ranks[y == 1].sum() - P * (P + 1) / 2) / (P * N)
print(f"AUC trapezoid {auc_trapezoid:.3f}  pairs {pairs:.3f}  ranks {auc_ranks:.3f}  sklearn {roc_auc_score(y, s):.3f}")
f, t, thr = roc_curve(y, s)
print("sklearn keeps only the corners:", len(f), "points, thresholds", thr[1:].round(2).tolist())
FPR: [0.0, 0.0, 0.0, 0.2, 0.2, 0.4, 0.4, 0.6, 0.8, 0.8, 1.0]
TPR: [0.0, 0.2, 0.4, 0.4, 0.6, 0.6, 0.8, 0.8, 0.8, 1.0, 1.0]
AUC trapezoid 0.720  pairs 0.720  ranks 0.720  sklearn 0.720
sklearn keeps only the corners: 10 points, thresholds [0.95, 0.85, 0.8, 0.7, 0.55, 0.45, 0.3, 0.2, 0.1]

The three ways of computing the area agree: 0.720. Counting pairs makes it concrete: of the 5⋅5=255 \cdot 5 = 25 positive-negative pairs, the positive scores higher in 18, and 18/25=0.7218/25 = 0.72. The curve has a vertical step for every positive and a horizontal step for every negative. roc_curve drops points that lie on a straight segment between their neighbours (here the one at threshold 0.40), which does not change the area.

Precision-recall curve and average precision

The PR curve plots precision against recall for every threshold. It ignores true negatives, so it describes how the model does on the positives, which is what you care about when they are rare. Its summary is average precision, the precision at each threshold weighted by how much recall increased there:

AP=∑n(Rn−Rn−1) Pn\text{AP} = \sum_{n} (R_n - R_{n-1}) \, P_n

This is a step-wise sum, not the trapezoid rule. scikit-learn's average_precision_score computes exactly this; auc(recall, precision) (the trapezoid) interpolates linearly between points, but precision does not change linearly between thresholds, so the trapezoid can be off in either direction (scikit-learn's documentation warns that it can be too optimistic). "PR-AUC" in papers can mean either, so say which one you report.

python · try it yourself
import numpy as np
from sklearn.metrics import average_precision_score, precision_recall_curve, auc

y = np.array([1, 1, 0, 1, 0, 1, 0, 0, 1, 0])
s = np.array([0.95, 0.85, 0.80, 0.70, 0.55, 0.45, 0.40, 0.30, 0.20, 0.10])

order = np.argsort(-s)
tp = np.cumsum(y[order])
k = np.arange(1, len(y) + 1)              # number predicted positive
precision = tp / k
recall = tp / y.sum()
for kk, p, r in zip(k, precision, recall):
    print(f"top {kk:2d}: precision {p:.3f}  recall {r:.2f}")

ap = np.sum(np.diff(np.r_[0, recall]) * precision)
prec_sk, rec_sk, _ = precision_recall_curve(y, s)
print(f"AP ours {ap:.4f}  sklearn {average_precision_score(y, s):.4f}  trapezoid {auc(rec_sk, prec_sk):.4f}")
top  1: precision 1.000  recall 0.20
top  2: precision 1.000  recall 0.40
top  3: precision 0.667  recall 0.40
top  4: precision 0.750  recall 0.60
top  5: precision 0.600  recall 0.60
top  6: precision 0.667  recall 0.80
top  7: precision 0.571  recall 0.80
top  8: precision 0.500  recall 0.80
top  9: precision 0.556  recall 1.00
top 10: precision 0.500  recall 1.00
AP ours 0.7944  sklearn 0.7944  trapezoid 0.7739

Recall only increases at the five positives (top 1, 2, 4, 6 and 9), so AP is the mean of the precision at those five points: (1+1+0.75+0.667+0.556)/5=0.794(1 + 1 + 0.75 + 0.667 + 0.556)/5 = 0.794. The trapezoid over the same curve gives 0.774. The numbers are close here, but on a real curve with many points they can differ enough to change a ranking of models.

Why PR curves for rare positives

ROC curves use rates within each class, so they do not change when the class balance changes. That sounds like an advantage, but it hides what rarity does to precision. Take the same score distributions as the lab and make positives rare:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score, average_precision_score, roc_curve, precision_recall_curve

rng = np.random.default_rng(1)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4))
for share in [0.5, 0.1, 0.01]:
    n_pos = int(20000 * share)
    y = np.r_[np.ones(n_pos), np.zeros(20000 - n_pos)]
    s = np.r_[rng.normal(1.5, 1, n_pos), rng.normal(0, 1, 20000 - n_pos)]
    print(f"positives {share:5.0%}: ROC AUC {roc_auc_score(y, s):.3f}   AP {average_precision_score(y, s):.3f}")
    f, t, _ = roc_curve(y, s); ax1.plot(f, t, label=f"{share:.0%} positive")
    p, r, _ = precision_recall_curve(y, s); ax2.plot(r, p, label=f"{share:.0%} positive")
ax1.plot([0, 1], [0, 1], "k:"); ax1.set(xlabel="false positive rate", ylabel="true positive rate", title="ROC")
ax2.set(xlabel="recall", ylabel="precision", title="precision-recall"); ax2.legend()
plt.tight_layout()
positives   50%: ROC AUC 0.857   AP 0.855
positives   10%: ROC AUC 0.862   AP 0.484
positives    1%: ROC AUC 0.836   AP 0.087

With the same two score distributions, ROC AUC stays around 0.84 to 0.86 (the variation is sampling noise), while AP falls from 0.855 to 0.484 to 0.087. With 1 % positives the negatives outnumber the positives 99 to 1, so even the small tail of negatives above any threshold swamps the positives. ROC AUC describes the score; AP describes what a user of the alerts will experience.

In the lab, set the share of positives to 0.05: the ROC AUC hardly moves (0.833), while the AP falls from 0.710 to 0.322. At threshold 1 the recall is still 0.64, but the precision is only 0.167, so five of every six alarms are false.

05010005scorecountScores by true classpositive →← negativenegativepositivepredicted +predicted −actual posactual neg32TP18FN160FP790TNprecision 0.167 recall 0.640 F1 0.2640.00.51.00.00.51.0false positive rateTPRROC curveAUC 0.833- - chance0.00.51.00.00.51.0recallprecisionPrecision-recallAP 0.322- - chance

Which to report

Situation Report
balanced classes, ranking quality, comparing models before a threshold is fixed ROC AUC
rare positives (fraud, disease, defects, retrieval), the positives are what matters average precision, and the PR curve
a decision at a known operating point precision and recall (or cost) at that threshold, with the curve for context
probabilities will be used as probabilities also log loss and calibration (next lesson, Calibration)

Pitfalls

  • AUC from hard labels. roc_auc_score(y, model.predict(X)) gives a one-point "curve"; pass scores (predict_proba(X)[:, 1] or decision_function(X)).
  • Wrong column. For predict_proba, column 1 is the score of the class model.classes_[1].
  • AUC says nothing about calibration. Any increasing transformation of the scores (squaring, log) leaves AUC unchanged.
  • High ROC AUC on rare positives can still mean a useless alert stream; look at precision at the recall you need.
  • Comparing AP across data sets with different positive rates: a random model's AP equals the positive rate, so AP 0.3 is poor at 50 % positives and excellent at 1 %.

Practice

  1. Scores: positives 0.9, 0.6; negatives 0.7, 0.3, 0.2. Compute the ROC AUC by counting pairs.
Answer

There are 2⋅3=62 \cdot 3 = 6 pairs. 0.9 beats all three negatives; 0.6 beats 0.3 and 0.2 but not 0.7. So 5/6≈0.8335/6 \approx 0.833.

  1. What AP does a model with random scores get on data with 2 % positives? What ROC AUC?
Answer

About 0.02 (precision is the positive rate at every recall), and about 0.5 for ROC AUC.

Test yourself

What does ROC AUC = 0.8 mean?

  1. 80 % of predictions are correct
  2. A random positive scores higher than a random negative with probability 0.8
  3. Precision is 0.8 at the best threshold
  4. The model is 80 % calibrated

Positives drop from 30 % to 5 % of the data, with the same score distributions per class. What happens?

  1. ROC AUC falls sharply, AP stays
  2. ROC AUC stays about the same, AP falls sharply
  3. Both stay the same
  4. Both rise

How does scikit-learn's average_precision_score summarise the PR curve?

  1. Trapezoid rule between PR points
  2. ∑n(Rn−Rn−1)Pn\sum_n (R_n - R_{n-1}) P_n, a step-wise sum
  3. The maximum F1F_1
  4. Precision at recall 0.5

You square every score of a model. How does its ROC AUC change?

  1. It doubles
  2. It does not change if all scores are positive
  3. It becomes 0.5
  4. It is squared too