Confusion matrix, precision, recall and F1

Of everything the model called "positive", how many were right? Of all the real positives, how many did it find? These are two different questions, and when you move the threshold, one goes up while the other goes down. Drag the line across 30 points and watch the four boxes and the scores change.

Short answer. Count a classifier's answers in four boxes: hit (TP), false alarm (FP), miss (FN), and correct rejection (TN). Precision TP ÷ (TP + FP) is "of what it called positive, the share that was right". Recall TP ÷ (TP + FN) is "of the real positives, the share it found". F1 is their harmonic mean 2PR ÷ (P + R), so it stays low if only one of them is good. When negatives far outnumber positives, the share of right answers (accuracy) can fool you.

Called positiveCalled negative
Really positivehit TP miss FN
Really negativefalse alarm FP correct rejection TN
Accuracy
Precision
Recall
F1

Drag across the picture or edit the number (0 to 1, arrow keys move it by 0.01). A point is called positive when its score is at or above the threshold. The green circles on top are real positives, the blue squares below are real negatives. The 30 points come from a random number generator with a fixed seed, so they are the same every time you open the page. This is a small made-up example: only the scores are invented, with no real model. A real model would produce one such score for each example.

Definitions

The text below explains these with scores and a threshold. These are the textbook definitions. In binary classification, one class is called positive and the other negative, and each prediction is counted against the true label.

confusion matrix
A table that counts the model's predictions against the true labels. For binary classification it is a 2 × 2 table with four cells: true positive TP (a real positive predicted positive), false positive FP (a real negative predicted positive), false negative FN (a real positive predicted negative) and true negative TN (a real negative predicted negative).
accuracy
The share of all samples that the model predicts correctly.

accuracy=TP+TNTP+FP+FN+TN

precision
The share of positive predictions that are real positives. It is undefined when TP + FP = 0.

P=TPTP+FP

recall
The share of real positives that the model predicts positive. In medical statistics it is called sensitivity.

R=TPTP+FN

F1 score
The harmonic mean of precision and recall. Written with TP, FP and FN, it takes the form on the right.

F1=2PRP+R=2TP2TP+FP+FN

precision-recall curve, average precision
The precision-recall (PR) curve joins the (recall, precision) points you get as you move the threshold. Average precision AP turns the area under it into one number by adding one bar per step. If Pk and Rk are the precision and recall when the k highest scores are predicted positive (with R0=0), then the formula is below. Some definitions smooth the curve by interpolation, so the value can differ a little.

AP=∑k(Rk−Rk−1)Pk

1. Four boxes and three scores

A classifier gives each example a score for "how positive it looks". If the score is at or above the threshold, it says "positive", otherwise "negative". For a spam filter, spam is positive and normal mail is negative. Pair what the model said with the real answer and there are only four cases.

BoxPlain wordsModel saidReal answer
TPhitpositivepositive
FPfalse alarmpositivenegative
FNmissnegativepositive
TNcorrect rejectionnegativenegative

Lay these four out in a 2 × 2 table and you have the confusion matrix. The first letter (T or F) says whether the model was right. The second letter (P or N) says what the model said. Every score below comes from these four counts.

Precision and recall share the same top (TP) and differ only in the bottom. Precision divides by a column of the confusion matrix (what was called positive). Recall divides by a row (what is really positive).

2. When accuracy fools you

Say 10 out of 1,000 card payments are fraud. A model that looks at nothing and says "all fine" gets 990 right, so its accuracy is 0.99. Yet it caught no fraud at all. Its recall is 0 ÷ (0 + 10) = 0.

When negatives far outnumber positives (class imbalance), the TN box fills up the accuracy. The experiment above has 20 real negatives and 10 positives. Set the threshold to 1 so nothing is called positive, and accuracy is still 0.67. Set it to 0.95 so only 1 of the 10 positives is found, and accuracy is 0.7. So the rarer the positives, the more you should look at precision and recall instead of accuracy.

3. How the formula is built: why F1 is a harmonic mean

You often want one number for precision and recall, for example to compare several models or to pick a threshold. See what happens with a plain average by stepping through below. Across is precision P, up is recall R, and each point is one model.

The formula grows one piece at a time. A light orange background marks the newest piece, solid orange marks the wrong path. The model in the picture is experiment ① with the same 30 points and the threshold at 0.95.

  1. Precision and recall. At threshold 0.95 the model calls 1 point positive, and it is right. P = 1 ÷ (1 + 0) = 1. It found only 1 of the 10 real positives, so R = 1 ÷ (1 + 9) = 0.1.
  2. Plain average (P + R) ÷ 2. (1 + 0.1) ÷ 2 = 0.55. A model that missed 9 of 10 now looks "half good". It ties with a model whose precision and recall are both 0.55. In the picture, models with the same plain average sit on a straight line, so giving up one side completely still keeps the score as long as the other side is high.
  3. Harmonic mean 2 ÷ (1/P + 1/R). Flip each value, average, and flip back. 1/1 = 1, 1/0.1 = 10, average 5.5, 1 ÷ 5.5 ≈ 0.18. A small value becomes large when flipped and drags the average, so the result stays near the smaller value. The harmonic mean is never more than twice the smaller value.
  4. Done: F1 = 2PR ÷ (P + R) = 2TP ÷ (2TP + FP + FN). Put the counts in for P and R and simplify: hits count twice and each kind of mistake counts once. For this model, 2 ÷ (2 + 0 + 9) = 0.18. This form still gives a value when precision is 0 ÷ 0 and undefined.

