Search

Search papers and lessons

Confusion Matrix

Level 2 · 9 min read

A confusion matrix is a small table that counts every answer a yes-or-no classifier gave, split by what it said and what was actually true.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Probability
  • Learning basics
  • Losses & regularization
  • Sign in to see your progress

TL;DR

A classifier that answers yes or no has four kinds of answer. It can be right about a yes, right about a no, wrong by saying yes when the truth is no, or wrong by saying no when the truth is yes. A confusion matrix is a two-by-two table that counts how many answers fall into each of the four boxes. Every score you compute for the classifier comes from those four counts.

Where you'll see it: reporting how well a spam filter, a fraud alert or a medical screening test performs, and comparing two models on the same test set.

Intuition

Suppose you built a filter that reads an email and says "spam" or "not spam". To judge it, you take emails whose labels you already know, run the filter on them, and compare each answer with the truth. The question is: how do you summarise a long list of right and wrong answers in a form you can read at a glance?

Start with ten emails. Four are spam and six are not. The filter says "spam" to five of them. Three of those five really are spam, and two are ordinary mail it wrongly flagged. Of the five it let through, one is spam it missed, and four are ordinary mail it correctly passed. Sort the ten answers into boxes:

  • said spam, really spam: 3
  • said spam, really not spam: 2
  • said not spam, really spam: 1
  • said not spam, really not spam: 4

Those four numbers are the whole confusion matrix. The name comes from the fact that the table shows where the classifier gets confused: which true class it mixes up with which.

Why not just report the fraction correct? Because the two kinds of mistake usually have different costs. A spam filter that sends a real invoice to the junk folder hurts more than one that lets a single spam message through. Two classifiers can have the same number of total mistakes but make them in different boxes, and only the table shows that.

flowchart TD
  A["Each test case has a true label and a predicted label"] --> B{"Predicted yes?"}
  B -->|yes| C{"Truly yes?"}
  B -->|no| D{"Truly yes?"}
  C -->|yes| E["True positive"]
  C -->|no| F["False positive"]
  D -->|yes| G["False negative"]
  D -->|no| H["True negative"]

The math

Setting up the table

Call the two classes positive and negative. "Positive" is the class you are looking for, such as spam or fraud. It is a naming convention, not a judgement that positive is good. Let the test set contain nn cases. Each case has a true label y∈{pos,neg}y \in \{\text{pos}, \text{neg}\} and a predicted label y^\hat{y}. Count the cases in each box:

Definition: Confusion matrix

For a binary classifier, the confusion matrix is the 2×22 \times 2 table of counts

TP=#{truly positive, predicted positive}FN=#{truly positive, predicted negative}FP=#{truly negative, predicted positive}TN=#{truly negative, predicted negative}\begin{aligned} TP &= \#\{\text{truly positive, predicted positive}\} \\ FN &= \#\{\text{truly positive, predicted negative}\} \\ FP &= \#\{\text{truly negative, predicted positive}\} \\ TN &= \#\{\text{truly negative, predicted negative}\} \end{aligned}

where #{⋅}\#\{\cdot\} means "the number of cases that satisfy this condition". The four counts add up to nn.

The letters are read as follows. The first letter says whether the prediction was right (true) or wrong (false). The second letter says what the classifier predicted (positive or negative). So a false positive is a wrong answer of "positive". Many libraries print the table with rows for the true class and columns for the predicted class:

Predicted positivePredicted negative
Truly positiveTPTPFNFN
Truly negativeFPFPTNTN

The row totals are the number of truly positive cases, TP+FNTP + FN, and the number of truly negative cases, FP+TNFP + TN. The column totals are the number of positive predictions, TP+FPTP + FP, and the number of negative predictions, FN+TNFN + TN. Check the table by confirming that these totals agree with the number of cases you know to be in each class.

Accuracy, the number everyone asks for first

The simplest summary is the fraction of answers that were correct:

accuracy=TP+TNTP+TN+FP+FN=TP+TNn.\text{accuracy} = \frac{TP + TN}{TP + TN + FP + FN} = \frac{TP + TN}{n}.

