Sub topic 3
Laying out the matrix and checking its axes
A confusion matrix is a table of counts. Before you read any number in it, you need to know which axis holds the actual labels and which holds the predicted labels. This chapter assumes you know the four outcomes (TP, FP, FN, TN) from the previous chapter, and that you can read short Python snippets. It shows how those four outcomes sit in the grid, how to confirm the orientation of any matrix you are given, and what goes wrong when you skip that check.
The standard layout
For a binary problem, the matrix has two rows and two columns. In the layout used by scikit-learn:
- Each row is an actual (true) class.
- Each column is a predicted class.
- The cell at row i, column j counts the samples whose actual class is i and whose predicted class is j.
With the classes ordered negative (0) first and positive (1) second, the four cells are:
| Row | Predicted 0 | Predicted 1 |
|---|---|---|
| **Actual 0** | TN | FP |
| **Actual 1** | FN | TP |
The diagonal, from top left to bottom right, holds the correct predictions. The off-diagonal cells hold the two kinds of error. A false positive (FP) is an actual negative predicted as positive. A false negative (FN) is an actual positive predicted as negative.
Notice that TN is at the top left and TP is at the bottom right. This surprises many people, because "positive" feels like it should come first. The position follows from the class order, not from the meaning of the words. Put 0 before 1 and the negative class takes the first row and column.
Building one and reading it
This example uses the same ten samples as the rest of the tutorial.
from sklearn.metrics import confusion_matrix
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 0]
y_pred = [1, 0, 0, 1, 0, 1, 1, 1, 0, 0]
cm = confusion_matrix(y_true, y_pred, labels=[0, 1])
print(cm)
# [[4 2]
# [1 3]]
tn, fp, fn, tp = cm.ravel()
print(tn, fp, fn, tp) # 4 2 1 3Read it row by row:
- Row 0 (actual negatives): 4 were predicted 0 (TN) and 2 were predicted 1 (FP). There are 6 actual negatives in total.
- Row 1 (actual positives): 1 was predicted 0 (FN) and 3 were predicted 1 (TP). There are 4 actual positives in total.
Two sums are worth remembering. A row sum is the number of samples that truly belong to that class, so it is the denominator of recall for that class. A column sum is the number of samples the model assigned to that class, so it is the denominator of precision for that class. Here the column for class 1 sums to 2 + 3 = 5, which is the number of positive predictions.
Why `ravel()` order matters
The call cm.ravel() flattens the matrix row by row. For a 2×2 matrix with labels=[0, 1], that gives tn, fp, fn, tp in that order. The unpacking line is correct only because of two facts: scikit-learn puts actual labels on rows, and labels=[0, 1] puts the negative class first.
If either fact changes, the same unpacking line silently assigns the wrong names. Consider reversing the label order:
from sklearn.metrics import confusion_matrix
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 0]
y_pred = [1, 0, 0, 1, 0, 1, 1, 1, 0, 0]
cm_reversed = confusion_matrix(y_true, y_pred, labels=[1, 0])
print(cm_reversed)
# [[3 1]
# [2 4]]
# Now the positive class comes first, so the flattened order is tp, fn, fp, tn.
tp, fn, fp, tn = cm_reversed.ravel()
print(tp, fn, fp, tn) # 3 1 2 4The counts are the same as before. Only their positions moved. If you had kept the line tn, fp, fn, tp = cm_reversed.ravel(), you would have called the 3 true negatives and the 4 true positives, and every metric you computed afterward would be wrong. No error is raised. The code runs and prints plausible numbers.
The safest habit is to pass labels= explicitly, as every example here does. Without it, scikit-learn uses the sorted unique labels found in y_true and y_pred. That works for 0 and 1, but for string labels such as "spam" and "ham" the sorted order puts "ham" first, and that is rarely the order you had in mind.
Checking the axes of a matrix you did not build
You will often meet matrices produced by someone else: in a paper, a dashboard, a notebook, or a library you did not write. Orientation is rarely stated in the numbers themselves. Use this procedure.
The sum check in the middle of the diagram is the most useful trick when no titles are given. If you know the dataset has 6 negatives and 4 positives, then a matrix whose row sums are 6 and 4 has actual labels on its rows. A matrix whose column sums are 6 and 4 has them on its columns. This works only when the model's predicted counts differ from the true counts. If a model predicts exactly as many samples of each class as there really are, both sums agree and the check cannot tell you anything. In that case you need the axis titles or the source code.
Transposed matrices
Transposing a matrix swaps rows and columns. Taking cm.T of the example above gives:
from sklearn.metrics import confusion_matrix
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 0]
y_pred = [1, 0, 0, 1, 0, 1, 1, 1, 0, 0]
cm = confusion_matrix(y_true, y_pred, labels=[0, 1])
print(cm.T)
# [[4 1]
# [2 3]]Reading this as if rows were still actual labels would make the 1 in the top right look like a false positive, when it is really a false negative. TP and TN stay on the diagonal under transposition, so accuracy is unchanged, but FP and FN trade places. Precision and recall would be swapped. That is a dangerous error because the two metrics answer different questions, and a transposed matrix still looks perfectly reasonable.
Printing a labeled matrix
A bare NumPy array carries no labels, which is how orientation mistakes start. A small helper that prints axis titles removes the ambiguity:
from sklearn.metrics import confusion_matrix
def show_matrix(y_true, y_pred, labels):
cm = confusion_matrix(y_true, y_pred, labels=labels)
width = max(len(str(label)) for label in labels) + 2
header = " " * (width + 8) + "".join(f"pred {label}".rjust(width + 5) for label in labels)
print(header)
for label, row in zip(labels, cm):
counts = "".join(str(n).rjust(width + 5) for n in row)
print(f"actual {str(label).ljust(width)}{counts}")
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 0]
y_pred = [1, 0, 0, 1, 0, 1, 1, 1, 0, 0]
show_matrix(y_true, y_pred, labels=[0, 1])The output has the words actual and pred next to the numbers, so a later reader cannot misread the orientation. If your plotting tool supports axis labels, set them. Plots with no axis titles are a common source of misreading.
Other tools and conventions
Not every source follows the scikit-learn layout. Some textbooks and software put predicted classes on the rows and actual classes on the columns. Some put the positive class first, so TP sits at the top left. Some tools print the matrix with its axes labeled in the opposite order from the one you expect. The next chapters cover the specific conventions of common libraries. For now, the rule is simple: never assume. Look for titles, check the sums, and confirm the class order.
Common mistakes
- Unpacking
cm.ravel()astn, fp, fn, tpwithout confirming that rows are actual labels and the negative class comes first. - Letting scikit-learn choose the label order for string classes, then assuming the first class is the positive one.
- Computing precision from a row sum or recall from a column sum. Precision divides by a column sum (predicted positives). Recall divides by a row sum (actual positives), in the scikit-learn layout.
- Reading a matrix copied from a paper or a screenshot without checking its axis titles.
- Using the sum check on a model whose predicted class counts equal the true class counts. It cannot detect orientation in that case.
Exercise
A colleague sends you this 2×2 matrix with no axis titles: [[50, 10], [5, 35]]. You know the dataset has 60 negatives and 40 positives, and the class order is 0 then 1. Which axis holds the actual labels, and what are TN, FP, FN and TP?
Show answer
The row sums are 50 + 10 = 60 and 5 + 35 = 40, which match the true class counts of 60 and 40. The column sums are 55 and 45, which do not match. So rows are actual labels and columns are predicted labels. With class 0 first, TN = 50, FP = 10, FN = 5 and TP = 35.
Exercise
You build a matrix with confusion_matrix(y_true, y_pred, labels=[1, 0]) and then run tn, fp, fn, tp = cm.ravel(). For the ten-sample example in this chapter, which values do the four variable names actually hold, and are they correct?
Show answer
With labels=[1, 0] the matrix is [[3, 1], [2, 4]]. Flattening gives 3, 1, 2, 4, so the code assigns tn = 3, fp = 1, fn = 2 and tp = 4. These names are wrong. The real values are tp = 3, fn = 1, fp = 2 and tn = 4. The correct unpacking for this label order is tp, fn, fp, tn = cm.ravel().