Reading history

ROC Curve and AUC in Python: Thresholds and Precision-Recall Curves

6 min read 2 views

Learn ROC curves and AUC in Python with scikit-learn: true and false positive rates, choosing a threshold, and precision-recall curves for rare positives.

A classifier rarely gives a plain yes or no. It gives a score, such as a probability, and you choose the threshold that turns the score into a decision. The ROC curve shows how the model behaves at every possible threshold, and AUC sums that up in one number. This lesson also covers the precision-recall curve, which is the better tool when positives are rare.

In this lesson you will learn

  • What the true positive rate and false positive rate measure
  • How to draw an ROC curve with roc_curve and score it with roc_auc_score
  • How moving the threshold trades recall against false alarms
  • Why the precision-recall curve suits rare positives
  • How to pick a threshold for a target precision

You should know logistic regression and precision and recall.

Two Rates Behind the Curve

Pick a threshold, say 0.5. Every row with a score at or above it is predicted positive. Two rates then describe the result:

RateFormulaPlain meaning
True positive rate (TPR)TP / (TP + FN)Share of real positives we caught. Same as recall.
False positive rate (FPR)FP / (FP + TN)Share of real negatives we wrongly flagged.

Lower the threshold and both rates go up: you catch more positives but also raise more false alarms. The ROC curve plots TPR against FPR for every threshold. A perfect model hugs the top-left corner. A model that guesses at random follows the diagonal line from (0, 0) to (1, 1).

ROC Curve and AUC in scikit-learn

from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_breast_cancer(return_X_y=True)
# In this dataset 1 = benign, 0 = malignant. Treat malignant as the positive class.
y = 1 - y
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=1)

model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X_train, y_train)
scores = model.predict_proba(X_test)[:, 1]   # probability of "malignant"

fpr, tpr, thresholds = roc_curve(y_test, scores)
print("Points on the ROC curve:", len(fpr))
print("AUC:", round(roc_auc_score(y_test, scores), 4))

print("\nthreshold   TPR (recall)   FPR")
for t in [0.9, 0.5, 0.2, 0.05]:
    pred = scores >= t
    tpr_t = (pred & (y_test == 1)).sum() / (y_test == 1).sum()
    fpr_t = (pred & (y_test == 0)).sum() / (y_test == 0).sum()
    print(f"{t:>9}   {tpr_t:>12.3f}   {fpr_t:.3f}")

Output

Points on the ROC curve: 16
AUC: 0.9877

threshold   TPR (recall)   FPR
      0.9          0.844   0.000
      0.5          0.906   0.009
      0.2          0.938   0.047
     0.05          0.969   0.075
  • predict_proba(X_test)[:, 1] gives the score for the positive class. ROC tools need these scores, not the 0/1 output of predict.
  • roc_curve returns the FPR, TPR and threshold of each corner point. By default it drops points that lie on a straight segment, so only 16 remain.
  • AUC is the area under the curve. 0.5 means random guessing and 1.0 means perfect ranking. Here it is 0.988.
  • AUC has a handy meaning: pick one random positive and one random negative. AUC is the chance that the positive gets the higher score.
  • The table shows the trade-off. At 0.5 the model catches 90.6% of malignant tumours with under 1% false alarms. At 0.05 it catches 96.9%, but 7.5% of benign cases are now flagged.

To draw the curve, pass the arrays to Matplotlib with plt.plot(fpr, tpr), or use RocCurveDisplay.from_predictions(y_test, scores).

Rare Positives: the Precision-Recall Curve

When only 2% of rows are positive, there are so many negatives that FPR stays small even when the model raises many false alarms. ROC AUC can then look better than the model feels in use. The precision-recall curve avoids this, because precision counts false alarms against the flagged rows, not against all negatives.

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

# Rare positive class: about 2% of rows
X, y = make_classification(n_samples=5000, n_features=10, n_informative=4,
                           weights=[0.98, 0.02], class_sep=0.7, random_state=3)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, stratify=y, random_state=3)
scores = LogisticRegression(max_iter=1000).fit(X_train, y_train).predict_proba(X_test)[:, 1]

print("Positives in test set:", y_test.sum(), "of", len(y_test))
print(f"ROC AUC:           {roc_auc_score(y_test, scores):.3f}")
print(f"Average precision: {average_precision_score(y_test, scores):.3f}")
print(f"Random-guess AP:   {y_test.mean():.3f}")

# Pick the lowest threshold that still gives at least 50% precision
precision, recall, thresholds = precision_recall_curve(y_test, scores)
for p, r, t in zip(precision, recall, thresholds):
    if p >= 0.5:
        print(f"\nThreshold {t:.3f} gives precision {p:.2f} and recall {r:.2f}")
        break

Output

Positives in test set: 47 of 2000
ROC AUC:           0.700
Average precision: 0.266
Random-guess AP:   0.024

Threshold 0.200 gives precision 0.50 and recall 0.32
  • ROC AUC is a respectable-sounding 0.700, yet average precision (the area under the precision-recall curve) is only 0.266.
  • For the PR curve, the random baseline is the positive share, 0.024, not 0.5. So 0.266 is about eleven times better than guessing, but far from perfect.
  • precision_recall_curve returns one more precision and recall value than thresholds; zip stops at the shortest list, so the loop is safe.
  • The loop finds a working threshold: at 0.200, half of the flagged rows are real positives and we catch 32% of them.

ROC or Precision-Recall?

SituationBetter summary
Classes roughly balancedROC AUC
Positives are rare (fraud, disease screening)Average precision / PR curve
Comparing models that will rank itemsROC AUC
Cost of each false alarm matters mostPrecision at the chosen threshold

Common Mistakes

  1. Passing predict output to roc_auc_score. With only 0s and 1s the curve has a single corner, so the AUC describes just the 0.5 threshold and usually understates the model.
  2. Choosing the threshold on the test set, then reporting test results with it. Choose on validation data or with cross-validation.
  3. Reading AUC as accuracy. An AUC of 0.9 does not mean 90% of predictions are right.
  4. Judging a rare-event model by ROC AUC alone. Always look at precision too.

Practice Exercises

Exercise 1. A model gives every row the same score, 0.5. What is its ROC AUC?

Show answer

0.5. Every positive and negative pair is a tie, and ties count as half, so the model is no better than a coin flip.

Exercise 2. Change the loop in the second example so it finds the threshold with the highest recall while keeping precision at or above 0.4.

Show answer
best = None
for p, r, t in zip(precision, recall, thresholds):
    if p >= 0.4 and (best is None or r > best[1]):
        best = (t, r, p)
print(best)

The loop scans every threshold rather than stopping at the first match, because recall falls as the threshold rises.

Frequently Asked Questions

What is a good AUC score?

It depends on the problem. As a rough guide, 0.7 to 0.8 is fair, 0.8 to 0.9 is good and above 0.9 is excellent. Compare against a simple baseline model on the same data rather than a fixed number.

Can ROC AUC be used for more than two classes?

Yes. roc_auc_score(y, proba, multi_class="ovr") scores each class against the rest and averages the results. Pass the full probability matrix from predict_proba.

Summary

  • The ROC curve plots recall (TPR) against the false positive rate for every threshold.
  • AUC is the chance a random positive outscores a random negative; 0.5 is random.
  • For rare positives, use the precision-recall curve and average precision.
  • Pick the decision threshold from the costs of each error, on validation data.

Next: Polynomial Regression in Python.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *