Data Science
Precision / Recall / F1
This takes O(n) time — one pass over the predictions to count TP, FP, and FN, then a handful of arithmetic operations.
The idea, in plain English
Picture an airport security scanner flagging bags for a manual search. Precision asks: 'of all the bags you flagged, how many actually had something dangerous?' It punishes false alarms. Recall asks a different question: 'of all the actually dangerous bags, how many did you catch?' It punishes misses. You can game either one alone. You could flag every single bag for perfect recall, or flag almost nothing for perfect precision. F1 combines both into one number, called the harmonic mean, that only stays high when precision and recall are both reasonably good.
How it works
- 1Start from the same counts as a confusion matrix: true positives (TP), false positives (FP), and false negatives (FN).
- 2Precision = TP / (TP + FP). Out of everything you predicted positive, this shows what fraction was actually positive.
- 3Recall = TP / (TP + FN). Out of everything that was actually positive, this shows what fraction you predicted positive.
- 4F1 = 2 * precision * recall / (precision + recall). This is the harmonic mean, and it stays low if either precision or recall is low, unlike a plain average would.
When you'd use it
Reach for these whenever accuracy alone would be misleading, especially with imbalanced data like fraud detection or disease screening. There, missing a rare positive (low recall) or crying wolf too often (low precision) matters far more than the overall percentage correct. Which of precision or recall matters more depends on whether false alarms or missed cases cost you more.
Common beginner mistakes
- Do not optimize only for accuracy on imbalanced data. A model that always predicts 'no' can still have terrible recall while looking fine on accuracy.
- Do not report precision or recall alone without the other. A model can reach 100% recall by predicting positive for everything, which tanks its precision, and vice versa. F1 catches that trade-off; either number alone can hide it.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Total examples: 20
TP: 9
FP: 1
FN: 3
TN: 7
Precision: 0.90
Recall: 0.75
F1 score: 0.82Not sure this is the right topic? See the learning paths → or where this leads →