Skip to main content

AI and machine learning · Intermediate · 25 min

Measure a classifier with precision, recall and ROC curves

By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · scikit-learn 1.9.1 · matplotlib 3.11.2

You will score a fraud classifier on rare-class data with a confusion matrix, precision, recall, F1, precision-recall and ROC curves and a reliability curve, then pick its decision threshold from the cost of each mistake.

On this page

A model that flags fraudulent payments can be 98% accurate and catch no fraud at all. If only 2 in every 100 payments are fraud, a model that always answers "legit" is right 98 times out of 100. Accuracy counts every payment the same, so the rare case you care about barely moves it.

This tutorial measures one classifier properly. You train a logistic regression on a synthetic payments dataset where 2% of rows are fraud, then look at it through the confusion matrix, precision, recall and F1, the precision-recall and ROC curves, a reliability curve for its probabilities, and finally choose the score threshold that costs least. Every chart is saved as a PNG file, so it works on a server with no screen.

The same questions come up wherever the important case is rare: mobile money fraud checks, loan default scoring, flagging a failed delivery or a faulty meter reading. The data here is generated with a fixed seed, so your numbers match the ones shown.

Step 1 · Create the project and the data

Create a throwaway project folder and add scikit-learn and matplotlib at exact versions:

Bash
mkdir -p ~/classifier-metrics-demo
cd ~/classifier-metrics-demo
uv init --no-package
uv add scikit-learn==1.9.1 matplotlib==3.11.2

Now write data.py. It generates 20,000 payments with 12 numeric features, of which 2% are fraud (label 1), and splits them 70/30 into training and test sets. stratify=y keeps the fraud rate the same in both halves, which matters when there are only a few hundred positives. make_model builds the classifier every later script uses: features scaled, then a logistic regression.

Bash
cat > data.py <<'PY'
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler


def load_data():
    X, y = make_classification(
        n_samples=20_000,
        n_features=12,
        n_informative=6,
        n_redundant=2,
        n_clusters_per_class=1,
        weights=[0.98],
        flip_y=0,
        class_sep=1.2,
        random_state=7,
    )
    return train_test_split(X, y, test_size=0.3, stratify=y, random_state=7)


def make_model(class_weight=None):
    return make_pipeline(
        StandardScaler(),
        LogisticRegression(max_iter=1000, class_weight=class_weight),
    )
PY
cat > check_data.py <<'PY'
from data import load_data

X_train, X_test, y_train, y_test = load_data()
print("train rows:", len(y_train), "fraud:", y_train.sum())
print("test rows: ", len(y_test), "fraud:", y_test.sum())
print(f"fraud rate in test: {y_test.mean():.3f}")
PY
uv run python check_data.py

Check it worked

The output shows 14,000 training rows with 280 fraud, and 6,000 test rows with 120 fraud, a fraud rate of 0.020:

Text
train rows: 14000 fraud: 280
test rows:  6000 fraud: 120
fraud rate in test: 0.020

Step 2 · See accuracy fail

Compare the real model with a DummyClassifier that always predicts the most common class. Any model worth shipping has to beat it clearly.

Bash
cat > accuracy.py <<'PY'
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score

from data import load_data, make_model

X_train, X_test, y_train, y_test = load_data()

dummy = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
model = make_model().fit(X_train, y_train)

print(f"always 'legit':      accuracy {accuracy_score(y_test, dummy.predict(X_test)):.3f}")
print(f"logistic regression: accuracy {accuracy_score(y_test, model.predict(X_test)):.3f}")
PY
uv run python accuracy.py

Check it worked

You see two numbers less than half a percentage point apart:

Text
always 'legit':      accuracy 0.980
logistic regression: accuracy 0.984

The dummy catches no fraud and still scores 0.980. Accuracy cannot tell you whether the model is useful here, so the rest of the tutorial replaces it.

Step 3 · Build a confusion matrix

A confusion matrix counts the four outcomes of a yes/no prediction. Rows are what really happened, columns are what the model said:

A two-by-two grid with actual class as rows and predicted class as columns. Top left is TN (legit, let through), top right FP (false alarm), bottom left FN (missed fraud), bottom right TP (fraud, caught). Beside it, precision is TP over the right column, recall is TP over the bottom row, and false positive rate is FP over the top row.
Precision reads down the 'fraud' column, recall reads across the 'fraud' row.

