Skip to content
Visual explainer 3h 30m to learn 5 steps

Precision, recall, ROC-AUC and calibration on imbalanced data

Evaluate an imbalanced classifier with a confusion matrix, PR and ROC curves and calibration, then set a threshold from business costs.

By Invicly Tech, , in AI and Machine Learning with Python. About 13 minutes to read.

Topic 12 of 34

In short

When positives are rare, accuracy is misleading: a model that never predicts fraud is 99 percent accurate if only 1 percent of cases are fraud. The confusion matrix, precision, recall and F1 show what kinds of mistakes the model makes, while ROC and precision-recall curves show how that changes across thresholds. Calibration checks whether a score of 0.2 really means about a 20 percent chance, which you need before turning scores into costs.

Think of it like this: Precision asks how many of the people you stopped at the gate were really suspects; recall asks how many of the real suspects you stopped.

Explained simply

Imagine 1,000 card payments where 10 are fraud. A model that says not fraud every time is right 990 times: 99 percent accuracy, and completely useless. When one class is rare, accuracy hides the thing you care about. You need metrics that look at the rare class directly.

The confusion matrix counts four kinds of outcome: fraud caught (true positive), honest payment flagged (false positive), fraud missed (false negative) and honest payment let through (true negative). Every other classification metric is built from these four numbers.

Precision says how often the model is right when it raises an alarm. Recall says how many of the real frauds it catches. Raising the alarm more often lifts recall but lowers precision. F1 combines the two into one number that is only high when both are high.

Curves show the whole trade-off at once. The ROC curve and the precision-recall curve plot what happens at every possible threshold. Calibration is a different check: it asks whether a score of 0.3 really means about 30 percent of such cases are fraud. You need that before turning scores into money.

Press Play on a diagram to walk through it one step at a time.

CompareWhat each metric answers
Precision and recall
  • Precision = TP / (TP + FP)
  • Recall = TP / (TP + FN)
  • F1 = their harmonic mean
  • Depend on the threshold
ROC-AUC
  • True positive rate vs false positive rate
  • 0.5 = random, 1.0 = perfect ranking
  • Ignores the threshold
  • Can look high when positives are rare
PR-AUC (average precision)
  • Precision vs recall across thresholds
  • Random baseline = share of positives
  • Focuses on the rare class
  • Better guide for imbalanced data
LayersThe confusion matrix, cell by cell
  1. 1
    True positive (TP)

    Predicted positive, really positive

  2. 2
    False positive (FP)

    Predicted positive, really negative: a false alarm

  3. 3
    False negative (FN)

    Predicted negative, really positive: a miss

  4. 4
    True negative (TN)

    Predicted negative, really negative

FlowEvaluating an imbalanced classifier
  1. 1
    Baseline

    Positive rate and a dummy model

  2. 2
    Ranking

    PR-AUC and ROC-AUC on validation data

  3. 3
    Calibration

    Reliability curve and Brier score

  4. 4
    Threshold

    Minimise expected cost

  5. 5
    Final check

    Confusion matrix on the test set

In depth

Reading a confusion matrix

In scikit-learn, confusion_matrix(y_true, y_pred) puts true classes in rows and predicted classes in columns, ordered by label. For a 0 and 1 problem, the layout is TN, FP in the first row and FN, TP in the second, so confusion_matrix(...).ravel() returns tn, fp, fn, tp.

From these four counts: precision = TP / (TP + FP); recall = TP / (TP + FN); specificity = TN / (TN + FP); false positive rate = FP / (FP + TN). Accuracy is (TP + TN) divided by all rows. Look at the raw counts as well as the ratios. A precision of 0.5 means something different with 4 alarms than with 4,000, and the counts tell the operations team how much work the model creates.

  • Rows = true class, columns = predicted class
  • ravel() order for binary: tn, fp, fn, tp
  • ConfusionMatrixDisplay.from_predictions draws it
  • Show counts, not only percentages

ROC-AUC versus PR-AUC on imbalanced data

The ROC curve plots recall (true positive rate) against false positive rate as the threshold moves. Its area equals the chance that a random positive scores higher than a random negative. A random model gets 0.5 no matter how rare positives are.