Accuracy uses the two correct boxes only. It treats both kinds of mistake the same and ignores which class the mistakes fall into. This is the trap taken up in the worked examples below.

Error rates from the rows

Dividing each row by its total gives two rates that describe the classifier's behaviour on each true class:

false negative rate=FNTP+FN,false positive rate=FPFP+TN.\text{false negative rate} = \frac{FN}{TP + FN}, \qquad \text{false positive rate} = \frac{FP}{FP + TN}.

The false negative rate is the fraction of real positives the classifier missed. The false positive rate is the fraction of real negatives it wrongly flagged. Their complements, TP/(TP+FN)TP / (TP + FN) and TN/(FP+TN)TN / (FP + TN), are called the true positive rate and the true negative rate. In some fields the true positive rate is called sensitivity and the true negative rate is called specificity. The type I error and type II error rates from statistics are the same quantities under different names: a false positive is a type I error and a false negative is a type II error.

Summaries from the columns

Dividing each column by its total asks a different question: when the classifier says yes, how often is it right? The answer is called precision, and it is one of the scores the matrix is used to compute. The other scores, such as recall and the F1 score, are covered in the lesson on Precision and Recall.

Worked examples

Example
1. A tiny table you can check by hand

Use the ten-email filter from the intuition section. Here TP=3TP = 3, FP=2FP = 2, FN=1FN = 1, TN=4TN = 4.

  1. Check the total: 3+2+1+4=103 + 2 + 1 + 4 = 10. This equals nn, so no case is missing.
  2. Accuracy: the correct answers are TP+TN=3+4=7TP + TN = 3 + 4 = 7, so accuracy is 7/10=0.77 / 10 = 0.7.
  3. False negative rate: the spam emails are TP+FN=3+1=4TP + FN = 3 + 1 = 4, and one was missed, so the rate is 1/4=0.251 / 4 = 0.25.
  4. False positive rate: the ordinary emails are FP+TN=2+4=6FP + TN = 2 + 4 = 6, and two were flagged, so the rate is 2/6≈0.332 / 6 \approx 0.33.

Interpretation: the filter is right seven times out of ten. It misses a quarter of the spam, and it wrongly flags a third of the legitimate mail. The second number is the one a user would notice first.

Example
2. A textbook test set with two classes of similar size

A classifier is tested on 200 cases (positive means the case belongs to the class being looked for). 80 are truly positive and 120 are truly negative. It gives this confusion matrix:

Predicted positivePredicted negativeRow total
Truly positive70 (TPTP)10 (FNFN)80
Truly negative15 (FPFP)105 (TNTN)120
Column total85115200
  1. Check the rows: 70+10=8070 + 10 = 80 and 15+105=12015 + 105 = 120. Both match the known class sizes.
  2. Check the total: 80+120=20080 + 120 = 200.
  3. Accuracy: (70+105)/200=175/200=0.875(70 + 105) / 200 = 175 / 200 = 0.875, or 87.5 percent.
  4. False negative rate: 10/80=0.12510 / 80 = 0.125. The classifier misses one positive in eight.
  5. False positive rate: 15/120=0.12515 / 120 = 0.125. It also wrongly flags one negative in eight.

Interpretation: both error rates happen to be equal here, so the classifier treats the two classes alike. That symmetry is unusual. The matrix shows it at a glance, and accuracy alone would not reveal that the two kinds of error are equal in size.

Example
3. Fraud detection with a rare positive class

A bank checks 10,000 card transactions. 50 are fraud, which is 0.5 percent of the total. The fraud model flags 90 transactions as fraud. Of the flagged ones, 40 are real fraud. The other 10 frauds go unflagged.

  1. Fill in the table. Truly fraudulent: TP+FN=50TP + FN = 50, with TP=40TP = 40 and so FN=10FN = 10. Truly legitimate: 9,9509{,}950, of which FP=90−40=50FP = 90 - 40 = 50 were flagged and so TN=9,950−50=9,900TN = 9{,}950 - 50 = 9{,}900.
  2. Check the total: 40+10+50+9,900=10,00040 + 10 + 50 + 9{,}900 = 10{,}000.
  3. Accuracy of the model: (40+9,900)/10,000=0.994(40 + 9{,}900) / 10{,}000 = 0.994, or 99.4 percent.
  4. Accuracy of a useless rule that never flags anything: it answers "legitimate" every time, so it is right on all 9,9509{,}950 legitimate transactions and wrong on the 50 frauds. Its accuracy is 9,950/10,000=0.9959{,}950 / 10{,}000 = 0.995, or 99.5 percent.
  5. Recall, the share of real fraud the model caught: 40/50=0.840 / 50 = 0.8.
  6. Precision, the share of flags that were real fraud: 40/90≈0.4440 / 90 \approx 0.44.