Write confusion.py. It prints the four counts and saves the matrix as confusion_matrix.png. The first line selects matplotlib's Agg back end, which draws to files and needs no display.

Bash
cat > confusion.py <<'PY'
import matplotlib

matplotlib.use("Agg")
from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix

from data import load_data, make_model

X_train, X_test, y_train, y_test = load_data()
model = make_model().fit(X_train, y_train)
y_pred = model.predict(X_test)

tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()
print(f"TN={tn} FP={fp} FN={fn} TP={tp}")

disp = ConfusionMatrixDisplay.from_predictions(
    y_test, y_pred, display_labels=["legit", "fraud"], cmap="Greys", colorbar=False
)
disp.ax_.set_title("Logistic regression, threshold 0.5")
disp.figure_.savefig("confusion_matrix.png", dpi=150, bbox_inches="tight")
print("saved confusion_matrix.png")
PY
uv run python confusion.py

confusion_matrix(...).ravel() returns the cells in the order TN, FP, FN, TP for labels 0 and 1. Unpack them in that order or you will mix up the two kinds of mistake.

Check it worked

The output is something like TN=5872 FP=8 FN=89 TP=31, and confusion_matrix.png is in the folder. Open it: the bottom row shows that of 120 frauds the model caught 31 and missed 89. The 5,872 correct "legit" answers in the top left are what kept accuracy high.

Step 4 · Compute precision, recall and F1

Each metric answers one question about the fraud class:

  • Precision is TP / (TP + FP): when the model flags a payment, how often is it fraud? Low precision means reviewers waste time on false alarms.
  • Recall is TP / (TP + FN): of all the fraud, how much did the model flag? Low recall means fraud gets through.
  • F1 is the harmonic mean of the two, 2 × precision × recall / (precision + recall). It is high only when both are.

Compute them by hand from the four counts, check scikit-learn agrees, then print the full report:

Bash
cat > metrics.py <<'PY'
import math

from sklearn.metrics import (
    classification_report,
    confusion_matrix,
    f1_score,
    precision_score,
    recall_score,
)

from data import load_data, make_model

X_train, X_test, y_train, y_test = load_data()
model = make_model().fit(X_train, y_train)
y_pred = model.predict(X_test)

tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()
precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1 = 2 * precision * recall / (precision + recall)
print(f"by hand:      precision {precision:.3f}  recall {recall:.3f}  F1 {f1:.3f}")

assert math.isclose(precision, precision_score(y_test, y_pred))
assert math.isclose(recall, recall_score(y_test, y_pred))
assert math.isclose(f1, f1_score(y_test, y_pred))
print("scikit-learn: same three numbers")

print(classification_report(y_test, y_pred, target_names=["legit", "fraud"], digits=3))
PY
uv run python metrics.py

Check it worked

The first line is something like by hand: precision 0.795 recall 0.258 F1 0.390, followed by scikit-learn: same three numbers, so your arithmetic matches the library. The report then shows a row per class:

Text
              precision    recall  f1-score   support

       legit      0.985     0.999     0.992      5880
       fraud      0.795     0.258     0.390       120

    accuracy                          0.984      6000
   macro avg      0.890     0.628     0.691      6000
weighted avg      0.981     0.984     0.980      6000

Read the fraud row: four out of five flags are right, but three quarters of the fraud is missed. The weighted avg row is weighted by support, so the 5,880 legit rows swamp it and it looks almost as good as accuracy. On rare-class problems, quote the minority row or the macro avg, not the weighted one.

Step 5 · Plot precision-recall and ROC curves

predict turns each probability into a yes or no with a cut-off of 0.5. Every number so far depends on that one threshold. The curves remove it: they sweep the threshold from 1 down to 0 and plot what happens at each position.

A horizontal fraud score axis from 0 to 1 with light dots for legit payments mostly on the left and dark dots for fraud mostly on the right. Two vertical lines mark a low threshold and the default 0.5. Moving the threshold left catches more fraud but adds false alarms; sweeping it across the whole axis traces the precision-recall and ROC curves.
  • The precision-recall curve plots precision against recall. Its summary number is average precision (AP). A model that guesses at random scores AP equal to the positive rate, here 0.02.
  • The ROC curve plots recall (the true positive rate) against the false positive rate, FP / (FP + TN). Its summary is ROC AUC. Random guessing scores 0.5, whatever the class balance.

