Here's a classic trap. You build a fraud detector, test it, and it scores 99% accuracy. You present it proudly. Then someone points out that only 1% of transactions are fraudulent, so a model that says "not fraud" every single time would also score 99%.
That's why accuracy alone is rarely enough, and why every ML course, Kaggle competition and data science interview expects you to know precision, recall, F1 and ROC-AUC. In this guide we'll compute each one by hand in NumPy on a tiny example, check them against scikit-learn, and, most importantly, learn which one to use when.
Start with the confusion matrix
Every binary classification metric comes from four counts:
| Predicted positive | Predicted negative | |
|---|---|---|
| Actually positive | True positive (TP) | False negative (FN) |
| Actually negative | False positive (FP) | True negative (TN) |
- False positive: a false alarm (a legitimate email sent to spam).
- False negative: a miss (a fraudulent payment that got through).
Let's make a small example: ten students, a model predicting who will fail an exam (1 = at risk), with its probability scores:
import numpy as np
y_true = np.array([1, 0, 1, 1, 0, 0, 1, 0, 0, 1])
y_score = np.array([0.92, 0.40, 0.65, 0.30, 0.55, 0.10, 0.80, 0.35, 0.20, 0.70])
y_pred = (y_score >= 0.5).astype(int)
print(y_pred) # [1 0 1 0 1 0 1 0 0 1]
def confusion(y_true, y_pred):
tp = int(((y_pred == 1) & (y_true == 1)).sum())
fp = int(((y_pred == 1) & (y_true == 0)).sum())
fn = int(((y_pred == 0) & (y_true == 1)).sum())
tn = int(((y_pred == 0) & (y_true == 0)).sum())
return tp, fp, fn, tn
print(confusion(y_true, y_pred)) # (4, 1, 1, 4)Four students correctly flagged, one false alarm, one missed, four correctly left alone.
Accuracy: the share of predictions that were right
Accuracy = (TP + TN) / total
Here: (4 + 4) / 10 = 0.8.
Accuracy is fine when classes are roughly balanced and both kinds of error cost about the same. Here's how badly it fails when they aren't:
y_rare = np.array([1] * 10 + [0] * 990) # 1% positives
always_zero = np.zeros_like(y_rare)
print((always_zero == y_rare).mean()) # 0.9999% accuracy, zero positives found. Never report accuracy alone on imbalanced data.
Precision: when you flag something, how often are you right?
Precision = TP / (TP + FP)
Here: 4 / (4 + 1) = 0.8. Of the five students flagged, four really were at risk.
Care about precision when false alarms are expensive: spam filters (losing a real email is bad), recommending a costly medical procedure, or banning a user account.
Recall: of all the real positives, how many did you find?
Recall = TP / (TP + FN)
Here: 4 / (4 + 1) = 0.8. We found four of the five at-risk students. Recall is also called sensitivity or the true positive rate.
Care about recall when misses are expensive: cancer screening, fraud detection, safety monitoring. Missing a real case is worse than a false alarm that a human can quickly dismiss.
F1: one number that balances both
F1 = 2 × precision × recall / (precision + recall)
It's the harmonic mean of precision and recall. Unlike a simple average, it stays low if either one is low. A model with precision 1.0 and recall 0.1 gets an F1 of about 0.18, not 0.55.
tp, fp, fn, tn = confusion(y_true, y_pred)
precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1 = 2 * precision * recall / (precision + recall)
print(precision, recall, f1) # 0.8 0.8 0.8000000000000002(That trailing ...0002 is ordinary floating-point rounding, not a bug.)
Use F1 when you need a single number for imbalanced data and care about both kinds of error.
The threshold changes everything
Precision and recall depend on the cut-off you choose. Watch what happens as we move it:
for t in [0.3, 0.5, 0.7]:
yp = (y_score >= t).astype(int)
tp, fp, fn, tn = confusion(y_true, yp)
p = tp / (tp + fp) if tp + fp else 0.0
r = tp / (tp + fn)
print(f"threshold={t}: precision={p:.2f} recall={r:.2f}")threshold=0.3: precision=0.62 recall=1.00
threshold=0.5: precision=0.80 recall=0.80
threshold=0.7: precision=1.00 recall=0.60This is the precision–recall trade-off. A low threshold catches everyone at risk but raises more false alarms; a high threshold is always right when it flags someone but misses students. There's no universally "correct" threshold. It's a product decision about which mistake costs more.
In an interview, saying "I'd pick the threshold based on the relative cost of false positives and false negatives, and validate it on held-out data" is a strong answer.
ROC-AUC: quality across every threshold
Since the threshold is a choice, it's useful to measure how good the scores are regardless of threshold. That's what ROC-AUC does.
The ROC curve plots the true positive rate (recall) against the false positive rate at every possible threshold, and AUC is the area under it. But there's a more intuitive definition:
AUC is the probability that a randomly chosen positive example gets a higher score than a randomly chosen negative one.
That gives us a neat way to compute it, by comparing every positive with every negative:
def roc_auc(y_true, y_score):
pos = y_score[y_true == 1]
neg = y_score[y_true == 0]
wins = (pos[:, None] > neg[None, :]).sum() + 0.5 * (pos[:, None] == neg[None, :]).sum()
return wins / (len(pos) * len(neg))
print(roc_auc(y_true, y_score)) # 0.88(Ties count as half a win. The [:, None] trick builds every pair at once; see our broadcasting guide.)
How to read AUC:
- 0.5: no better than random guessing.
- 0.7–0.8: useful.
- 0.8–0.9: good.
- 1.0: perfect ranking (and in practice, a reason to check for data leakage).
One caveat: on heavily imbalanced data, ROC-AUC can look reassuringly high even when precision is poor. In those cases also report PR-AUC (average precision), which focuses on the positive class.
Check your work against scikit-learn
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score
print(accuracy_score(y_true, y_pred)) # 0.8
print(precision_score(y_true, y_pred)) # 0.8
print(recall_score(y_true, y_pred)) # 0.8
print(f1_score(y_true, y_pred)) # 0.8
print(roc_auc_score(y_true, y_score)) # 0.88Everything matches. Note that roc_auc_score takes the scores, not the thresholded predictions. Passing y_pred is a common bug that quietly gives you a worse number.
Cheat sheet: which metric when?
| Situation | Metric to lead with |
|---|---|
| Balanced classes, equal error costs | Accuracy (plus F1 as a check) |
| False alarms are costly (spam, account bans) | Precision |
| Misses are costly (disease, fraud, safety) | Recall |
| Imbalanced data, need one number | F1 or PR-AUC |
| Comparing models before choosing a threshold | ROC-AUC |
| Multi-class problems | Macro-F1 (treats each class equally) or weighted-F1 |
Frequently asked questions
What is the difference between precision and recall?
Precision measures how many of your positive predictions were correct: TP / (TP + FP). Recall measures how many of the actual positives you found: TP / (TP + FN). Precision penalises false alarms; recall penalises misses.
What is a good F1 score?
It depends on the problem and the baseline. Compare against a simple baseline model and the level the use case needs. For many applied problems an F1 above 0.8 is strong, but a medical screening tool may need very high recall even if F1 is lower.
Why is accuracy misleading for imbalanced datasets?
When one class dominates, a model can predict that class every time and still achieve high accuracy while never detecting the rare class. Precision, recall, F1 and PR-AUC reveal this failure.
What does an AUC of 0.5 mean?
An AUC of 0.5 means the model ranks a random positive example above a random negative one only half the time, which is no better than random guessing. An AUC below 0.5 usually means the labels or scores are inverted.
Should I use ROC-AUC or PR-AUC?
Use ROC-AUC for roughly balanced data or when both classes matter equally. Use PR-AUC when positives are rare and you mainly care about finding them, because it is more sensitive to false positives among the few predicted positives.