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 positive | Called negative | |
|---|---|---|
| Really positive | hit TP | miss FN |
| Really negative | false 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.
- precision
- The share of positive predictions that are real positives. It is undefined when TP + FP = 0.
- recall
- The share of real positives that the model predicts positive. In medical statistics it is called sensitivity.
- F1 score
- The harmonic mean of precision and recall. Written with TP, FP and FN, it takes the form on the right.
- 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 and are the precision and recall when the k highest scores are predicted positive (with ), then the formula is below. Some definitions smooth the curve by interpolation, so the value can differ a little.
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.
| Box | Plain words | Model said | Real answer |
|---|---|---|---|
| TP | hit | positive | positive |
| FP | false alarm | positive | negative |
| FN | miss | negative | positive |
| TN | correct rejection | negative | negative |
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.
- Accuracy
(TP + TN) ÷ all: the share of right answers. - Precision
TP ÷ (TP + FP): of what the model called positive, the share that was right. "Can I trust the alarm?" - Recall
TP ÷ (TP + FN): of the real positives, the share it found. "Did it miss any?" - F1
2TP ÷ (2TP + FP + FN): precision and recall rolled into one number (section 3).
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.
- 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, soR = 1 ÷ (1 + 9) = 0.1. - 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. - 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. - 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.
- 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.
- FP. Real negatives among those 12: 0.51, 0.52, 0.55, 0.71. That is 4.
- FN. Real positives below 0.5: 0.3, 0.47. That is 2. TN is the remaining real negatives,
20 − 4 = 16. - Scores. Accuracy
(8 + 16) ÷ 30 = 0.8. Precision8 ÷ (8 + 4) = 8 ÷ 12 ≈ 0.67. Recall8 ÷ (8 + 2) = 0.8. F12·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ₖ
k: the step number, when the top k points by score are called positive.Pₖ: precision at step k.Rₖ: recall at step k. It starts atR₀ = 0.Rₖ − Rₖ₋₁: the recall that step added. It is1 ÷ number of real positives(0.1 here) on steps where a real positive came in, and 0 on the other steps.Σ: add over every step.
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
| Property | Plain words | In the experiment |
|---|---|---|
| Accuracy is fooled by imbalance | With many negatives, saying "negative" every time already scores high | Threshold 1: accuracy 0.67, recall 0 |
| Raising the threshold never raises recall | Fewer points are called positive, so the number found cannot grow | Drag from 0 to 1: 1 → 0 |
| Precision usually rises, but not always | When the line passes a real positive, only TP drops | 0.63 → 0.64: 0.89 → 0.88 |
| F1 is pulled toward the smaller value | The harmonic mean is never more than twice the smaller value | P 1, R 0.1 → F1 0.18 |
| F1 ignores TN | The formula 2TP ÷ (2TP + FP + FN) has no TN | The F1 cell's formula has no TN count |
| Precision is undefined when nothing is called positive | 0 ÷ 0. scikit-learn returns 0 by default and raises a warning | Threshold 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.
| Class | TP | FP | FN | Precision | Recall | F1 |
|---|---|---|---|---|---|---|
| cat | 8 | 1 | 2 | 0.89 | 0.8 | 0.84 |
| dog | 5 | 5 | 0 | 0.5 | 1 | 0.67 |
| bird | 1 | 0 | 4 | 1 | 0.2 | 0.33 |
| macro: average of the class F1s | 0.61 | |||||
| micro: add up the counts first | 14 | 6 | 6 | 0.7 | 0.7 | 0.7 |
- Macro computes the score for each class and takes a plain average. Every class has the same weight, so the bird's 0.33 makes up a third and pulls the result down to 0.61. A weak rare class shows up. In scikit-learn, macro F1 is the average of the class F1s. It is not the harmonic mean of macro precision (0.8) and macro recall (0.67), which would be 0.73.
- Micro adds up TP, FP and FN over all classes and computes once. Every example has the same weight, so common classes decide the number. When each example has exactly one answer, every mistake is an FP for one class and an FN for another, so total FP equals total FN. Then precision, recall and F1 all equal accuracy (
14 ÷ 20 = 0.7).
9. Which one to use
First decide which mistake costs more: a false alarm (FP) or a miss (FN).
| Option | Good | Bad | Use when |
|---|---|---|---|
| Accuracy | One easy number. Uses all four boxes | Fooled by imbalance. Treats both mistakes as equal | Positives and negatives are about equally common and both mistakes cost about the same |
| Precision | Tells you whether a "positive" answer can be trusted | Ignores misses. Easy to push up by calling only the surest cases positive | False alarms are expensive: spam filtering (real mail in the spam folder hurts), alerts sent to people that must stay rare |
| Recall | Tells you how much of what you needed to find was found | Ignores false alarms. Calling everything positive gives 1 | Misses are expensive: first-round disease screening, flagging suspicious payments for a person to review |
| F1 | One number for both. Stays low if only one is good | Ignores TN. Weighs both mistakes the same | Positives are rare and both mistakes cost about the same, or you compare several models with one number |
| F-beta | Lets one mistake weigh more | You need a separate reason for the value of β | One mistake costs more but you still need a single number |
| Macro average | Same weight for every class. A failing rare class shows up | Swings a lot with one small class | Rare classes matter as much as common ones |
| Micro average | Same weight for every example. Steadier | Common classes decide the number. Equals accuracy when each example has one answer | What matters is how many examples were right overall |
| ROC curve and AUC | Looks at every threshold, not just one | Does not pick a threshold for you | Comparing models before you choose a threshold (see ROC curve) |
Where it is used
- Report cards for classifiers. Models that answer yes or no, such as spam, fraud, defect or disease checks, are judged with the confusion matrix and these scores. Putting a threshold on the score from logistic regression or a neural network is exactly experiment ①.
- Picking a threshold. After training, move the threshold across the validation data and pick it by a rule such as "the highest precision that still keeps the recall we need".
- Search and recommendations. Of the items shown, the share that was relevant is precision. Of the relevant items, the share that was shown is recall.
- Separate from the training loss. Training usually lowers a loss such as cross-entropy, and these scores are measured after training. Measure them on test data to get close to real performance (see overfitting).
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 here | Textbook term |
|---|---|
| table of four boxes | confusion matrix |
| hit | true positive (TP) |
| false alarm | false positive (FP), type I error |
| miss | false negative (FN), type II error |
| correct rejection | true negative (TN) |
| share of right answers | accuracy |
| of what was called positive, the share that was right | precision, positive predictive value |
| of the real positives, the share that was found | recall, sensitivity, true positive rate |
| harmonic mean of precision and recall | F1 score, F-measure |
| F with more weight on one side | F-beta score |
| flip, average, flip back | harmonic mean. The plain average is the arithmetic mean |
| threshold | classification threshold, decision threshold |
| data where one answer is far more common | class imbalance |
| score each class, then average | macro average |
| add up all counts, then score once | micro average |
| curve of (recall, precision) as the threshold goes down | PR curve, precision-recall curve |
| each rise in recall × the precision there, added up | average precision (AP) |
Sources
- Google, Machine Learning Crash Course: Accuracy, recall, precision, and related metrics. Avoid accuracy on imbalanced data, how precision and recall trade off as the threshold moves, 0 ÷ 0 (NaN), and choosing a metric by which mistake costs more.
- scikit-learn documentation, Model evaluation: Precision, recall and F-measures. F as the harmonic mean of precision and recall, F-beta, when the micro average equals accuracy, and macro F as the plain average of the class F scores.
- scikit-learn documentation, sklearn.metrics.f1_score. F1 = 2TP ÷ (2TP + FP + FN), what micro and macro mean for the average parameter, and the zero_division default (acts like 0 and warns).
← Registration: from rigid to non-rigidData splits and leakage →