Sub topic 2
The Confusion Matrix: TP, FP, TN, FN
This chapter assumes you know basic Python, the idea of supervised classification with labeled data, and what a train/test split is. It also assumes you can work with ratios and percentages. Everything else is built from scratch.
A classifier's output is a list of predictions. A single number such as "80% correct" hides what kind of mistakes the model makes. The confusion matrix is the table that shows those mistakes in full. Accuracy, precision, recall, and F1 are all computed from its four counts, so it is the base for the rest of this tutorial.
Predictions versus true labels
To evaluate a classifier you need two parallel lists of the same length:
y_true: the correct label for each example, taken from the labeled test data.y_pred: the label the model predicted for the same example, in the same order.
This chapter covers binary classification, where each label is 1 (the positive class) or 0 (the negative class). Which class counts as positive is your choice. It is usually the class you are trying to find: a fraud case, a disease, a spam message.
Here are ten examples:
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]Compare them position by position. Position 0 is correct (both 1). Position 2 is wrong: the truth is 1 and the model said 0. Position 5 is wrong in the other direction: the truth is 0 and the model said 1. These two wrong cases are different kinds of error, and the confusion matrix keeps them apart.
The four outcomes
Every prediction falls into one of four cases. Two questions decide which one: what was the truth, and what did the model say?
| Row | Predicted positive (1) | Predicted negative (0) |
|---|---|---|
| **Actually positive (1)** | True positive (TP) | False negative (FN) |
| **Actually negative (0)** | False positive (FP) | True negative (TN) |
Read each name in two parts. The second word is what the model said. The first word says whether the model was right.
- True positive (TP): the model said positive, and the example is positive. A real fraud case was flagged.
- False positive (FP): the model said positive, but the example is negative. A legitimate transaction was flagged. This is a false alarm.
- True negative (TN): the model said negative, and the example is negative. A legitimate transaction passed.
- False negative (FN): the model said negative, but the example is positive. A real fraud case was missed.
Statistics textbooks sometimes call a false positive a Type I error and a false negative a Type II error. The FP/FN names are more descriptive, so this tutorial uses them.
Counting the cells in Python
Counting needs no library. Walk through the pairs and test each cell's condition:
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]
tp = sum(t == 1 and p == 1 for t, p in zip(y_true, y_pred))
fp = sum(t == 0 and p == 1 for t, p in zip(y_true, y_pred))
tn = sum(t == 0 and p == 0 for t, p in zip(y_true, y_pred))
fn = sum(t == 1 and p == 0 for t, p in zip(y_true, y_pred))
print(tp, fp, tn, fn) # 3 1 5 1zip pairs the two lists element by element. Each sum(...) adds up the True values, which Python counts as 1. Each pair satisfies exactly one of the four conditions, so each example is counted once.
Checking by hand against the lists:
- Positions 0, 3, and 9 are true
1and predicted1. That gives 3 TP. - Position 2 is true
1and predicted0. That gives 1 FN. - Position 5 is true
0and predicted1. That gives 1 FP. - Positions 1, 4, 6, 7, and 8 are true
0and predicted0. That gives 5 TN.
As a table:
| Row | Predicted 1 | Predicted 0 |
|---|---|---|
| **Actual 1** | TP = 3 | FN = 1 |
| **Actual 0** | FP = 1 | TN = 5 |
Reading the matrix: sums and invariants
Row and column totals carry meaning, and you can use them to check your counts.
- Row sums are true class sizes. TP + FN is the number of actual positives (4 here). FP + TN is the number of actual negatives (6 here).
- Column sums are prediction counts. TP + FP is how many times the model predicted positive (4 here). FN + TN is how many times it predicted negative (6 here).
- The grand total is the dataset size. TP + FP + TN + FN must equal
len(y_true). If it does not, there is a bug.
The row sums depend only on the data, never on the model. If you change the model, the actual-positive count stays the same, and only how it splits between TP and FN changes. The column sums depend on the model, and they change when you change the model or its threshold.
A short helper makes these checks routine:
def confusion_counts(y_true, y_pred):
if len(y_true) != len(y_pred):
raise ValueError("y_true and y_pred must have the same length")
pairs = list(zip(y_true, y_pred))
tp = sum(t == 1 and p == 1 for t, p in pairs)
fp = sum(t == 0 and p == 1 for t, p in pairs)
tn = sum(t == 0 and p == 0 for t, p in pairs)
fn = sum(t == 1 and p == 0 for t, p in pairs)
assert tp + fp + tn + fn == len(pairs), "labels must be 0 or 1"
return tp, fp, tn, fn
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]
tp, fp, tn, fn = confusion_counts(y_true, y_pred)
print(tp + fn) # 4 actual positives
print(fp + tn) # 6 actual negatives
print(tp + fp) # 4 predicted positivesThe assert catches labels outside {0, 1}. A label like 2 or "yes" would match none of the four conditions, and the total would fall short of the dataset size.
The same matrix in scikit-learn
scikit-learn computes the matrix with confusion_matrix. The layout is the part people get wrong:
from sklearn.metrics import confusion_matrix
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]
cm = confusion_matrix(y_true, y_pred)
print(cm)
# [[5 1]
# [1 3]]
tn, fp, fn, tp = cm.ravel()
print(tp, fp, tn, fn) # 3 1 5 1Rows are true classes and columns are predicted classes, both in sorted label order: 0 first, then 1. For binary labels 0 and 1 the layout is therefore:
| Row | Predicted 0 | Predicted 1 |
|---|---|---|
| **Actual 0** | TN | FP |
| **Actual 1** | FN | TP |
This is not the same as the table earlier in the chapter, where the positive class came first. Many textbooks draw the matrix with positives first, but scikit-learn puts the negative class first. The order from .ravel() is tn, fp, fn, tp, which is why the unpacking above uses that order. Unpacking it as tp, fp, fn, tn gives wrong numbers with no error.
Edge cases
Only one class in the data
If y_true and y_pred contain only one class, scikit-learn infers a 1×1 matrix, and .ravel() returns one number. Unpacking it into four variables then fails. Pass labels to fix the shape:
from sklearn.metrics import confusion_matrix
y_true = [0, 0, 0, 0]
y_pred = [0, 0, 0, 0]
print(confusion_matrix(y_true, y_pred))
# [[4]]
cm = confusion_matrix(y_true, y_pred, labels=[0, 1])
print(cm)
# [[4 0]
# [0 0]]
tn, fp, fn, tp = cm.ravel()
print(tp, fp, tn, fn) # 0 0 4 0This happens in practice with small test sets, or with folds that contain no positives. Always pass labels=[0, 1] when the shape must be 2×2. A matrix like this one also leads to division by zero in precision and recall, which a later chapter covers.
Choosing which class is positive
Swapping the class you call positive swaps the cells. TP trades places with TN, and FP trades places with FN. If you flip the labels in the example above, the new matrix has TP = 5, FP = 1, TN = 3, FN = 1. Nothing about the model changed. This matters because metrics such as precision and recall describe the positive class only. Define the positive class as the one whose errors you care about, and state it when you report results.
String labels
With labels like "spam" and "ham", scikit-learn sorts them alphabetically, so "ham" becomes the first row and column. The matrix would then put "ham" in the TN position and "spam" in the TP position, which happens to be correct here. With labels like "cat" and "dog" where "dog" is the target, sorting would put the target in the wrong place. Pass labels=["cat", "dog"] to set the order explicitly.
Multiclass problems
With K classes the matrix is K×K. The diagonal holds correct predictions, and each off-diagonal cell [i][j] counts examples of true class i predicted as class j. The four-name vocabulary applies per class, by treating that class as positive and all the others as negative. A later chapter covers how to average the per-class results.
What the matrix does and does not tell you
The matrix holds everything needed to compute the standard metrics. Later chapters build on it as follows:
- Accuracy is (TP + TN) divided by the total.
- Precision is TP divided by (TP + FP).
- Recall is TP divided by (TP + FN).
Two limits are worth knowing now:
- The matrix describes one set of predictions at one threshold. Models that output scores are turned into labels by a threshold. A different threshold gives a different matrix from the same model.
- The matrix is only meaningful on data the model has not trained on. Counts computed on training data are usually too good, because the model has seen those examples. Build the matrix from a held-out test set.
Common errors
- Misaligned lists.
y_trueandy_predmust be in the same example order. If you shuffle one list and not the other, the counts are meaningless and no error is raised. The length check inconfusion_countscatches only length mismatches. - Swapped arguments.
confusion_matrix(y_pred, y_true)transposes the matrix, so FP and FN trade places. The order is always(y_true, y_pred). - Mixing up the layout. The positive-first layout in diagrams differs from scikit-learn's negative-first layout. Check which convention a source uses before comparing numbers.
- Predicting scores, not labels. If
y_predcontains probabilities such as0.83, the matrix function rejects them or treats each unique value as a class. Convert scores to0or1with a threshold first. - Counting from a tiny test set. Ten examples give a matrix with a few counts in each cell. A single changed prediction moves the metrics a lot. Use enough data that each cell has meaningful counts.
Exercises
Exercise
A test set has ytrue = [1, 1, 0, 0, 0, 1, 0, 1] and ypred = [1, 0, 0, 1, 0, 1, 0, 0]. Count TP, FP, TN, and FN, and check that the four counts add up to the number of examples.
Show answer
Compare position by position. Positions 0 and 5 are true 1 and predicted 1, so TP = 2. Positions 1 and 7 are true 1 and predicted 0, so FN = 2. Position 3 is true 0 and predicted 1, so FP = 1. Positions 2, 4, and 6 are true 0 and predicted 0, so TN = 3. The total is 2 + 1 + 3 + 2 = 8, which equals the number of examples. As a check, TP + FN = 4 matches the four 1s in y_true.
Exercise
confusionmatrix(ytrue, y_pred) returns [[50, 10], [5, 35]] for labels 0 and 1. Which numbers are TN, FP, FN, and TP? How many actual positives and how many predicted positives are there?
Show answer
Rows are true classes and columns are predicted classes, with 0 first. So TN = 50, FP = 10, FN = 5, TP = 35. Actual positives are the second row: FN + TP = 5 + 35 = 40. Predicted positives are the second column: FP + TP = 10 + 35 = 45.
Exercise
A teammate unpacks scikit-learn's matrix with tp, fp, fn, tn = cm.ravel(). For the matrix [[5, 1], [1, 3]], what values do they get for each name, and which are wrong?
Show answer
ravel() returns [5, 1, 1, 3] in the order TN, FP, FN, TP. Unpacked in the wrong order, the teammate gets tp = 5, fp = 1, fn = 1, tn = 3. The correct values are TP = 3 and TN = 5, so tp and tn are swapped. fp and fn happen to be correct only because both equal 1. The right unpacking is tn, fp, fn, tp = cm.ravel().