Skip to content

MLDay 13 of 50Supervised and Unsupervised Learning

Classification Metrics

Thresholds, ROC and PR Curves

8 min read

At a bank where 13% of payments are fraud, a model that calls every payment "legit" is 87% accurate. It also never catches a single fraud. To judge a classifier, count each kind of mistake and price it.

The idea

A classifier such as D12's logistic regression gives a probability pp. A threshold turns it into a decision: flag the payment when pp is above the threshold. D12 used 0.5, but nothing makes 0.5 right.

Every decision lands in one cell of the confusion matrix, a 2 × 2 table of truth against prediction:

Flagged as fraud Passed as legit
Really fraud TP, true positive (caught) FN, false negative (missed fraud)
Really legit FP, false positive (false alarm) TN, true negative

Two scores read the table:

  • Precision: of the payments you flagged, the share that were fraud. Low precision means many false alarms.
  • Recall: of the real frauds, the share you flagged. Low recall means many missed frauds.

Lower the threshold and you flag more: recall rises, and precision usually falls. Where to stop depends on what each mistake costs. A missed $200 fraud hurts far more than a $20 check call, so a bank flags generously. A spam filter that hides real email should flag sparingly.

Accuracy, the share of right answers, mostly rewards the big class. On rare positives, always compare a model with the "always say no" baseline, and judge it by precision and recall.

To score a model across every threshold at once, sweep the threshold from 1 down to 0 and draw a curve:

  • The PR curve plots precision against recall. Its area, PR-AUC, is 1 for a perfect model and about the positive share (0.13 here) for random guessing.
  • The ROC curve plots recall against the false-alarm rate: FP divided by all legit payments. Its area, ROC-AUC, is 0.5 for guessing.

With few positives, the false-alarm rate divides by a huge number of legit payments, so false alarms barely move it. ROC then looks rosier than PR.

A tiny example

Take 100 payments, 12 of them fraud. The model flags 10: 8 are fraud (TP = 8) and 2 are legit (FP = 2). It misses 4 frauds (FN = 4) and correctly passes 86 legit payments (TN = 86).

  • Accuracy: (8 + 86) / 100 = 94%.
  • "Always legit" scores 88 / 100 = 88%, with zero frauds caught. The model beats it by only 6 points.
  • Precision: 8 of 10 flags were right, 0.80. Recall: 8 of 12 frauds were caught, about 0.67.

The formula

P=TPTP+FPR=TPTP+FNP = \frac{TP}{TP + FP} \qquad R = \frac{TP}{TP + FN}
Symbol Meaning
PP precision: the share of flagged rows that are really positive
RR recall: the share of real positives that were flagged
TPTP, FPFP, FNFN true positives, false positives (false alarms), false negatives (misses)

Worked: P=88+2=0.80P = \frac{8}{8 + 2} = 0.80 and R=88+4≈0.67R = \frac{8}{8 + 4} \approx 0.67.

When you can't price the mistakes, F1 blends the two into one score. It is low if either one is low:

F1=2PRP+RF_1 = \frac{2PR}{P + R}
Symbol Meaning
F1F_1 the F1 score, from 0 (worst) to 1 (perfect)
PP, RR precision and recall

Worked: F1=2×0.80×0.670.80+0.67≈0.73F_1 = \frac{2 \times 0.80 \times 0.67}{0.80 + 0.67} \approx 0.73.

Try it

Move the threshold, watch the mistakes trade

Top row: fraud, label 1. Bottom row: legit, label 0. Move the curve so it sits near 1 over the top row and near 0 over the bottom row, and watch the log loss fall.

02400.51Payment amount ($100s)probability px = 0.1, legit, p = 0.013x = 0.2, legit, p = 0.015x = 0.3, legit, p = 0.017x = 0.4, legit, p = 0.02x = 0.5, legit, p = 0.023x = 0.6, legit, p = 0.027x = 0.7, legit, p = 0.031x = 0.9, legit, p = 0.041x = 1, legit, p = 0.047x = 1.1, legit, p = 0.055x = 1.2, legit, p = 0.063x = 1.4, legit, p = 0.083x = 2, legit, p = 0.182x = 2.4, legit, p = 0.289x = 2.8, legit, p = 0.426x = 3.4, legit, p = 0.646 (wrong side)x = 1.9, fraud, p = 0.161 (wrong side)x = 2.6, fraud, p = 0.354 (wrong side)x = 3.8, fraud, p = 0.769x = 4.6, fraud, p = 0.917

p = σ(1.5·x + -4.5)mean log loss 0.29right at p > 0.5: 17 of 20boundary x = 3

Confusion matrix at p > 0.5
predicted legitpredicted fraud
actually legitTN (true negative)15FP (false positive)1
actually fraudFN (false negative)2TP (true positive)2

precision TP/(TP + FP) 0.67recall TP/(TP + FN) 0.5

Points outlined in red are on the wrong side of the boundary.

The curve is already fitted (w=1.5w = 1.5, b=−4.5b = -4.5), so leave it and move only the threshold. At 0.5 it catches 2 of the 4 frauds: precision 0.67, recall 0.50, 17 of 20 right. Price each miss at $200 and each false alarm at $20, and that costs $420. Slide down to 0.3 ($240), then to 0.1. Now all four frauds are caught, precision drops to 0.50, and only 16 of 20 are right, no better than "always legit". Yet the cost falls to $80.

In code

These are D12's payments made harder: small frauds and big legit buys now overlap. There are 2,000 seeded payments, about 13% fraud. The model trains on half and is judged on the other half, the validation rows. Pick the threshold on validation rows, never on the final test set (D06).

