Accuracy, Precision, Recall, F1 and the Confusion Matrix
A spam filter, a fraud detector and a tumour classifier all output a class, and all of them make two kinds of mistakes: calling something positive that is not (a false alarm) and missing something that is (a miss). The two mistakes rarely cost the same. A missed tumour is far worse than an extra biopsy; a legitimate email lost in the spam folder is worse than one spam message in the inbox. Accuracy lumps both together. The confusion matrix keeps them apart, and precision, recall and F1 summarise it in ways that match different costs.
The confusion matrix
For a binary problem, compare each prediction with the true label and count the four outcomes:
scikit-learn uses this layout: rows are the true class, columns the predicted class, classes in sorted order, so confusion_matrix(y, p).ravel() gives tn, fp, fn, tp. Some books put the positive class first; always check which way round a matrix is printed.
The metrics
Recall is also called sensitivity or the true positive rate; is the specificity, and the false positive rate used by ROC curves (next lesson). is the harmonic mean of precision and recall, so it is high only when both are; the general weighs recall times as much as precision ( for screening, when false alarms are expensive).
| Use mainly | When |
|---|---|
| recall | a miss is costly: disease screening, fraud, safety defects |
| precision | a false alarm is costly: spam filtering, recommending a costly action |
| both matter and positives are rare; one number for model selection | |
| accuracy | classes are roughly balanced and both errors cost about the same |
From scratch, checked against scikit-learn
Twelve emails, 1 = spam:
import numpy as np
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
y_true = np.array([1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0])
y_pred = np.array([1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0])
tp = int(np.sum((y_pred == 1) & (y_true == 1)))
fp = int(np.sum((y_pred == 1) & (y_true == 0)))
fn = int(np.sum((y_pred == 0) & (y_true == 1)))
tn = int(np.sum((y_pred == 0) & (y_true == 0)))
print("TP FP FN TN:", tp, fp, fn, tn)
print("sklearn matrix [[TN FP] [FN TP]]:", confusion_matrix(y_true, y_pred).tolist())
acc = (tp + tn) / len(y_true)
prec = tp / (tp + fp)
rec = tp / (tp + fn)
f1 = 2 * prec * rec / (prec + rec)
print(f"accuracy ours {acc:.3f} sklearn {accuracy_score(y_true, y_pred):.3f}")
print(f"precision ours {prec:.3f} sklearn {precision_score(y_true, y_pred):.3f}")
print(f"recall ours {rec:.3f} sklearn {recall_score(y_true, y_pred):.3f}")
print(f"F1 ours {f1:.3f} sklearn {f1_score(y_true, y_pred):.3f}")TP FP FN TN: 3 1 2 6
sklearn matrix [[TN FP] [FN TP]]: [[6, 1], [2, 3]]
accuracy ours 0.750 sklearn 0.750
precision ours 0.750 sklearn 0.750
recall ours 0.600 sklearn 0.600
F1 ours 0.667 sklearn 0.667
Nine of twelve emails are classified correctly (accuracy 0.75). Of the four emails flagged as spam, three really are (precision 0.75); of the five spam emails, three were caught (recall 0.6). sits between the two, closer to the smaller one, as a harmonic mean does.
The accuracy paradox
When one class is rare, accuracy rewards ignoring it. On a test set with 1 % fraud, the "model" that never predicts fraud is 99 % accurate and completely useless:
import numpy as np
from sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score, balanced_accuracy_score
rng = np.random.default_rng(0)
y = (rng.random(5000) < 0.01).astype(int) # about 1 % positives
never = np.zeros_like(y) # always "not fraud"
# a real but imperfect detector: finds 70 % of fraud, flags 2 % of normal cases
model = np.where(y == 1, rng.random(5000) < 0.70, rng.random(5000) < 0.02).astype(int)
print("positives in the test set:", int(y.sum()), "of", len(y))
for name, p in [("always negative", never), ("detector", model)]:
print(f"{name:16s} accuracy {accuracy_score(y, p):.3f} balanced acc {balanced_accuracy_score(y, p):.3f}"
f" precision {precision_score(y, p, zero_division=0):.3f} recall {recall_score(y, p):.3f}"
f" F1 {f1_score(y, p):.3f}")positives in the test set: 51 of 5000
always negative accuracy 0.990 balanced acc 0.500 precision 0.000 recall 0.000 F1 0.000
detector accuracy 0.976 balanced acc 0.823 precision 0.252 recall 0.667 F1 0.366
The test set has 51 frauds among 5000 cases. Never flagging anything scores 0.990 accuracy, higher than the real detector's 0.976, which catches two thirds of the frauds (recall 0.667). Recall, and balanced accuracy (the mean of the recall of each class, 0.5 for any constant prediction) all rank the two correctly. The detector's precision of 0.252 is also worth noticing: with positives this rare, even a 2 % false-alarm rate on 4949 normal cases produces about three false alarms per real fraud.
More than two classes
With classes the confusion matrix is , and precision, recall and are computed per class (that class against all the others). Three ways to combine them:
- macro: the plain mean over classes; every class counts the same, so rare classes matter;
- weighted: the mean weighted by each class's number of true examples (its support), so large classes dominate (weighted recall is exactly the accuracy);
- micro: pool the TP, FP and FN of all classes, then compute the metric once. For single-label multiclass problems micro precision = micro recall = micro = accuracy.
import numpy as np
from sklearn.metrics import confusion_matrix, precision_recall_fscore_support, f1_score
classes = ["cat", "dog", "bird"]
y_true = np.array([0] * 10 + [1] * 6 + [2] * 4) # 10 cats, 6 dogs, 4 birds
y_pred = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, # cats: 8 right, 2 called dog
1, 1, 1, 1, 0, 2, # dogs: 4 right
2, 0, 0, 1]) # birds: only 1 right
cm = confusion_matrix(y_true, y_pred)
print("confusion matrix (rows = true cat, dog, bird):")
print(cm)
tp = np.diag(cm)
prec = tp / cm.sum(axis=0) # column sums = predicted counts
rec = tp / cm.sum(axis=1) # row sums = true counts (support)
f1 = 2 * prec * rec / (prec + rec)
support = cm.sum(axis=1)
for c, p, r, f, s in zip(classes, prec, rec, f1, support):
print(f"{c:5s} precision {p:.3f} recall {r:.3f} F1 {f:.3f} support {s}")
print(f"macro F1 ours {f1.mean():.3f} sklearn {f1_score(y_true, y_pred, average='macro'):.3f}")
print(f"weighted F1 ours {np.sum(f1 * support) / support.sum():.3f} sklearn {f1_score(y_true, y_pred, average='weighted'):.3f}")
print(f"micro F1 ours {tp.sum() / cm.sum():.3f} sklearn {f1_score(y_true, y_pred, average='micro'):.3f}")confusion matrix (rows = true cat, dog, bird):
[[8 2 0]
[1 4 1]
[2 1 1]]
cat precision 0.727 recall 0.800 F1 0.762 support 10
dog precision 0.571 recall 0.667 F1 0.615 support 6
bird precision 0.500 recall 0.250 F1 0.333 support 4
macro F1 ours 0.570 sklearn 0.570
weighted F1 ours 0.632 sklearn 0.632
micro F1 ours 0.650 sklearn 0.650
Read the matrix row by row: 8 of 10 cats are right (recall 0.8), but only 1 of 4 birds (recall 0.25). The macro of 0.570 is pulled down by the bird class; the weighted (0.632) mostly reflects cats; micro is exactly the accuracy, 13 correct out of 20 = 0.65. If the rare class matters, report macro averages and the per-class table, not just the micro or weighted number.
Pitfalls
- Reporting accuracy on imbalanced data. Always show the confusion matrix, and recall and precision of the rare class; see Class Imbalance.
- Forgetting the threshold. Precision and recall belong to one threshold on the model's scores. Move it and they trade off (Log Loss and Choosing a Threshold).
- Precision of a model that predicts no positives is . scikit-learn warns and returns 0; pass
zero_divisionto make the choice explicit. - Macro averages on tiny classes are noisy: a class with 4 examples moves the macro a lot with one prediction. Report the support next to it.
Practice
- A screening test has TP = 45, FN = 5, FP = 150, TN = 800. Compute recall, precision, specificity and accuracy.
Answer
Recall , precision , specificity , accuracy . It finds 90 % of the cases, but fewer than one in four positive results is real: typical for screening, where a second test confirms.
- Show that .
Answer
With and : . TN does not appear: ignores correct rejections, which is why it suits rare positives.
Test yourself
In scikit-learn's confusion_matrix(y_true, y_pred) for labels 0 and 1, what is the entry in row 1, column 0?
- true positives
- false positives
- false negatives
- true negatives
A cancer screening model must miss as few cancers as possible. Which metric should be high?
- precision
- recall
- specificity
- accuracy
On a data set with 1 % positives, a model that always predicts negative has which accuracy and recall?
- 0.99 and 0
- 0.5 and 0.5
- 0.01 and 1
- 0.99 and 0.99
For a single-label multiclass problem, micro-averaged equals…
- macro
- accuracy
- weighted recall of the largest class
- the mean of precision and recall