Write curves.py. It draws both curves with their chance lines into curves.png, prints both summaries, and then recomputes them on a 50/50 sample of the test set: all 120 frauds plus 120 randomly chosen legit rows, with the same model and the same scores.

Bash
cat > curves.py <<'PY'
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import (
    PrecisionRecallDisplay,
    RocCurveDisplay,
    average_precision_score,
    roc_auc_score,
)

from data import load_data, make_model

X_train, X_test, y_train, y_test = load_data()
model = make_model().fit(X_train, y_train)
scores = model.predict_proba(X_test)[:, 1]

fig, (ax_pr, ax_roc) = plt.subplots(1, 2, figsize=(11, 5))
PrecisionRecallDisplay.from_predictions(
    y_test, scores, name="logistic regression", ax=ax_pr, plot_chance_level=True
)
RocCurveDisplay.from_predictions(
    y_test, scores, name="logistic regression", ax=ax_roc, plot_chance_level=True
)
ax_pr.set_title("Precision-recall")
ax_roc.set_title("ROC")
fig.savefig("curves.png", dpi=150, bbox_inches="tight")
print("saved curves.png")

print(f"fraud rate:        {y_test.mean():.3f}")
print(f"average precision: {average_precision_score(y_test, scores):.3f}")
print(f"ROC AUC:           {roc_auc_score(y_test, scores):.3f}")

# Same model, same scores, but keep only as many legit rows as fraud rows.
rng = np.random.default_rng(7)
fraud = np.flatnonzero(y_test == 1)
legit = rng.choice(np.flatnonzero(y_test == 0), size=len(fraud), replace=False)
keep = np.concatenate([fraud, legit])
print("on a 50/50 sample of the test set:")
print(f"  average precision: {average_precision_score(y_test[keep], scores[keep]):.3f}")
print(f"  ROC AUC:           {roc_auc_score(y_test[keep], scores[keep]):.3f}")
PY
uv run python curves.py

Check it worked

curves.png holds two charts side by side, each with a dashed chance line. The output is something like:

Text
saved curves.png
fraud rate:        0.020
average precision: 0.483
ROC AUC:           0.911
on a 50/50 sample of the test set:
  average precision: 0.931
  ROC AUC:           0.922

ROC AUC barely moves when the class balance changes, because both of its axes are rates within one class. Average precision nearly doubles, because precision depends on how many negatives there are to raise false alarms. That is why a ROC AUC of 0.91 can sound excellent on a fraud problem while the precision-recall chart shows that above about 45% recall, most flags are false alarms. When the positive class is rare and false alarms cost you something, lead with average precision and the precision-recall curve, and compare it with the 0.02 chance level, not with 0.5.

Step 6 · Check the probabilities with a reliability curve

If the model says 0.3, does fraud happen about 30% of the time? That property is called calibration, and it matters whenever you use the probability itself: to rank cases for review, to estimate expected losses, or to pick a threshold from costs as in the next step. ROC AUC and average precision only look at the order of the scores, so they cannot see it.

A reliability curve groups predictions into bins and plots each bin's mean predicted probability against the fraction that really was fraud. A calibrated model sits on the diagonal. The Brier score, the mean squared gap between probability and outcome, sums it up in one number (lower is better).

A common fix for rare classes is class_weight="balanced", which makes each fraud row count as much as roughly 49 legit rows during training. Compare it with the plain model:

Bash
cat > calibration.py <<'PY'
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
from sklearn.calibration import CalibrationDisplay
from sklearn.metrics import brier_score_loss, roc_auc_score

from data import load_data, make_model

X_train, X_test, y_train, y_test = load_data()
plain = make_model().fit(X_train, y_train)
balanced = make_model(class_weight="balanced").fit(X_train, y_train)