# script_id: day_013_classification_metrics/fraud_metrics
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, average_precision_score, confusion_matrix, recall_score, roc_auc_score
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(42)
fraud = (rng.random(2000) < 0.13).astype(int)                 # 1 = fraud, about 13%
X = pd.DataFrame({
    "amount": np.where(fraud, rng.uniform(50, 499, 2000), rng.lognormal(np.log(60), 1.0, 2000)),
    "km_from_home": np.where(fraud, rng.exponential(60, 2000), rng.exponential(10, 2000)),
})
X_tr, X_va, y_tr, y_va = train_test_split(X, fraud, test_size=0.5, random_state=42)
p = LogisticRegression().fit(X_tr, y_tr).predict_proba(X_va)[:, 1]   # chance of fraud

never = np.zeros(len(y_va))                                    # "always legit"
# PR-AUC below is average precision, scikit-learn's step-wise area under the PR curve
print(f"fraud share:  {y_va.mean():.3f}")
print(f"always legit: accuracy {accuracy_score(y_va, never):.3f}  recall {recall_score(y_va, never):.2f}  "
      f"PR-AUC {average_precision_score(y_va, never):.3f}")
print(f"model at 0.5: accuracy {accuracy_score(y_va, p >= 0.5):.3f}  recall {recall_score(y_va, p >= 0.5):.2f}  "
      f"PR-AUC {average_precision_score(y_va, p):.3f}  ROC-AUC {roc_auc_score(y_va, p):.3f}")
fraud share:  0.126
always legit: accuracy 0.874  recall 0.00  PR-AUC 0.126
model at 0.5: accuracy 0.917  recall 0.55  PR-AUC 0.732  ROC-AUC 0.922

The model is 91.7% accurate, only 4 points above saying "legit" to everything, and it misses 45% of the frauds. PR-AUC shows the real gain: 0.73 against the baseline's 0.126, which is just the fraud share. ROC-AUC (0.92) sounds better than the model is.

Now sweep the threshold and price the mistakes as in the playground: $200 per missed fraud, $20 per false alarm.

# script_id: day_013_classification_metrics/fraud_metrics
for t in [0.5, 0.3, 0.1]:
    tn, fp, fn, tp = confusion_matrix(y_va, p >= t).ravel()
    print(f"threshold {t}: TP {tp:3d}  FP {fp:3d}  FN {fn:3d}  precision {tp / (tp + fp):.2f}  "
          f"recall {tp / (tp + fn):.2f}  accuracy {(tp + tn) / len(y_va):.3f}  cost ${200 * fn + 20 * fp:,}")

weighted = LogisticRegression(class_weight="balanced").fit(X_tr, y_tr).predict_proba(X_va)[:, 1]
print(f"balanced at 0.5: recall {recall_score(y_va, weighted >= 0.5):.2f}  "
      f"PR-AUC {average_precision_score(y_va, weighted):.3f}")
threshold 0.5: TP  69  FP  26  FN  57  precision 0.73  recall 0.55  accuracy 0.917  cost $11,920
threshold 0.3: TP  90  FP  41  FN  36  precision 0.69  recall 0.71  accuracy 0.923  cost $8,020
threshold 0.1: TP 105  FP 107  FN  21  precision 0.50  recall 0.83  accuracy 0.872  cost $6,340
balanced at 0.5: recall 0.83  PR-AUC 0.691

The cheapest of the three, 0.1, has the worst accuracy, below even "always legit". Accuracy would have picked 0.3 and cost $1,680 more. class_weight="balanced" makes each fraud count about 7× as much in training. At 0.5 it catches about what 0.1 did (104 frauds vs 105), so it moves the cut-off for you, but it doesn't rank payments any better (PR-AUC 0.69).

Both curves for the same model, from the same validation rows:

# script_id: day_013_classification_metrics/fraud_metrics
import os
from pathlib import Path

import matplotlib.pyplot as plt
from sklearn.metrics import precision_recall_curve, roc_curve

FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
fpr, tpr, _ = roc_curve(y_va, p)
prec, rec, _ = precision_recall_curve(y_va, p)
fig, (roc, pr) = plt.subplots(1, 2, figsize=(6, 4))
roc.plot(fpr, tpr)
roc.plot([0, 1], [0, 1], "--", color="gray")                 # guessing
roc.set(title="ROC (area 0.92)", xlabel="false-alarm rate", ylabel="recall")
pr.plot(rec, prec)
pr.axhline(y_va.mean(), ls="--", color="gray")                # guessing: the fraud share
pr.set(title="PR (area 0.73)", xlabel="recall", ylabel="precision", ylim=(0, 1.05))
fig.suptitle("Same model: ROC looks great, PR shows the false alarms")
fig.tight_layout()
fig.savefig(FIG_DIR / "roc_vs_pr.png", dpi=120)

Same model: ROC looks great, PR shows the false alarms

The ROC curve hugs the top-left corner. The PR curve shows that past a recall of about 0.85, precision sinks below one half.

Quick check

Quick check

1. 1,000 payments include 130 frauds. A model calls every payment legit. What are its accuracy and recall?

2. You lower the threshold from 0.5 to 0.1. What usually happens?

3. 13% of payments are fraud. What PR-AUC does a model that only guesses score?

Next

Day 14: Prepare Messy Tabular Data fills gaps and encodes text categories, so real tables can reach models like this one.

Next · Day 14 · 7 minPrepare Messy Tabular Data← Previous: Day 12 · Logistic Regression
Not tapped yet