Sub topic 9
Evaluating Multiclass Models with a Confusion Matrix
What this chapter assumes
You should know binary precision, recall and F1, and how to fit a scikit-learn classifier on a train/test split. The earlier chapters on softmax and argmax explain how a multiclass model turns scores into one predicted class. This chapter starts from those predictions and asks how well they match the truth.
Accuracy is a single number and hides which classes fail. A confusion matrix keeps the full picture. Every per-class metric in this chapter comes from it.
The K×K confusion matrix
For K classes, the confusion matrix is a K×K table of counts. Entry [i, j] is the number of test samples whose true class is i and whose predicted class is j.
scikit-learn puts true classes in rows and predicted classes in columns. Some other tools use the opposite layout, so check the convention before reading anyone else's matrix.
This example has three classes and 120 test samples.
| True \ Predicted | cat | dog | bird | Row total |
|---|---|---|---|---|
| cat | 50 | 5 | 5 | 60 |
| dog | 10 | 30 | 0 | 40 |
| bird | 2 | 3 | 15 | 20 |
| Column total | 62 | 38 | 20 | 120 |
- The diagonal holds the correct predictions: 50 + 30 + 15 = 95.
- Every off-diagonal cell is a specific mistake. The 10 in row
dog, columncatmeans ten dogs were predicted as cats. - A row sum is the number of true samples of that class (its support).
- A column sum is the number of times the model predicted that class.
Accuracy is the trace divided by the total: 95 / 120 = 0.792.
Per-class precision and recall
Treat each class as "positive" and every other class as "negative". For class k:
- TP is
cm[k, k]. - FN is the rest of row
k, the trueksamples predicted as something else. - FP is the rest of column
k, the samples of other classes predicted ask.
So recall divides the diagonal by the row sums, and precision divides it by the column sums.
import numpy as np
names = ["cat", "dog", "bird"]
cm = np.array([
[50, 5, 5],
[10, 30, 0],
[2, 3, 15],
])
tp = np.diag(cm)
precision = tp / cm.sum(axis=0) # column sums = predicted counts
recall = tp / cm.sum(axis=1) # row sums = true counts
f1 = 2 * tp / (cm.sum(axis=0) + cm.sum(axis=1)) # 2TP / (2TP + FP + FN)
print("accuracy: ", round(tp.sum() / cm.sum(), 3))
for i, name in enumerate(names):
print(name, "precision", round(precision[i], 3),
"recall", round(recall[i], 3), "f1", round(f1[i], 3))The code gives precision of 0.806, 0.789 and 0.75, and recall of 0.833, 0.75 and 0.75. The F1 formula 2TP / (2TP + FP + FN) is the binary F1 rewritten in counts. Because FP + TP is the column sum and FN + TP is the row sum, the denominator is just the two sums added.
Dogs have lower recall than cats. The matrix shows why: the model misses dogs mostly by calling them cats.
Normalizing the matrix
Raw counts are hard to compare when classes differ in size. scikit-learn can normalize the matrix three ways.
| `normalize=` | Each cell is divided by | The diagonal then shows |
|---|---|---|
| `"true"` | its row sum | per-class recall |
| `"pred"` | its column sum | per-class precision |
| `"all"` | the grand total | the share of all samples |
Row normalization is the usual choice for diagnosis. Each row becomes a distribution that answers: given the true class, where do predictions go? Show raw counts next to it so that a tiny class with an alarming percentage is not mistaken for a large problem.
Computing it with scikit-learn
This example uses the iris baseline and prints the matrix, a per-class report and a plot-ready display object.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
confusion_matrix, classification_report, ConfusionMatrixDisplay
)
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=0
)
clf = LogisticRegression(max_iter=1000).fit(X_train, y_train)
y_pred = clf.predict(X_test)
labels = clf.classes_
print(confusion_matrix(y_test, y_pred, labels=labels))
print(confusion_matrix(y_test, y_pred, labels=labels, normalize="true").round(2))
print(classification_report(y_test, y_pred))
disp = ConfusionMatrixDisplay.from_predictions(
y_test, y_pred, normalize="true", values_format=".2f"
)
disp.figure_.savefig("confusion_iris.png")Always pass labels=. Without it, scikit-learn builds the matrix from the classes that appear in y_true or y_pred. If a test split lacks a class, the matrix shrinks and its rows no longer line up with your class list.
Reading the matrix for diagnosis
Look at the structure of the off-diagonal cells, not just the overall score.
- Concentrated errors. One large off-diagonal cell points to two classes the model cannot separate. Look for similar features, ambiguous labels or inconsistent annotation.
- Asymmetric errors.
dog → catis 10 butcat → dogis 5. The model leans towardcat, which is often a sign of class imbalance or a biased decision rule. - A dominant column. One column with many entries means the model over-predicts that class. Its precision falls.
- A weak row. A row with a small diagonal and spread-out errors means low recall for that class.
To rank the confusions in code, zero the diagonal and sort the remaining cells.
import numpy as np
names = ["cat", "dog", "bird"]
cm = np.array([[50, 5, 5], [10, 30, 0], [2, 3, 15]])
pairs = sorted(
((cm[i, j], names[i], names[j])
for i in range(len(names)) for j in range(len(names)) if i != j),
reverse=True,
)
for count, true_name, pred_name in pairs[:3]:
print(f"{true_name} predicted as {pred_name}: {count}")From the matrix to one summary number
Per-class scores need a single summary for model comparison. The next chapter covers averaging in detail. This table shows what each average gives for the cat/dog/bird example, so you can see the differences.
| Average | How it is computed | Value for the example |
|---|---|---|
| Micro F1 | pool all TP, FP and FN, then compute F1 | 0.792 |
| Macro F1 | unweighted mean of per-class F1 | 0.780 |
| Weighted F1 | mean of per-class F1 weighted by support | 0.791 |
In single-label multiclass problems, micro-averaged precision, recall and F1 all equal accuracy. Every wrong prediction is one false positive for the predicted class and one false negative for the true class, so the pooled FP and FN totals are equal.
Common errors
- Swapped axes. Reading columns as true classes swaps precision and recall. Check the convention of every library and plotting tool.
- Reporting only accuracy on imbalanced data. A model that gets the majority class right and misses a small one can still score high. Row-normalized recall exposes it.
- Omitting
labels=. The matrix shape and row order can then change between runs and splits. - Computing the matrix on training data. The diagonal will look better than it really is. Use held-out data, or out-of-fold predictions from
cross_val_predictwhen data is scarce. - Dividing by zero. A class that is never predicted has an empty column, so its precision is undefined. Set
zero_divisioninclassification_reportand report such classes explicitly. - Using a single small test split. In a rare class, one extra mistake moves a percentage a lot. Use stratified splits so every class appears in the test set, and read the counts next to the percentages.
Exercise
Using the cat/dog/bird matrix in this chapter, what is the recall of dog, what is its precision, and which single confusion is the model's largest mistake?
Show answer
Recall of dog is 30 / 40 = 0.75, because 30 of the 40 true dogs are on the diagonal. Precision of dog is 30 / 38 = 0.789, because the dog column sums to 38 (5 cats + 30 dogs + 3 birds). The largest mistake is dog predicted as cat, with 10 samples.
Exercise
A multiclass model has accuracy 0.92 on a test set. Why can the micro F1 be exactly 0.92 as well, and what would you inspect to find out whether a rare class is being missed?
Show answer
In single-label multiclass classification each error counts once as a false positive and once as a false negative, so pooled precision, recall and F1 all equal accuracy. To check a rare class, compute the row-normalized confusion matrix (or per-class recall) and look at the diagonal entry for that class, along with its support count.