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.
What runs in CodeSplash
- Diagnostic accuracy (sensitivity, specificity, PPV, NPV) Verified in Python and R
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
Four counts, two questions
ReadPick 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 positive | Actually negative | |
|---|---|---|
| Predicted positive | 118 true positives | 82 false positives |
| Predicted negative | 59 false negatives | 273 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 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.
Compute one
PredictPredict 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.
Move the threshold
ExploreSet 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?
| flagged | passed | |
|---|---|---|
| pos | 52 | 62 |
| neg | 312 | 4574 |
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 to see the result.
One-number summaries
Read| Metric | What it does | Blind spot |
|---|---|---|
| F1F1 scoreThe harmonic mean of precision and recall. It has no term for true negatives. | Harmonic mean of precision and recall | Ignores true negatives |
| Balanced accuracyBalanced accuracyThe average of recall across classes; 0.5 is chance for two classes, whatever the imbalance. | Mean of recall and specificity | Ignores 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 cells | Hard 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.
Multiclass
ReadWith 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.
Check your understanding
CheckpointCheck yourself
A rule has 118 true positives and 82 false positives. What is its precision? Give two decimals.
Show the answer
Answer: 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
. 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.
Read them on a run
In the appOn 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.
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))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.
- Precision
Of the women the rule flags, what share have diabetes? Store this precision in
precision.Show a solution
Pythonprecision = tp / (tp + fp)Rprecision <- tp / (tp + fp) - Recall
Of the women with diabetes, what share does the rule flag? Store this recall (sensitivity) in
recall.Show a solution
Pythonrecall = tp / (tp + fn)Rrecall <- tp / (tp + fn)
In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.
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