fig, ax = plt.subplots(figsize=(6, 6))
for name, model in [("plain", plain), ("balanced weights", balanced)]:
    CalibrationDisplay.from_estimator(
        model, X_test, y_test, n_bins=10, strategy="quantile", name=name, ax=ax
    )
    scores = model.predict_proba(X_test)[:, 1]
    print(
        f"{name:<17} ROC AUC {roc_auc_score(y_test, scores):.3f}  "
        f"Brier {brier_score_loss(y_test, scores):.4f}  "
        f"mean predicted {scores.mean():.3f}"
    )
print(f"actual fraud rate {y_test.mean():.3f}")
ax.set_title("Reliability curve")
fig.savefig("calibration.png", dpi=150, bbox_inches="tight")
print("saved calibration.png")
PY
uv run python calibration.py

strategy="quantile" puts the same number of predictions in each bin. With uniform bins, almost every prediction of a rare-class model lands in the first bin and the curve has one or two usable points.

Check it worked

The output is something like:

Text
plain             ROC AUC 0.911  Brier 0.0137  mean predicted 0.020
balanced weights  ROC AUC 0.929  Brier 0.1164  mean predicted 0.211
actual fraud rate 0.020
saved calibration.png

In calibration.png the plain model's points hug the diagonal near zero, and its mean prediction matches the true fraud rate. The balanced model ranks slightly better here, but its curve sags far below the diagonal: it says 0.2 on average when the true rate is 0.02, so its Brier score is about eight times worse. Balanced weights can be fine for ranking, but do not read its outputs as probabilities without recalibrating them (CalibratedClassifierCV does that).

Step 7 · Choose a threshold from the cost of mistakes

The 0.5 cut-off is a default, not a decision. The right threshold depends on what each mistake costs you. Suppose a missed fraud costs 50 units (the money lost) and a false alarm costs 2 (a reviewer's time, an annoyed customer). Put the costs in a function and let TunedThresholdClassifierCV search for the threshold that minimises them.

It runs cross-validation on the training data only, tries 100 thresholds in each fold, and keeps the one with the best average score. The test set stays untouched, so the comparison at the end is fair. Choosing the threshold by looking at test results would make them look better than they will be on new data.

Bash
cat > threshold.py <<'PY'
from sklearn.metrics import confusion_matrix, make_scorer, precision_score, recall_score
from sklearn.model_selection import TunedThresholdClassifierCV

from data import load_data, make_model

MISSED_FRAUD_COST = 50  # a fraud you did not catch
FALSE_ALARM_COST = 2  # a legit payment someone has to review


def cost(y_true, y_pred):
    tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel()
    return MISSED_FRAUD_COST * fn + FALSE_ALARM_COST * fp


X_train, X_test, y_train, y_test = load_data()

default = make_model().fit(X_train, y_train)
tuned = TunedThresholdClassifierCV(
    make_model(),
    scoring=make_scorer(cost, greater_is_better=False),
    cv=5,
).fit(X_train, y_train)

print(f"chosen threshold: {tuned.best_threshold_:.3f}")
for name, model in [("default 0.5", default), ("tuned", tuned)]:
    y_pred = model.predict(X_test)
    print(
        f"{name:<12} cost {cost(y_test, y_pred):>5}  "
        f"precision {precision_score(y_test, y_pred):.3f}  "
        f"recall {recall_score(y_test, y_pred):.3f}"
    )
PY
uv run python threshold.py

greater_is_better=False tells scikit-learn that a lower cost is better. The tuned object behaves like any classifier: tuned.predict(X) applies the chosen threshold.

Check it worked

The output is something like:

Text
chosen threshold: 0.040
default 0.5  cost  4466  precision 0.795  recall 0.258
tuned        cost  2308  precision 0.168  recall 0.767

The chosen threshold is far below 0.5. On the untouched test set, the tuned model catches about three times as much fraud and roughly halves the total cost, while precision drops to about one flag in six. With a missed fraud worth 25 false alarms, that trade is worth making. Change the two costs and run it again: with a false alarm costing 20, the chosen threshold rises to about 0.33 and precision goes back up to about 0.7, at the price of recall. Agree these costs with whoever owns the outcome, because they decide the threshold more than any metric does.

The threshold only means something if the probabilities are stable. If your incoming data changes, rerun the reliability check and the tuning, not just the training.

When you are finished, delete the project:

Bash
cd ~
rm -rf ~/classifier-metrics-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.