Sub topic 11
Class imbalance and precision-recall curves
This chapter assumes you can build a ROC curve and compute AUC with scikit-learn, and that you know the confusion matrix terms. It covers what happens to those tools when positives are rare. It then introduces the precision-recall (PR) curve and gives rules for choosing between the two.
Why a good ROC curve can hide a bad classifier
TPR and FPR are each computed within one class. TPR divides by the number of positives. FPR divides by the number of negatives. Neither depends on how many examples of each class exist. That is why ROC curves stay stable when class proportions change, and it is also why they can look good when the classifier is not useful.
Take a screening problem with 100 positives and 9,900 negatives, so 1% of examples are positive. At some threshold the classifier has TPR = 0.80 and FPR = 0.05. Those look like good numbers. The confusion matrix shows what they mean:
- True positives: 0.80 × 100 = 80
- False negatives: 20
- False positives: 0.05 × 9,900 = 495
- True negatives: 9,405
Of 575 alerts, only 80 are real. Precision is 80 / 575 ≈ 0.139. About 86% of the alerts are false alarms, yet the point sits comfortably high and left on the ROC plot.
Precision is TP / (TP + FP), the fraction of predicted positives that are truly positive. Recall is the same quantity as TPR, TP / (TP + FN). Precision is the only one of these three that mixes the two classes, because FP comes from the negatives and TP from the positives. That mixing makes precision sensitive to prevalence, and prevalence is the share of positives in the data.
Precision as a function of prevalence
Let π be the prevalence. For a fixed TPR and FPR, precision is:
precision = TPR·π / (TPR·π + FPR·(1 − π))
The classifier's ROC point does not change as π changes, but its precision does.
tpr, fpr = 0.80, 0.05
for prevalence in [0.5, 0.1, 0.01, 0.001]:
tp = tpr * prevalence
fp = fpr * (1 - prevalence)
precision = tp / (tp + fp)
print(f"{prevalence:.3f} {precision:.3f}")
# 0.500 0.941
# 0.100 0.640
# 0.010 0.139
# 0.001 0.016The same classifier is 94% precise on balanced data and 1.6% precise when one example in a thousand is positive. ROC AUC is identical in all four cases, so it cannot tell you this.
The precision-recall curve
A PR curve uses the same threshold sweep as a ROC curve. Each threshold gives one (recall, precision) point, with recall on the x-axis and precision on the y-axis. The two curves differ in what they measure:
| Row | ROC curve | PR curve |
|---|---|---|
| x-axis | FPR (negatives wrongly flagged, relative to all negatives) | Recall (positives found, relative to all positives) |
| y-axis | TPR (recall) | Precision (true positives, relative to all flagged) |
| Uses true negatives | Yes, through FPR | No |
| Random classifier | Diagonal, AUC 0.5 | Horizontal line at prevalence π |
| Perfect classifier | Top-left corner | Top-right corner |
| Sensitive to prevalence | No | Yes |
The PR curve never uses true negatives. When negatives vastly outnumber positives, adding thousands more easy negatives barely moves the PR curve, but it shrinks FPR and makes the ROC curve look better.
The random baseline is also different. A classifier that ignores its input has precision π at every recall level. On a 1% problem the baseline is 0.01, so a PR curve hovering near 0.14 is well above chance. On a balanced problem it would be only slightly better than chance. Always draw this baseline on a PR plot.
Average precision
The usual one-number summary of a PR curve is average precision (AP):
AP = Σ (Rₙ − Rₙ₋₁) · Pₙ
Here Pₙ and Rₙ are precision and recall at the n-th threshold. This is a step-wise sum, with no interpolation between points. Compute it with average_precision_score. The small example from earlier chapters shows the difference from ROC AUC:
import numpy as np
from sklearn.metrics import average_precision_score, roc_auc_score
y_true = np.array([0, 0, 1, 1])
y_score = np.array([0.1, 0.4, 0.35, 0.8])
print(round(roc_auc_score(y_true, y_score), 3)) # 0.75
print(round(average_precision_score(y_true, y_score), 3)) # 0.833You can check the 0.833 by hand. Ranking by score gives positive, negative, positive, negative. The first positive arrives at recall 0.5 with precision 1.0, which contributes 0.5 × 1.0. The second arrives at recall 1.0 with precision 2/3, which contributes 0.5 × 0.667. The sum is 0.833.
Comparing the two on imbalanced data
The following script generates a roughly 1% positive problem and reports both metrics. The exact values depend on your scikit-learn version, so run it rather than trusting a printed number. The pattern to expect is a high ROC AUC alongside a much lower AP.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, precision_recall_curve, roc_auc_score
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_samples=20000,
n_features=10,
n_informative=3,
weights=[0.99, 0.01],
class_sep=1.0,
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]
precision, recall, thresholds = precision_recall_curve(y_test, scores)
print("prevalence (PR baseline):", round(y_test.mean(), 4))
print("ROC AUC:", round(roc_auc_score(y_test, scores), 3))
print("Average precision:", round(average_precision_score(y_test, scores), 3))Three details matter here:
stratify=ykeeps the rare class present in both splits. Without it, a small test set can end up with very few positives, and every metric becomes noisy.precision_recall_curvereturnsprecisionandrecallarrays that are one element longer thanthresholds. The final point (precision 1, recall 0) has no threshold.- Passing
scoresfrompredict_probais correct. Passing hard 0/1 predictions collapses the curve to a single point.
Gotchas specific to PR curves
- Non-monotonic precision. Lowering the threshold can reduce precision, then raise it again if the next examples are positive. The curve is jagged, and that is expected.
- Noisy at the high-precision end. The first few thresholds involve very few predictions. One early false positive can drop precision from 1.0 to 0.5. With few positives, the left side of the curve is mostly noise.
- Not comparable across datasets. AP of 0.30 is strong at prevalence 0.01 and weak at prevalence 0.25. Report AP together with prevalence, or use the ratio of AP to prevalence.
- Prevalence shift. If the deployment prevalence differs from your test set, precision, and therefore AP, will not transfer. TPR and FPR will transfer, assuming the score distribution within each class is unchanged. To estimate deployment precision, apply the formula from earlier with the deployment π.
- Resampling distorts PR. If you oversample positives or undersample negatives in the test set, the PR curve describes the resampled data. Resample only the training set, and evaluate on data with realistic prevalence.
Choosing between ROC and PR
| Situation | Prefer |
|---|---|
| You care about ranking quality overall, and classes are roughly balanced | ROC AUC |
| Positives are rare and false alarms are costly to handle | PR curve and AP |
| You need the metric to be stable if prevalence changes | ROC AUC |
| You need to know what fraction of alerts are real | Precision at the chosen threshold |
| Both classes matter equally and you care about negatives too | ROC AUC |
The two curves contain the same information about the ranking. A model dominates another in ROC space exactly when it dominates it in PR space, for the same dataset. They only differ in how they emphasize the region of the curve where the model operates. For a rare-event problem, that region is the low-FPR corner of the ROC plot, which is hard to see. Plotting FPR on a log scale, or reading the PR curve, makes it visible.
Exercise
Exercise
A test set has 200 positives and 19,800 negatives. At the operating threshold, TPR = 0.90 and FPR = 0.02. Compute the precision, and say why the ROC point alone would not reveal it.
Show answer
True positives = 0.90 × 200 = 180. False positives = 0.02 × 19,800 = 396. Precision = 180 / (180 + 396) = 180 / 576 = 0.3125, so about 31% of alerts are real. TPR and FPR are each computed within a single class, so they do not depend on the 1% prevalence. Precision combines positives and negatives, so it falls as negatives become more numerous.
Exercise
Why is auc(recall, precision) a poor way to summarize a PR curve, and what should you use instead?
Show answer
The trapezoidal rule assumes precision varies linearly between two points on the curve, but precision can jump when a threshold crosses a single example. This can overstate the area. Use average_precision_score, which sums precision weighted by the recall increase at each threshold without interpolation.