The false positive rate divides by the number of negatives. With 99,000 negatives, 500 extra false alarms barely move it, so ROC-AUC can look excellent while the alarm list is mostly wrong. The precision-recall curve uses precision instead, which feels every false alarm. Its random baseline equals the positive rate, for example 0.01. average_precision_score summarises it; that is the usual PR-AUC in scikit-learn. For rare positives, report both, but lead with PR-AUC and the precision at the recall you need.

CompareSame model, 1 percent positives
ROC view
  • Random baseline 0.5
  • False alarms diluted by many negatives
  • Often looks high, such as 0.95
  • Good for ranking quality overall
Precision-recall view
  • Random baseline 0.01
  • Every false alarm lowers precision
  • Often much lower, such as 0.40
  • Matches the alarm queue people review

Calibration: can you trust the scores?

A model is calibrated if, among rows scored about 0.3, about 30 percent are positive. Many models are not. Boosted trees and naive Bayes can be over-confident; random forests often avoid extreme scores. Class weighting or resampling also shifts scores away from real frequencies.

Check calibration with a reliability curve: CalibrationDisplay.from_estimator bins the scores and plots the mean score against the observed positive rate in each bin; a calibrated model follows the diagonal. The Brier score, the mean squared difference between score and outcome, summarises it (lower is better). To fix it, wrap the model in CalibratedClassifierCV with method="sigmoid" (better with little data) or method="isotonic" (more flexible, needs more data). Calibration is fitted with cross-validation, never on the test set.

  • Reliability curve on the diagonal = calibrated
  • Brier score: lower is better
  • sigmoid for small data, isotonic for larger data
  • Calibration changes scores, not ranking much

Setting a threshold from business costs

Give each outcome a cost. Suppose a missed fraud costs 200 euros on average and reviewing a flagged payment costs 5 euros. For each threshold on the validation set, total cost = 200 x FN + 5 x FP. Choose the threshold with the lowest total, then confirm it on the test set.

With calibrated scores there is also a shortcut: flag a payment when its probability times the cost of a miss is larger than the cost of a review, that is p x 200 > 5, so p > 0.025. Real teams add constraints too, such as a review team that can handle at most 300 alerts a day, which caps how low the threshold can go. Write the chosen threshold, the cost assumptions and the date into the model documentation, because costs change.

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Read a confusion matrix~40m
  2. 2
    Compute precision, recall and F1~40m
  3. 3
    Compare ROC-AUC and PR-AUC~40m
  4. 4
    Check calibration~40m
  5. 5
    Set a threshold from costs~40m

Key points

  • Always report the positive rate and a dummy baseline next to any metric on imbalanced data.
  • Precision, recall and F1 describe one threshold; ROC-AUC and PR-AUC summarise all thresholds.
  • With rare positives, PR-AUC moves much more than ROC-AUC when the model improves, so it is the more useful summary.
  • A calibrated model's scores match observed frequencies; check with a reliability curve and the Brier score.
  • Set the final threshold from the cost of a false positive and a false negative, measured on validation data.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (classification_report, roc_auc_score,
                             average_precision_score, brier_score_loss)

X, y = make_classification(n_samples=20000, weights=[0.98], flip_y=0.01, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=0)
p = LogisticRegression(max_iter=1000).fit(X_tr, y_tr).predict_proba(X_te)[:, 1]
print("positive rate", y_te.mean().round(3))
print(classification_report(y_te, p >= 0.5, digits=3))
print("ROC-AUC", roc_auc_score(y_te, p).round(3),
      "PR-AUC", average_precision_score(y_te, p).round(3),
      "Brier", brier_score_loss(y_te, p).round(4))

Synthetic data with about 2 percent positives, so no real records are involved.

Fraud screening with 2 percent positives

Using synthetic payments with about 2 percent fraud, step 1: compare a DummyClassifier with logistic regression and a HistGradientBoostingClassifier. The dummy gets about 98 percent accuracy and zero recall. Step 2: compute average precision for both models; expect the dummy near 0.02 and the real models far above it. Step 3: draw both precision-recall curves on one plot. Step 4: read off the precision each model gets at 80 percent recall, because the business wants to catch at least 80 percent of fraud. That single number usually decides between models more clearly than any area.

python
import numpy as np
from sklearn.metrics import average_precision_score, precision_recall_curve

