Skip to content

Accuracy, precision, recall and friends

Start with four counts. Every threshold metric is a different ratio of them, built for a different question. Read Pima's glucose rule through each one.

Applied ~12 min8 steps

What runs in CodeSplash

You will be able to

  • Build a confusion matrix and compute precision, recall and specificity
  • Choose between F1, balanced accuracy and MCC
  • Say what each metric ignores

Read first

01

Four counts, two questions

Read

Pick a threshold and every row lands in one of four cells. Here, the rule "glucose of 126 or more" against a diabetes diagnosis, across 532 women:

Actually positiveActually negative
Predicted positive118 true positives82 false positives
Predicted negative59 false negatives273 true negatives

This is a confusion matrixConfusion matrixCounts of predicted against actual classes. For two classes, these are TP, FP, FN and TN.. Everything below is a ratio of these four numbers.

Recall=TPTP+FNPrecision=TPTP+FP\text{Recall} = \frac{TP}{TP+FN} \qquad \text{Precision} = \frac{TP}{TP+FP}

Recall asks: of the real cases, how many did you find? Here 0.667. Precision asks: of the rows you flagged, how many were real? Here 0.590.

They pull against each other. Flag more rows, and recall rises while precision usually falls. Specificity is recall for the negatives: 0.769. Medicine says sensitivity for recall and PPV for precision.

02

Compute one

Predict

Predict first

Using the table above, what is the accuracy, the share of rows on the diagonal?

Make your guess between 0 and 1 accuracy, then reveal.

Reveal

0.735. But a third of these rows are positive (prevalence 0.333), so always saying "negative" would already get about 0.67. Accuracy needs its baseline.

03

Move the threshold

Explore

Set Share of positives low and drag Decision threshold. Watch Recall and Precision trade, and watch Accuracy sit close to Always negative the whole time. MCC sees what accuracy can't.

HExplorable · Rare events and the decision threshold

Why can a 98% accurate model be useless, and where should the threshold go?

A lazy model calls every case negative. What accuracy does it score?

0.500
How sure?
0.020
1.5
1.50
20
5000
threshold
flaggedpassed
pos5262
neg3124574

Bars are drawn to one count scale, so a rare positive class looks as rare as it is. The ROC curve barely notices the imbalance; the precision–recall curve shows it. Cheapest threshold here: 1.14; the binormal formula gives 1.35.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

04

One-number summaries

Read
MetricWhat it doesBlind spot
F1F1 scoreThe harmonic mean of precision and recall. It has no term for true negatives.Harmonic mean of precision and recallIgnores true negatives
Balanced accuracyBalanced accuracyThe average of recall across classes; 0.5 is chance for two classes, whatever the imbalance.Mean of recall and specificityIgnores precision
MCCMatthews correlationThe correlation between a binary prediction and the truth, using all four cells of the table. 0 means no better than chance.Correlation between prediction and truth; uses all four cellsHard to explain to a stakeholder

For this rule: F1 0.626, balanced accuracy 0.718, MCC 0.424.

Any one-number summary assumes a trade-off between errors. If you know the actual costs, use them instead.

05

Multiclass

Read

With more classes, compute each ratio per class, then average. Macro gives every class equal weight, so rare classes count fully. The Evaluation tab's per-class table has precision, recall, F1, and n for each class. Check the classes with small n: their numbers are noisy, and a good average can hide a class the model never gets right.

06

Check your understanding

Checkpoint

Check yourself

A rule has 118 true positives and 82 false positives. What is its precision? Give two decimals.

Show the answer

Answer: 0.59

118/(118+82)=0.59118 / (118 + 82) = 0.59. Of 200 rows flagged, 118 were real.

Check yourself

The same rule has 59 false negatives. What is its recall? Give two decimals.

Show the answer

Answer: 0.666666666666667

118/(118+59)≈0.67118 / (118 + 59) \approx 0.67. It misses about a third of real cases.

Check yourself

A screening test leads to a cheap follow-up. Missing a case is very costly. Which metric should get most of your attention?

Show the answer

Answer: a

You want to catch nearly every case, and false alarms are cheap. If follow-up were invasive, precision would weigh more.

Check yourself

What can't F1 see?

Show the answer

Answer: c

F1 is built only from precision and recall. Two models with very different specificity can have the same F1.

07

Read them on a run

In the app

On a binary run, Overview lists accuracy, balanced accuracy, F1, precision, recall, MCC and more at the default threshold. Evaluation shows the confusion matrix, which changes when you type a value in Threshold. Then use Primary metric in Setup to rank the leaderboard by what you care about.

Python
import pandas as pd
from sklearn.metrics import classification_report, confusion_matrix

df = pd.read_csv("pima.csv")
pred, y = df["glu"] >= 126, df["diabetic"]
print(confusion_matrix(y, pred))
print(classification_report(y, pred, digits=3))
R
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
pred <- df$glu >= 126; y <- df$type == "Yes"
tp <- sum(pred & y); fp <- sum(pred & !y); fn <- sum(!pred & y); tn <- sum(!pred & !y)
c(tp = tp, fp = fp, fn = fn, tn = tn, precision = tp / (tp + fp), recall = tp / (tp + fn),
  f1 = 2 * tp / (2 * tp + fp + fn), accuracy = (tp + tn) / (tp + fp + fn + tn))

Notebook exercise · ~10 min

Precision and recall in code

Score a simple glucose rule for diabetes with precision and recall, and keep the two apart.

  1. Precision

    Of the women the rule flags, what share have diabetes? Store this precision in precision.

    Show a solution
    Python
    precision = tp / (tp + fp)
    R
    precision <- tp / (tp + fp)
  2. Recall

    Of the women with diabetes, what share does the rule flag? Store this recall (sensitivity) in recall.

    Show a solution
    Python
    recall = tp / (tp + fn)
    R
    recall <- tp / (tp + fn)

In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.

08

Recap

Recap
  • Four counts underlie every threshold metric.
  • Recall finds cases, and precision trusts flags. They trade off as the threshold moves.
  • F1, balanced accuracy and MCC each hide something. With known costs, use the costs.

Concepts in this lesson