Interpretation: the useless rule scores higher on accuracy than the real model. Accuracy rewards the large legitimate class and hides the fact that the model catches 80 percent of fraud. The matrix shows the trade-off clearly. About 56 percent of its alarms are false, which may or may not be acceptable depending on the cost of reviewing each one.

Tradeoffs and failure modes

The table is always the right place to start, but it has limits. The table below lists the common situations.

SituationWhat goes wrongBetter choice
The positive class is rareAccuracy is dominated by the majority class and looks high for a useless modelReport the row rates and precision and recall, and compare against a trivial baseline
The two mistakes have different costsOne number cannot weight themLook at the false negative and false positive counts separately, or tune a threshold
The model outputs a score, not a yes or noThe table depends on the cut-off you chose, so the same model gives different matricesReport how the matrix changes across thresholds, or use a curve that summarises all thresholds
The table is built on the training dataIt overstates performance because the model has seen those answersBuild the matrix on held-out data, as in [[train-validation-test-split
More than two classesThe 2 by 2 layout no longer appliesUse a larger square matrix, one row and one column per class

A confusion matrix is a count. Counts from a small test set are noisy, so two matrices that differ by a few cases may not mean much. Report the test-set size next to the table.

History

The idea of sorting decisions into hits and false alarms is older than machine learning. In the 1950s, signal detection theory used the same four-way split to describe how radar operators and listeners separated real signals from noise. The name "confusion matrix" became common in machine learning later, as classifiers were scored by how they confused one class with another. The table itself is simple; its value came from using it to ask which mistakes a system makes, not only how many.

Recap

A classifier's answers fall into four boxes: true positive, false positive, false negative and true negative. The confusion matrix holds these four counts. Accuracy adds the two correct boxes and divides by the total. The row rates say how the classifier behaves on each true class, and the column ratios say how reliable its positive answers are. Precision and Recall builds directly on this table.

Check yourself

QuestionRecall the four boxes. Which box holds a case that is truly negative but was predicted positive?Show answer

The false positive box, written FPFP. The first letter says the prediction was wrong, and the second says the prediction was positive. In the spam example, these are ordinary emails the filter flagged as spam.

QuestionA table has TP = 40, FN = 10, FP = 50, TN = 9,900. What is the total number of cases, and what fraction is correct?Show answer

The total is 40+10+50+9,900=10,00040 + 10 + 50 + 9{,}900 = 10{,}000. The correct answers are TP+TN=40+9,900=9,940TP + TN = 40 + 9{,}900 = 9{,}940. So accuracy is 9,940/10,000=0.9949{,}940 / 10{,}000 = 0.994. Interpretation: 99.4 percent of answers are correct, although the model misses 10 of the 50 frauds.

QuestionWhy can a classifier with 99.5 percent accuracy be worse than one with 99.4 percent accuracy?Show answer

The 99.5 percent classifier may be the rule that never flags anything. When the positive class is rare, that rule scores high by being right on almost every legitimate case, while it misses every real positive. The 99.4 percent model catches 40 of 50 frauds. Accuracy cannot tell these apart, but the false negative count and recall can.

QuestionA model's false negative rate is 0.25 and its false positive rate is 0.10. A colleague says it is 75 percent accurate. Is that necessarily true?Show answer

No. The two error rates describe rows of the table, and accuracy also depends on how many cases are in each class. If the positive class is rare, accuracy can be far above 75 percent while the false negative rate stays at 0.25. The colleague would need the class sizes, or the counts themselves, to compute accuracy.

Sources