Sub topic 3
Reading confusion matrices and per-class metrics
An aggregate score tells you how often the model is wrong. A confusion matrix tells you which classes it mixes up, and that is the first thing you need before you start reading individual errors.
This chapter assumes you can train a classifier and compute accuracy, precision, recall and F1 for a binary task. You should also be comfortable with NumPy arrays and scikit-learn. The examples use a three-class sentiment task with the labels neg, neu and pos.
What a confusion matrix contains
A confusion matrix is a table of counts. Each row is a true label, each column is a predicted label, and each cell counts the examples with that pair. Correct predictions sit on the diagonal. Every off-diagonal cell is a specific kind of mistake, such as "true neu, predicted pos".
Here is a small example. Compute it with scikit-learn.
from sklearn.metrics import classification_report, confusion_matrix
y_true = ["pos", "neg", "neu", "pos", "neg", "neu", "pos", "neg"]
y_pred = ["pos", "neg", "pos", "pos", "neu", "neu", "neg", "neg"]
labels = ["neg", "neu", "pos"]
# Rows are true labels, columns are predicted labels, in the order of `labels`.
print(confusion_matrix(y_true, y_pred, labels=labels))
print(classification_report(y_true, y_pred, labels=labels, zero_division=0))The matrix printed is:
[[2 1 0]
[0 1 1]
[1 0 2]]Read it row by row:
- Row
neg: of 3 true negatives, 2 were correct and 1 was calledneu. - Row
neu: of 2 true neutrals, 1 was correct and 1 was calledpos. - Row
pos: of 3 true positives, 2 were correct and 1 was calledneg.
Accuracy is the diagonal sum divided by the total: 5 of 8, or 0.625.
Always pass `labels`
Without the labels argument, scikit-learn sorts the labels it finds in the data. If a class is missing from both y_true and y_pred in some evaluation run, the matrix shrinks and its row order can shift. Passing an explicit list keeps the shape and order fixed across runs, so matrices from different experiments can be compared directly.
Orientation differs between tools
scikit-learn puts true labels on the rows. Some libraries and many papers transpose this, and the diagonal looks the same either way. Before you interpret an off-diagonal cell, check which axis is "true" and which is "predicted".
From the matrix to per-class metrics
Precision and recall for a class come from one column and one row of the matrix.
- Recall for class c is the diagonal cell divided by the row sum. It answers: of the examples that truly are c, how many did the model find?
- Precision for class c is the diagonal cell divided by the column sum. It answers: of the examples the model called c, how many really are c?
- F1 is the harmonic mean of the two, so it is low if either one is low.
- Support is the row sum, the number of true examples of the class.
The easiest way to remember this: rows are about what exists, so row sums give recall. Columns are about what the model claimed, so column sums give precision.
import numpy as np
labels = ["neg", "neu", "pos"]
cm = np.array([[2, 1, 0],
[0, 1, 1],
[1, 0, 2]])
tp = np.diag(cm)
precision = tp / cm.sum(axis=0) # column sums: predicted counts
recall = tp / cm.sum(axis=1) # row sums: true counts (support)
f1 = 2 * precision * recall / (precision + recall)
for name, p, r, f, s in zip(labels, precision, recall, f1, cm.sum(axis=1)):
print(f"{name}: precision={p:.2f} recall={r:.2f} f1={f:.2f} support={s}")
# Row-normalized matrix: each row sums to 1, so cells are per-class rates.
print(np.round(cm / cm.sum(axis=1, keepdims=True), 2))For this data, neg and pos each get precision, recall and F1 of 0.67, and neu gets 0.50 on all three. Neutral is the weakest class here, which is a typical pattern in sentiment work, since neutral text sits between the two other classes.
If a class is never predicted, its column sum is zero and precision is undefined. NumPy would produce a nan with a warning. scikit-learn reports 0.0 when you set zero_division=0. Choose one convention and state it, because a silent 0.0 can look like a model failure when it is really a missing prediction.
Normalizing the matrix
Raw counts are hard to compare when classes have very different sizes. A class with 5,000 examples will have large numbers in every cell, and a class with 50 will look empty. Normalization fixes this.
| Normalization | Each row sums to 1 | Each column sums to 1 | What a cell means |
|---|---|---|---|
| By true label (`normalize="true"`) | Yes | No | Fraction of true class *i* predicted as *j* (recall view) |
| By predicted label (`normalize="pred"`) | No | Yes | Fraction of predictions of class *j* that were truly *i* (precision view) |
| None (raw counts) | No | No | Absolute number of examples |
Use the row-normalized view to ask "where do the true examples of this class go?" Use the column-normalized view to ask "what is hiding inside this predicted class?" Keep the raw counts nearby, because a cell of 0.50 based on 2 examples carries little weight.
Averaging: macro, micro and weighted
A per-class table has one row per class. For a single summary you must pick an average, and each one hides something different.
- Macro average takes the unweighted mean across classes. Every class counts equally, so a poor result on a rare class pulls the number down.
- Weighted average weights each class by its support. It tracks overall performance and is dominated by common classes.
- Micro average pools all decisions before computing the metric. For single-label multiclass tasks, micro precision, micro recall and micro F1 all equal accuracy.
If the macro F1 is much lower than accuracy, some small class is doing badly. That gap is a signal to look at the per-class rows.
Reading the pattern, not just the numbers
Work through the matrix in a fixed order.
- Find the weakest classes. Sort the per-class table by F1 and note the support of each. A low F1 on a class with 10 examples is a weak signal.
- Separate recall problems from precision problems. Low recall means the class is being missed, and the row shows where its examples go. Low precision means other classes are leaking into it, and the column shows where they come from.
- Look for asymmetry. If many true
neuexamples are predictedposbut few trueposare predictedneu, the model has a bias towardpos. A symmetric confusion suggests the two classes are hard to tell apart in general, often because the labeling guidelines are unclear. - Look for clusters. In a larger label set, errors often concentrate in groups of related classes, such as fine-grained intents under one topic. Those groups tell you whether to merge labels, add examples, or write sharper guidelines.
- Name your candidates. Write down the three or four largest off-diagonal cells as pairs, for example "
neutopos". These pairs drive the next step, where you pull the examples behind each pair and read them.
Majority-class baselines
Compare against a trivial baseline before you praise any number. If 70% of examples are pos, a model that always predicts pos has 0.70 accuracy, and its confusion matrix has a single filled column. A real model should beat that on the weak classes, not only on overall accuracy.
Common errors when reading these tables
- Reading the matrix transposed. The wrong axis turns recall problems into precision problems and sends you looking in the wrong place.
- Ignoring support. A per-class F1 of 0.40 on 6 examples can easily move by 0.20 from changing one prediction. The later chapter on uncertainty in slice metrics covers how to put an interval around such numbers.
- Evaluating on the data you tuned on. Build the matrix from a held-out split. A confusion matrix from training data shows how well the model memorized, not where it fails.
- Treating multi-label tasks as multiclass. A single matrix assumes one label per example. For multi-label problems, compute one binary matrix per label instead.
- Reporting only the average. A macro F1 of 0.80 can come from five classes at 0.80 or from four at 0.95 and one at 0.20. Always show the per-class table next to it.
Where this leads
The matrix points to where errors happen but not why. The next step is to pull out the examples behind each large off-diagonal cell, which gives you a table you can read and sort. That table is the raw material for building an error taxonomy by hand.
Exercise
A classifier has this confusion matrix with rows as true labels and columns as predictions, in the order neg, neu, pos: [[8, 1, 1], [4, 4, 2], [0, 1, 9]]. Compute precision and recall for neu, and say what the biggest off-diagonal cell tells you.
Show answer
For neu, the diagonal cell is 4. The row sum is 4 + 4 + 2 = 10, so recall is 4/10 = 0.40. The column sum is 1 + 4 + 1 = 6, so precision is 4/6 = 0.67. The model rarely over-predicts neu but misses most true neutral examples. The largest off-diagonal cell is 4 in row neu, column neg: true neutral examples being called negative. That is the pair to pull and read first.
Exercise
A model has 0.90 accuracy, but its macro F1 is 0.62. What does the gap suggest, and what should you check next?
Show answer
Accuracy is dominated by large classes, and macro F1 weights every class equally, so some small class probably has a low F1. Print the per-class table with support, find the classes with low F1, and check whether they are rare. Then look at the matrix rows and columns for those classes to see whether the problem is missed examples (recall) or leakage from other classes (precision).