Sub topic 4
Precision-recall and ROC curves, and when each is informative
This chapter assumes you can train a scikit-learn classifier and get predict_proba scores. It also assumes you know the confusion matrix terms (true positive, false positive, precision, recall) from the previous chapter. Here you will learn to evaluate a model across all decision thresholds instead of at a single one.
Why look at curves
A classifier such as logistic regression outputs a score. A threshold turns that score into a class label. Precision, recall and F1 describe the model at one threshold, usually the default 0.5. On imbalanced data the default is rarely a sensible operating point, so a single-threshold metric can make a good ranking model look bad. It can also hide a bad model.
A curve evaluates the ranking quality of the scores. It plots a pair of metrics at every threshold the data supports. Two curves are standard:
- The ROC curve (receiver operating characteristic) plots true positive rate against false positive rate.
- The precision-recall curve (PR curve) plots precision against recall.
Both use the same ingredients, the four confusion matrix counts. They normalize them differently, and that difference decides when each curve is informative.
The definitions
For P actual positives and N actual negatives, at a given threshold:
- Recall, also called true positive rate (TPR), is TP / P.
- False positive rate (FPR) is FP / N.
- Precision is TP / (TP + FP).
TPR and FPR each divide by the size of one true class. Neither depends on how many negatives there are relative to positives. Precision divides by the number of predicted positives, which mixes both classes. That is why precision moves when the class ratio changes and FPR does not.
ROC curves
The ROC curve starts at (0, 0), where the threshold is so high that nothing is predicted positive. It ends at (1, 1), where everything is predicted positive. A model with no ranking ability follows the diagonal. A perfect model goes through (0, 1).
The area under the ROC curve (ROC AUC) has a useful reading. It is the probability that a randomly chosen positive gets a higher score than a randomly chosen negative. A value of 0.5 means random ranking and 1.0 means perfect ranking.
ROC strengths:
- It does not change if you add or remove negatives at random, as long as the score distributions of each class stay the same.
- It compares models fairly across datasets with different prevalence.
- It is a good fit when both kinds of error matter and the classes are of similar importance.
ROC weakness on imbalanced data: FPR divides by a very large N. A small-looking FPR can still produce more false positives than there are true positives.
Precision-recall curves
The PR curve plots precision on the y-axis against recall on the x-axis. A random classifier gives a horizontal line at the prevalence, the fraction of positives. At 5% positives, a random model has precision about 0.05 at every recall level. A perfect model stays at precision 1.0 until recall 1.0.
The summary number is average precision (AP). scikit-learn computes it as a step-wise sum, AP = Σ (Rₙ − Rₙ₋₁) · Pₙ, over the thresholds. It does not use linear interpolation between points. Interpolating between PR points is overly optimistic, so the step-wise form is the safer choice. This is also why sklearn.metrics.auc applied to a PR curve can give a slightly different number from average_precision_score.
PR curves answer the question that usually matters for rare-class problems: when the model flags a case, how often is it right, and how many real cases does it catch?
A worked example with numbers
Suppose a test set has 10,000 samples, 500 positives and 9,500 negatives. A model operates at TPR 0.80, which gives TP = 400. The table shows what different FPRs mean.
| FPR | False positives | Precision at TPR 0.80 |
|---|---|---|
| 0.05 | 475 | 400 / 875 ≈ 0.46 |
| 0.01 | 95 | 400 / 495 ≈ 0.81 |
An FPR of 0.05 looks excellent on a ROC plot, but fewer than half of the alerts are real. Now take a balanced set with 5,000 positives and 5,000 negatives, at the same TPR 0.80 and FPR 0.05. TP is 4,000 and FP is 250, so precision is 4,000 / 4,250 ≈ 0.94. The ROC point is identical, while precision changed from 0.46 to 0.94. The ROC curve cannot see this, because it discards the class ratio.
Computing both curves in scikit-learn
The code below trains a plain logistic regression with no rebalancing. We do that because the curves evaluate the scores, and the point here is the evaluation. It then computes both curves and reads off the precision available at 80% recall. The dataset is the same synthetic one as in the earlier chapters.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
roc_curve,
roc_auc_score,
precision_recall_curve,
average_precision_score,
)
X, y = make_classification(
n_samples=10000,
n_features=20,
n_informative=5,
weights=[0.95, 0.05],
flip_y=0.01,
random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
scores = model.predict_proba(X_test)[:, 1]
n_pos = int(y_test.sum())
n_neg = int(len(y_test) - n_pos)
print("prevalence:", y_test.mean())
print("ROC AUC:", roc_auc_score(y_test, scores))
print("average precision:", average_precision_score(y_test, scores))
fpr, tpr, _ = roc_curve(y_test, scores)
precision, recall, _ = precision_recall_curve(y_test, scores)
# Lowest FPR that reaches TPR >= 0.80 (fpr is sorted in increasing order).
i = np.argmax(tpr >= 0.80)
print("FPR at TPR>=0.80:", fpr[i], "-> false positives:", round(fpr[i] * n_neg), "of", n_neg, "negatives")
# Best precision among thresholds that keep recall >= 0.80.
print("precision at recall>=0.80:", precision[recall >= 0.80].max())Read the last three lines together. The false positive count shows how a small FPR turns into real review work. The precision line shows what fraction of the flagged cases a human would find to be real positives.
The precision_recall_curve function returns one more precision and recall value than thresholds. The last point is precision 1 at recall 0, which has no threshold. Remember this when you index into the threshold array, as you will in the threshold tuning chapter.
Plotting the two curves
Plot them side by side, and draw the no-skill baseline on each. The ROC baseline is the diagonal and the PR baseline is the prevalence.
import matplotlib.pyplot as plt
from sklearn.metrics import RocCurveDisplay, PrecisionRecallDisplay
# Continues from the previous example (y_test, scores).
fig, (ax_roc, ax_pr) = plt.subplots(1, 2, figsize=(10, 4))
RocCurveDisplay.from_predictions(y_test, scores, ax=ax_roc)
ax_roc.plot([0, 1], [0, 1], linestyle="--", color="gray")
ax_roc.set_title("ROC")
PrecisionRecallDisplay.from_predictions(y_test, scores, ax=ax_pr)
ax_pr.axhline(y_test.mean(), linestyle="--", color="gray")
ax_pr.set_title("Precision-recall")
fig.tight_layout()
fig.savefig("curves.png", dpi=120)On a dataset like this one, the ROC curve typically bows far into the top-left corner. The PR curve usually looks much less impressive, since it sits well above the baseline but is far from the top-right corner. Both are correct views of the same scores.
Demonstrating the prevalence effect
You can verify the effect from the table on your own data. Keep all test positives, subsample the negatives to the same count, and recompute both metrics from the same scores. This is a diagnostic only. Never evaluate a model you plan to deploy on a rebalanced test set, because deployment data will have the real class ratio.
# Continues from the previous examples (y_test, scores).
rng = np.random.default_rng(0)
pos = np.flatnonzero(y_test == 1)
neg = np.flatnonzero(y_test == 0)
neg_sub = rng.choice(neg, size=len(pos), replace=False)
idx = np.concatenate([pos, neg_sub])
print("original ROC AUC:", roc_auc_score(y_test, scores))
print("balanced ROC AUC:", roc_auc_score(y_test[idx], scores[idx]))
print("original AP:", average_precision_score(y_test, scores))
print("balanced AP:", average_precision_score(y_test[idx], scores[idx]))Expect the ROC AUC to stay close to its original value, apart from sampling noise. Expect the average precision to rise a lot. The model did not improve. The same scores simply face fewer negatives to be confused with.
When each curve is informative
| Situation | Better view | Reason |
|---|---|---|
| Rare positives, cost depends on false alarms | PR curve, AP | Precision exposes the false positive burden |
| Comparing models on data with the same prevalence | Either | Both rank models in similar order, usually |
| Comparing across datasets or time periods with different prevalence | ROC AUC | It does not shift with prevalence |
| Both classes matter equally, near-balanced data | ROC | FPR and TPR are both meaningful |
| Very few positives in the test set | Neither alone, add confidence intervals | Both are noisy |
Gotchas
- High ROC AUC does not mean usable precision. A ROC AUC of 0.95 with 1% prevalence can still give precision below 0.2 at useful recall. Always check precision at the recall you need.
- AP is not comparable across datasets. Its floor is the prevalence. An AP of 0.30 is strong at 2% prevalence and weak at 40%.
- Curves are noisy with few positives. With 40 test positives, each positive moves recall by 2.5 points. Use stratified cross-validation, pool out-of-fold scores, and bootstrap a confidence interval for the metric.
- A curve is not a model choice. AUC and AP summarize all thresholds, including ones you will never use. If you only care about a region, such as recall of at least 0.9, report the metric in that region, as in the earlier code.
- Do not compute curves on resampled test data. Curves from a rebalanced test set describe a prevalence you will never see in production.
- Class weights and resampling change scores, not just labels. Models trained with them still produce usable rankings, but their probabilities are shifted. The calibration chapter covers this.
Summary of the working model
ROC and PR curves are two normalizations of the same confusion matrix counts over all thresholds. ROC divides by class sizes, so it ignores prevalence. PR divides by predicted positives, so it reflects prevalence and the cost of false alarms. For a rare class that you must act on, start with PR and average precision. Keep ROC AUC as a secondary, prevalence-free ranking check.
Exercise
A test set has 200 positives and 19,800 negatives. A model at one threshold has TPR 0.75 and FPR 0.02. What are the true positives, false positives and precision at that threshold? Does the ROC curve alone tell you the precision?
Show answer
TP = 0.75 × 200 = 150. FP = 0.02 × 19,800 = 396. Precision = 150 / (150 + 396) ≈ 0.27. No. The ROC point (FPR 0.02, TPR 0.75) is the same for any class ratio, but precision depends on the number of negatives, so you also need the prevalence or the raw counts.
Exercise
You run the diagnostic from this chapter. After you subsample negatives to match the positives, ROC AUC barely changes but average precision rises sharply. Explain why, and say which number you would report to stakeholders for a deployed fraud model with real prevalence of 1%.
Show answer
ROC AUC depends only on how the scores of positives rank against the scores of negatives, so removing random negatives does not change it. Precision depends on how many false positives accompany each true positive, and fewer negatives means fewer false positives, so AP rises. Report the average precision and the precision at the required recall measured on data with the real 1% prevalence, since that reflects what the deployed model will do. ROC AUC can be added as a ranking-quality check.