Sub topic 13
Reading a Multiclass Matrix
This chapter assumes you can read a binary confusion matrix and compute precision and recall from its four cells. It also assumes you can follow short Python snippets that use NumPy and scikit-learn. Here the same ideas extend to three or more classes.
From two classes to many
A binary matrix has one positive class and one negative class. A multiclass matrix has N classes and is an N x N grid. Each cell counts how many examples had one actual class and received one predicted class.
With scikit-learn's orientation, rows are actual labels and columns are predicted labels. Cell [i, j] is the number of examples whose true class is i and whose predicted class is j. Always confirm this orientation before reading, as covered in the earlier chapter on axis conventions.
- The diagonal cells
[i, i]are correct predictions. - Every off-diagonal cell is an error, and its position tells you which kind.
- Each row sums to the number of actual examples of that class (the class's support).
- Each column sums to the number of times the model predicted that class.
A worked example
This data has three classes. The code prints the counts and then the row-normalized version.
from sklearn.metrics import confusion_matrix
labels = ["bird", "cat", "dog"]
y_true = ["cat", "cat", "cat", "dog", "dog", "dog", "bird", "bird", "bird", "bird"]
y_pred = ["cat", "cat", "dog", "dog", "dog", "dog", "bird", "cat", "bird", "bird"]
cm = confusion_matrix(y_true, y_pred, labels=labels)
print(cm)
# [[3 1 0]
# [0 2 1]
# [0 0 3]]
# Each row sums to 1, so the diagonal holds per-class recall.
print(confusion_matrix(y_true, y_pred, labels=labels, normalize="true"))Passing labels= fixes the order of rows and columns. Without it, scikit-learn sorts the labels that appear, which can silently change the layout between runs if a class is missing from a split.
Read the matrix one row at a time:
| Row (actual) | Predicted bird | Predicted cat | Predicted dog | What happened |
|---|---|---|---|---|
| bird | 3 | 1 | 0 | One bird was called a cat. |
| cat | 0 | 2 | 1 | One cat was called a dog. |
| dog | 0 | 0 | 3 | All dogs were found. |
Overall accuracy is the diagonal sum divided by the total: (3 + 2 + 3) / 10 = 0.8.
Reading a cell, a row and a column
The same matrix answers different questions depending on how you slice it.
- A row answers "when the truth is X, what does the model say?" The diagonal share of a row is that class's recall.
- A column answers "when the model says X, what was the truth?" The diagonal share of a column is that class's precision.
- A single off-diagonal cell names one specific confusion, such as "actual cat, predicted dog".
An error therefore hurts two classes at once. The cell "actual cat, predicted dog" is a missed cat, which lowers cat recall. It is also a false alarm for dog, which lowers dog precision.
Per-class counts: one-vs-rest
Precision, recall and specificity are defined for a single positive class. In a multiclass problem, you compute them by treating each class in turn as the positive class and all the others as the negative class. This is the one-vs-rest view. For class k:
- TP is the diagonal cell
cm[k, k]. - FN is the rest of row
k:cm[k].sum() - TP. - FP is the rest of column
k:cm[:, k].sum() - TP. - TN is everything else: the total minus TP, FP and FN.
import numpy as np
labels = ["bird", "cat", "dog"]
cm = np.array([[3, 1, 0],
[0, 2, 1],
[0, 0, 3]])
tp = np.diag(cm)
fp = cm.sum(axis=0) - tp
fn = cm.sum(axis=1) - tp
tn = cm.sum() - tp - fp - fn
precision = tp / (tp + fp)
recall = tp / (tp + fn)
for name, p, r in zip(labels, precision, recall):
print(f"{name}: precision={p:.2f} recall={r:.2f}")
# bird: precision=1.00 recall=0.75
# cat: precision=0.67 recall=0.67
# dog: precision=0.75 recall=1.00Each class gets its own binary matrix with TP, FP, FN and TN. For example, for cat: TP = 2, FP = 1, FN = 1, TN = 6. The four counts sum to 10, the total number of examples.
The numbers describe the model's behavior:
- Bird has perfect precision. Nothing else was ever called a bird. Its recall is 0.75, because one bird was labeled a cat.
- Dog has perfect recall. The model finds every dog, but it also calls one cat a dog, so precision is 0.75.
- Cat is the weakest class on both measures.
Finding which classes get confused
The diagonal says how often the model is right. The off-diagonal cells say how it is wrong, and that is where you find what to fix. To locate the largest confusion, zero the diagonal and look for the biggest remaining cell.
import numpy as np
labels = ["bird", "cat", "dog"]
cm = np.array([[3, 1, 0],
[0, 2, 1],
[0, 0, 3]])
errors = cm.copy()
np.fill_diagonal(errors, 0)
i, j = np.unravel_index(errors.argmax(), errors.shape)
print(f"Most common error: actual {labels[i]}, predicted {labels[j]} ({errors[i, j]} times)")
# Most common error: actual bird, predicted cat (1 times)Here argmax returns the first cell in row-major order when two cells tie. In this matrix, bird-as-cat and cat-as-dog both have a count of 1. With larger counts, ties are rare, but check the whole error matrix before you act on a single cell.
Patterns to look for in a real matrix:
- A bright off-diagonal cell means two classes look alike to the model. Candidates are more training data for the pair, better features, or merging the classes if the distinction does not matter.
- An empty column means the model never predicts that class.
- A symmetric pair (A as B and B as A) suggests the classes overlap. A one-sided pair (A as B but rarely B as A) suggests the model has a bias toward B.
- A dense column means the model uses that class as a default guess.
Normalization changes the story
Raw counts are dominated by large classes. A class with 1,000 examples will have bigger cell values than a class with 20, even if the model handles the small class better. Normalizing fixes the scale.
| `normalize=` | Each ... sums to 1 | Diagonal shows | Use it to ask |
|---|---|---|---|
| `"true"` | row | per-class recall | Of the real X, where did they go? |
| `"pred"` | column | per-class precision | Of the predicted X, what were they really? |
| `"all"` | whole matrix | share of all examples | What fraction of all data lands in each cell? |
Normalize by row when your question is about missing real examples. Normalize by column when your question is about trusting a prediction. Keep the raw counts nearby as well. A cell showing 0.50 can mean 1 of 2 or 500 of 1,000.
Averaging per-class scores
Per-class scores give you N numbers per metric. To report one number, you average them. The three common choices differ in how much weight each class receives.
- Macro averages the per-class scores with equal weight. A rare class counts as much as a common one. Use it when every class matters equally.
- Weighted averages the per-class scores, weighting each by its support. It reflects the class mix in your data.
- Micro pools the TP, FP and FN counts across all classes before computing the metric. In single-label multiclass problems, every error is one class's FP and another's FN. Micro precision, micro recall and micro F1 therefore all equal accuracy.
from sklearn.metrics import precision_score
labels = ["bird", "cat", "dog"]
y_true = ["cat", "cat", "cat", "dog", "dog", "dog", "bird", "bird", "bird", "bird"]
y_pred = ["cat", "cat", "dog", "dog", "dog", "dog", "bird", "cat", "bird", "bird"]
for avg in ("macro", "weighted", "micro"):
print(avg, round(precision_score(y_true, y_pred, labels=labels, average=avg), 3))
# macro 0.806
# weighted 0.833
# micro 0.8Macro precision is (1.00 + 0.67 + 0.75) / 3, about 0.806. Weighted precision is (4 x 1.00 + 3 x 0.667 + 3 x 0.75) / 10, about 0.825. Micro precision is 8 / 10, which equals accuracy.
Common mistakes
- Reading the axes backward. Some tools put predicted labels on the rows. Check the axis titles or the documentation first.
- Assuming sorted label order. Pass
labels=explicitly so the display names match the matrix positions. - Judging by accuracy alone. An accuracy of 0.95 can hide a class with recall near zero. Check the per-class recall on the diagonal of the row-normalized matrix.
- Comparing raw counts across classes of different size. Normalize first.
- Reporting an average without naming it. "F1 = 0.81" is ambiguous until you say macro, micro or weighted.
Exercise
A four-class model has this matrix, with rows as actual classes A, B, C, D and columns as predicted classes A, B, C, D: [[8, 1, 1, 0], [0, 6, 4, 0], [0, 0, 10, 0], [1, 0, 0, 9]]. What are the recall and precision of class C, and which confusion is the largest?
Show answer
Class C recall is the diagonal cell over its row sum: 10 / 10 = 1.0. Its precision is the diagonal cell over its column sum: column C is 1 + 4 + 10 + 0 = 15, so precision is 10 / 15, about 0.67. The largest confusion is the off-diagonal cell in row B, column C: actual B predicted as C, 4 times. That error lowers B's recall to 0.6 and C's precision.
Exercise
A matrix has 100 examples of class X, 100 of class Y and 10 of class Z. The model scores recall 0.9 on X, 0.9 on Y and 0.3 on Z. Is macro or weighted recall lower, and why?
Show answer
Macro recall is lower. Macro gives each class equal weight: (0.9 + 0.9 + 0.3) / 3 = 0.70. Weighted recall uses support: (100 x 0.9 + 100 x 0.9 + 10 x 0.3) / 210 = 183 / 210, about 0.87. The weak small class pulls the macro average down much more.