TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Accuracy, Precision, Recall, F1 and the Confusion Matrix

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:

predicted negativepositive actual negativepositive TNcorrect "no" FPfalse alarm FNmiss TPhit

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

accuracy=TP+TNTP+TN+FP+FNprecision=TPTP+FPof the predicted positives, how many are realrecall=TPTP+FNof the real positives, how many were foundF1=2⋅precision⋅recallprecision+recall=2 TP2 TP+FP+FN\begin{aligned} \text{accuracy} &= \frac{TP + TN}{TP + TN + FP + FN} \\ \text{precision} &= \frac{TP}{TP + FP} && \text{of the predicted positives, how many are real} \\ \text{recall} &= \frac{TP}{TP + FN} && \text{of the real positives, how many were found} \\ F_1 &= \frac{2 \cdot \text{precision} \cdot \text{recall}}{\text{precision} + \text{recall}} = \frac{2\,TP}{2\,TP + FP + FN} \end{aligned}

Recall is also called sensitivity or the true positive rate; TNTN+FP\frac{TN}{TN + FP} is the specificity, and 1−specificity1 - \text{specificity} the false positive rate used by ROC curves (next lesson). F1F_1 is the harmonic mean of precision and recall, so it is high only when both are; the general Fβ=(1+β2)PRβ2P+RF_\beta = \frac{(1 + \beta^2) P R}{\beta^2 P + R} weighs recall β\beta times as much as precision (F2F_2 for screening, F0.5F_{0.5} 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
F1F_1 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:

python · try it yourself
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). F1=0.667F_1 = 0.667 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:

python · try it yourself
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, F1F_1 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 KK classes the confusion matrix is K×KK \times K, and precision, recall and F1F_1 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 F1F_1 = accuracy.
python · try it yourself
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 F1F_1 of 0.570 is pulled down by the bird class; the weighted F1F_1 (0.632) mostly reflects cats; micro F1F_1 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 0/00/0. scikit-learn warns and returns 0; pass zero_division to make the choice explicit.
  • Macro averages on tiny classes are noisy: a class with 4 examples moves the macro F1F_1 a lot with one prediction. Report the support next to it.

Practice

  1. A screening test has TP = 45, FN = 5, FP = 150, TN = 800. Compute recall, precision, specificity and accuracy.
Answer

Recall =45/50=0.90= 45/50 = 0.90, precision =45/195≈0.23= 45/195 \approx 0.23, specificity =800/950≈0.84= 800/950 \approx 0.84, accuracy =845/1000=0.845= 845/1000 = 0.845. It finds 90 % of the cases, but fewer than one in four positive results is real: typical for screening, where a second test confirms.

  1. Show that F1=2TP2TP+FP+FNF_1 = \frac{2TP}{2TP + FP + FN}.
Answer

With P=TPTP+FPP = \frac{TP}{TP + FP} and R=TPTP+FNR = \frac{TP}{TP + FN}: 2PRP+R=21/P+1/R=2TP+FPTP+TP+FNTP=2 TP2 TP+FP+FN\frac{2PR}{P + R} = \frac{2}{1/P + 1/R} = \frac{2}{\frac{TP + FP}{TP} + \frac{TP + FN}{TP}} = \frac{2\,TP}{2\,TP + FP + FN}. TN does not appear: F1F_1 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?

  1. true positives
  2. false positives
  3. false negatives
  4. true negatives

A cancer screening model must miss as few cancers as possible. Which metric should be high?

  1. precision
  2. recall
  3. specificity
  4. accuracy

On a data set with 1 % positives, a model that always predicts negative has which accuracy and recall?

  1. 0.99 and 0
  2. 0.5 and 0.5
  3. 0.01 and 1
  4. 0.99 and 0.99

For a single-label multiclass problem, micro-averaged F1F_1 equals…

  1. macro F1F_1
  2. accuracy
  3. weighted recall of the largest class
  4. the mean of precision and recall