Learning path: Classify and Evaluate: Logistic Regression to Cross-Validation · Step 5 of 7
ROC Curve, AUC and Choosing a Classification Threshold
The 0.5 cut is only a default. On 1% fraud data: slide the threshold, draw the ROC and precision-recall curves, read AUC 0.877, pick the best-F1 cut on validation data, then open the test part once.
What you will learn
- Slide the threshold and track TPR and FPR
- Draw the ROC and precision-recall curves and read AUC and average precision
- Pick a threshold on a validation part, never on the test part
- Weigh caught frauds against false alarms at different cuts
Before you start
- Precision, Recall and F1 Score
- Logistic Regression in scikit-learn
Think about the metal detector at an airport. With low sensitivity the line moves fast and nothing beeps, but a knife can slip through. With high sensitivity it catches everything, and it also beeps at every belt buckle.
A classifier has the same knob: the threshold. predict cuts the probability at 0.5, but that's only a default. Lower the cut and you catch more fraud, and you pay with more false alarms. This article shows how to see that trade-off and choose the cut honestly.
Fit, validate, test
Same payments.csv as in Why Accuracy Lies, with 1% fraud. Choosing a cut is a kind of learning, so it can't happen on the test part. We cut a validation part out of the training rows.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.dummy import DummyClassifier
from sklearn.metrics import (confusion_matrix, roc_auc_score, average_precision_score,
precision_recall_curve, RocCurveDisplay, PrecisionRecallDisplay)
df = pd.read_csv("payments.csv")
X = df.drop(columns="fraud")
y = df["fraud"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42)
X_fit, X_val, y_fit, y_val = train_test_split(
X_train, y_train, test_size=0.25,
stratify=y_train, random_state=42)
print(len(X_fit), len(X_val), len(X_test))
print("frauds in validation:", y_val.sum())
11250 3750 5000
frauds in validation: 37
11,250 rows to fit, 3,750 to validate (37 frauds), 5,000 locked away for the test.
Frauds just under the cut
model = LogisticRegression().fit(X_fit, y_fit)
p_val = model.predict_proba(X_val)[:, 1]
missed = p_val[(y_val == 1) & (p_val < 0.5)]
print(np.sort(missed)[-3:].round(2))
[0.42 0.44 0.46]
These three frauds scored 0.42, 0.44 and 0.46. Just under 0.5, so predict calls them normal. A lower cut would catch them.
Slide the threshold
For each cut we count the four boxes and compute two rates:
- TPR (true positive rate) = TP / (TP + FN): the share of frauds caught. It's just recall.
- FPR (false positive rate) = FP / (FP + TN): the share of normal payments wrongly flagged.
print("t TPR FPR TP FP")
for t in [0.5, 0.2, 0.05, 0.01]:
cm = confusion_matrix(y_val, p_val >= t)
tn, fp, fn, tp = cm.ravel()
tpr, fpr = tp / (tp + fn), fp / (fp + tn)
print(f"{t:<5}{tpr:6.2f}{fpr:7.3f}{tp:5d}{fp:5d}")
t TPR FPR TP FP
0.5 0.30 0.000 11 0
0.2 0.43 0.001 16 4
0.05 0.54 0.014 20 53
0.01 0.81 0.140 30 518
As the cut goes down, both rates go up. At 0.5 we catch 11 frauds with no false alarms; at 0.01 we catch 30, with 518 false alarms. Each cut is one point (FPR, TPR).
The ROC curve: every cut at once
Join the points for every possible cut and you get the ROC curve.
RocCurveDisplay.from_predictions(
y_val, p_val, name="model", plot_chance_level=True);

AUC: a fair fight between payments
Pick one fraud and one normal payment at random. Does the fraud get the higher score? The AUC (area under the ROC curve) is how often it does. 1 is perfect; 0.5 is a coin flip.
lazy = DummyClassifier().fit(X_fit, y_fit)
p_lazy = lazy.predict_proba(X_val)[:, 1]
auc = roc_auc_score(y_val, p_val)
auc_lazy = roc_auc_score(y_val, p_lazy)
print("AUC model:", round(auc, 3))
print("AUC lazy: ", round(auc_lazy, 3))
AUC model: 0.877
AUC lazy: 0.5
0.877: about 88 pairs in 100 are ranked the right way. The lazy model gives every payment the same chance, so it scores exactly 0.5. AUC compares models with one number and no threshold to pick.
The precision-recall curve
With a rare class, the ROC curve can look a bit too happy. FPR divides by the 3,713 normal validation payments, so 53 false alarms look tiny. Precision doesn't hide them.
ap = average_precision_score(y_val, p_val)
ap_lazy = average_precision_score(y_val, p_lazy)
print("AP model:", round(ap, 3))
print("AP lazy: ", round(ap_lazy, 3))
AP model: 0.507
AP lazy: 0.01
Average precision sums up the precision-recall curve. The lazy model gets 0.01, just the share of frauds.
PrecisionRecallDisplay.from_predictions(
y_val, p_val, name="model", plot_chance_level=True);

Choose the cut on validation data
Pick the cut with the metric you care about. Here it's F1, computed at every cut that precision_recall_curve returns:
prec, rec, thr = precision_recall_curve(y_val, p_val)
f1 = 2 * prec * rec / (prec + rec + 1e-12)
t_best = thr[f1[:-1].argmax()]
print("best cut:", round(t_best, 3))
print("F1 on validation:", round(f1.max(), 3))
best cut: 0.258
F1 on validation: 0.571
The tiny 1e-12 avoids dividing by zero. The last precision/recall pair has no threshold, hence f1[:-1].
Only now, open the test part once
p_test = model.predict_proba(X_test)[:, 1]
for t in [0.5, t_best, 0.01]:
cm = confusion_matrix(y_test, p_test >= t)
tn, fp, fn, tp = cm.ravel()
print(f"t={t:.3f} caught {tp}/50 alarms {fp}")
t=0.500 caught 21/50 alarms 1
t=0.258 caught 25/50 alarms 2
t=0.010 caught 41/50 alarms 665
| Cut | Frauds caught | False alarms |
|---|---|---|
| 0.5 (default) | 21 of 50 | 1 |
| 0.258 (best F1 on validation) | 25 of 50 | 2 |
| 0.01 | 41 of 50 | 665 |
The chosen cut catches four more frauds for one extra alarm. Going down to 0.01 catches 41, at the price of 665 normal payments flagged. There's no free lunch; the cost of each mistake decides.
Common mistakes
- Tuning the threshold on the test part. Then the test score is no longer honest. Pick it on validation data and test once.
- Trusting ROC AUC alone on rare classes. Check the precision-recall curve and average precision too.
- Treating 0.5 as fixed. It's a default. Move it to fit the cost of a miss and a false alarm.
Quick recap
| Idea | Fraud model (validation) |
|---|---|
| ROC curve | TPR against FPR for every cut |
| AUC | 0.877 (lazy 0.5) |
| Average precision | 0.507 (lazy 0.01) |
| Best-F1 cut | 0.258, F1 0.571 |
| Rule | choose on validation, test once |
Try it yourself
On the validation part, find the highest threshold that still catches 70% of the frauds. Then check it once on the test part.
The notebook and payments.csv are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Precision, Recall and F1 Score: Two Questions and One Balance
Next →Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.