To weigh the two mistakes differently, use F-beta (1 + β²)·P·R ÷ (β²·P + R). With β = 1 it is F1. With β above 1 recall counts more, below 1 precision counts more.

4. Work it out by hand: threshold 0.5

This is where experiment ① starts. Twelve points have a score of 0.5 or more.

  1. TP. Real positives among those 12: 0.63, 0.7, 0.74, 0.76, 0.78, 0.86, 0.88, 0.95. That is 8.
  2. FP. Real negatives among those 12: 0.51, 0.52, 0.55, 0.71. That is 4.
  3. FN. Real positives below 0.5: 0.3, 0.47. That is 2. TN is the remaining real negatives, 20 − 4 = 16.
  4. Scores. Accuracy (8 + 16) ÷ 30 = 0.8. Precision 8 ÷ (8 + 4) = 8 ÷ 12 ≈ 0.67. Recall 8 ÷ (8 + 2) = 0.8. F1 2·8 ÷ (2·8 + 4 + 2) = 16 ÷ 22 ≈ 0.73. That is almost the plain average of 0.67 and 0.8, which is also 0.73. When the two values are close, both averages are close. The further apart they are, the more the harmonic mean is pulled toward the smaller one.

5. Moving the threshold trades one for the other

Raise the threshold and fewer points are called positive. False alarms (FP) drop, so precision usually rises, and misses (FN) grow, so recall falls. Lower it and the opposite happens. The threshold is a knob you turn without retraining the model, so you set it based on which mistake you can live with.

When you raise the threshold, recall always stays the same or falls. Its bottom (the number of real positives) is fixed, and TP can only shrink. Precision is different. When the line passes a real positive, only TP drops by one, so precision can fall. The PR curve in section 6 puts how the two move across every threshold into one picture.

Try this. ① The starting threshold 0.5 gives TP 8, FP 4, FN 2, TN 16, with accuracy 0.8, precision 0.67, recall 0.8 and F1 0.73. ② Raise it to 0.56 to 0.63 and FP drops to 1: precision 0.89, recall still 0.8, F1 0.84. That is the highest F1 for this data. ③ Raise it just one more step to 0.64 and the real positive at 0.63 drops out: TP 7, and precision falls to 0.88. ④ At 0.72 to 0.74 there are no false alarms, so precision is 1 and recall is 0.6. Lower it to 0.3 and recall is 1 while precision is 0.43. ⑤ At 1 nothing is called positive. Precision is 0 ÷ 0 and undefined, recall is 0, F1 is 0, and accuracy is still 0.67. At 0 everything is called positive: recall 1, precision 0.33, F1 0.5.

6. PR curve and average precision (AP)

Start with the threshold above the top score and lower it one point at a time. Each step gives one (recall, precision) pair. Joining these points gives the PR curve (precision-recall curve), with recall across and precision up. Draw it step by step with the same 30 points as experiment ①.

In the top strip the orange vertical line is the threshold. The orange background to its right is what is called positive, and the orange ring is the point that just came in. In the plot below, a green arrow is a step where a real positive (●) came in, and a blue arrow is a step where a real negative (■) came in. Next to the arrow you see how precision and recall changed.

Why it zigzags. When a real positive comes in, TP and the number called positive both grow by 1. Recall rises by 0.1, and precision rises or stays at 1. The curve moves right (and up). When a real negative comes in, only the number called positive grows. Recall stays the same and only precision falls. The curve drops straight down. The two take turns, so the curve zigzags.

Average precision (AP) turns the area under the curve into one number. This page counts it like this.

AP = Σ (Rₖ − Rₖ₋₁) × Pₖ

The bars shaded on the last step of the experiment are this sum. There are 10 bars of width 0.1 and height Pₖ, so 0.1 × (1 + 1 + 1 + 1 + 1 + 1 + 0.88 + 0.89 + 0.6 + 0.43) ≈ 0.88. The highest F1 on the curve is at step 9 (threshold 0.63, precision 0.89, recall 0.8, F1 0.84), the same place as ② in section 5's "Try this". F1 is measured at one threshold, and AP sweeps every threshold.

The AP on the object detection page (multiply each rise in recall by the precision at that point and add) and on the retrieval metrics page (add the precision at each rank where a right answer appears, then divide by the number of right answers) is the same calculation. Some benchmarks smooth out the zigzag (interpolation), so the same result can give a slightly different number.