for name, m in models.items():
    p = m.fit(X_tr, y_tr).predict_proba(X_val)[:, 1]
    prec, rec, thr = precision_recall_curve(y_val, p)
    ok = rec[:-1] >= 0.80
    best = prec[:-1][ok].max() if ok.any() else 0.0
    print(f"{name:9s} AP {average_precision_score(y_val, p):.3f} "
          f"precision@80%recall {best:.3f}")

Calibrating a boosted model and choosing a cost threshold

Step 1: draw a reliability curve for HistGradientBoosting on the validation set and note where it leaves the diagonal. Step 2: wrap it in CalibratedClassifierCV with isotonic calibration and 5 folds, refit on the training set and draw the curve again. Step 3: compare Brier scores; expect the calibrated one to be equal or lower. Step 4: with a miss costing 200 and a review costing 5, sweep thresholds on validation scores and pick the cheapest. Step 5: apply it to the test set and report the confusion matrix and total cost.

python
import numpy as np
from sklearn.calibration import CalibratedClassifierCV
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import brier_score_loss, confusion_matrix

cal = CalibratedClassifierCV(HistGradientBoostingClassifier(random_state=0),
                             method="isotonic", cv=5).fit(X_tr, y_tr)
p = cal.predict_proba(X_val)[:, 1]
print("Brier", brier_score_loss(y_val, p).round(4))
costs = []
for t in np.linspace(0.01, 0.9, 90):
    tn, fp, fn, tp = confusion_matrix(y_val, p >= t).ravel()
    costs.append((200 * fn + 5 * fp, t))
print("best cost, threshold", min(costs))

Quick reference

  • Precision = TP / (TP + FP); recall = TP / (TP + FN)
  • F1 = 2 x precision x recall / (precision + recall)
  • ROC-AUC random baseline = 0.5; PR-AUC random baseline = positive rate
  • average_precision_score is the usual PR-AUC summary in scikit-learn
  • confusion_matrix(y, pred).ravel() gives tn, fp, fn, tp for binary labels
  • Brier score = mean of (score - outcome) squared; lower is better
  • CalibratedClassifierCV: sigmoid for small data, isotonic for larger data
  • Flag when p x cost of a miss > cost of a review (needs calibrated p)

Common mistakes

  • Celebrating 98 percent accuracy when 98 percent of rows are negative.
  • Comparing ROC-AUC between datasets with very different positive rates, or using it alone on rare-event problems.
  • Turning raw scores into expected costs without checking calibration first.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Positives are 1 percent of the data. Model A has ROC-AUC 0.96 and PR-AUC 0.35. What is the best reading?

Question 2

2A model flags 200 cases, 150 of them correctly, out of 300 real positives. What are precision and recall?

Question 3

3Among rows scored about 0.8, only 50 percent are positive. What does this show?

Question 4

4A miss costs 100 and a review costs 4. With calibrated scores, above what probability should you flag?

Question 5

5Why is accuracy a poor main metric for rare-event detection?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Make a synthetic dataset with 5 percent positives, train logistic regression and print the confusion matrix and classification report on the test set.

  2. Exercise 2medium

    Plot the ROC curve and precision-recall curve for the same model on one figure with two panels and print ROC-AUC and average precision next to the positive rate.

  3. Exercise 3hard

    Compare reliability curves and Brier scores for a random forest before and after sigmoid calibration, then pick the cost-minimising threshold with a miss costing 50 and a false alarm costing 2.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use F1 or PR-AUC?
PR-AUC summarises the model across all thresholds, so it is good for comparing models. F1 describes one chosen threshold. Report PR-AUC for model choice and precision, recall or cost at your chosen threshold for the decision.
Is ROC-AUC useless for imbalanced data?
No. It still measures ranking quality and is stable across datasets. It just hides how many false alarms you get, so pair it with PR-AUC or precision at a fixed recall.
Does class_weight="balanced" fix imbalance?
It makes the model pay more attention to the rare class during training, which can help ranking. It also shifts scores away from true probabilities, so recalibrate and retune the threshold afterwards.
What is a good F1 score?
It depends on the problem and the positive rate. Compare with a dummy baseline and with what the business needs, rather than a fixed number.

Go deeper

ShareXLinkedInWhatsApp