Compared with the ROC curve. The ROC curve also sweeps every threshold, but it puts the false positive rate (false alarms ÷ all real negatives) across and recall up. As the class imbalance page puts it, the false positive rate divides by the whole common class, so many false alarms can still look small, while precision shows directly how many of the alarms are false. So when the imbalance is severe, the PR curve tells you more than the ROC curve.

7. Properties to know

PropertyPlain wordsIn the experiment
Accuracy is fooled by imbalanceWith many negatives, saying "negative" every time already scores highThreshold 1: accuracy 0.67, recall 0
Raising the threshold never raises recallFewer points are called positive, so the number found cannot growDrag from 0 to 1: 1 → 0
Precision usually rises, but not alwaysWhen the line passes a real positive, only TP drops0.63 → 0.64: 0.89 → 0.88
F1 is pulled toward the smaller valueThe harmonic mean is never more than twice the smaller valueP 1, R 0.1 → F1 0.18
F1 ignores TNThe formula 2TP ÷ (2TP + FP + FN) has no TNThe F1 cell's formula has no TN count
Precision is undefined when nothing is called positive0 ÷ 0. scikit-learn returns 0 by default and raises a warningThreshold 1

8. Three or more classes: macro and micro

Say a model sorts 20 pictures (10 cats, 5 dogs, 5 birds). Of the 10 cats it called 8 cats and 2 dogs. It called all 5 dogs dogs. Of the 5 birds it called only 1 a bird, 3 dogs and 1 a cat. For each class, treat "this class is positive, everything else is negative" and count the four boxes.

These are the counts from the sentence above in a 3 × 3 table. Rows are the true class and columns are the class the model said. Colored boxes get a label: TP (green, the diagonal), FN (orange, the rest of its row), FP (blue, the rest of its column). Each step fills in that class's row of the table below.

ClassTPFPFNPrecisionRecallF1
cat8120.890.80.84
dog5500.510.67
bird10410.20.33
macro: average of the class F1s0.61
micro: add up the counts first14660.70.70.7

9. Which one to use

First decide which mistake costs more: a false alarm (FP) or a miss (FN).

OptionGoodBadUse when
AccuracyOne easy number. Uses all four boxesFooled by imbalance. Treats both mistakes as equalPositives and negatives are about equally common and both mistakes cost about the same
PrecisionTells you whether a "positive" answer can be trustedIgnores misses. Easy to push up by calling only the surest cases positiveFalse alarms are expensive: spam filtering (real mail in the spam folder hurts), alerts sent to people that must stay rare
RecallTells you how much of what you needed to find was foundIgnores false alarms. Calling everything positive gives 1Misses are expensive: first-round disease screening, flagging suspicious payments for a person to review
F1One number for both. Stays low if only one is goodIgnores TN. Weighs both mistakes the samePositives are rare and both mistakes cost about the same, or you compare several models with one number
F-betaLets one mistake weigh moreYou need a separate reason for the value of βOne mistake costs more but you still need a single number
Macro averageSame weight for every class. A failing rare class shows upSwings a lot with one small classRare classes matter as much as common ones
Micro averageSame weight for every example. SteadierCommon classes decide the number. Equals accuracy when each example has one answerWhat matters is how many examples were right overall
ROC curve and AUCLooks at every threshold, not just oneDoes not pick a threshold for youComparing models before you choose a threshold (see ROC curve)

Where it is used

FAQ

Which matters more, precision or recall?

It depends on which mistake costs more. If missing a positive (FN) is expensive, watch recall. If a false alarm (FP) is expensive, watch precision. If both cost about the same, watch F1. Either way, do not look at one number alone. Check how far the other one dropped.

Is the threshold always 0.5?

No. 0.5 is only a common starting point. The threshold is a knob that you set, not the model. Move it across the validation data, pick the spot that gives the precision and recall you need, and check it once more on the test data.

Does a high F1 mean a good model?

F1 ignores two things. First, the formula 2TP ÷ (2TP + FP + FN) has no TN (correctly rejected negatives). Second, it counts false alarms and misses with the same weight. If one mistake costs more, watch that metric or use F-beta. Also, F1 is measured at one threshold. To see all thresholds at once, look at the ROC curve.

Words

Plain words used hereTextbook term
table of four boxesconfusion matrix
hittrue positive (TP)
false alarmfalse positive (FP), type I error
missfalse negative (FN), type II error
correct rejectiontrue negative (TN)
share of right answersaccuracy
of what was called positive, the share that was rightprecision, positive predictive value
of the real positives, the share that was foundrecall, sensitivity, true positive rate
harmonic mean of precision and recallF1 score, F-measure
F with more weight on one sideF-beta score
flip, average, flip backharmonic mean. The plain average is the arithmetic mean
thresholdclassification threshold, decision threshold
data where one answer is far more commonclass imbalance
score each class, then averagemacro average
add up all counts, then score oncemicro average
curve of (recall, precision) as the threshold goes downPR curve, precision-recall curve
each rise in recall × the precision there, added upaverage precision (AP)

Sources

← Registration: from rigid to non-rigidData splits and leakage →