Sub topic 12
Normalizing by Row, Column or Total
This chapter assumes you can read a raw confusion matrix and know the four outcomes (TP, FP, FN, TN). It also assumes you know the scikit-learn layout, where rows are actual labels and columns are predicted labels. Normalizing divides each count by a total, so cells become proportions. Which total you divide by decides which question the matrix answers.
Why raw counts are not enough
Raw counts depend on how many examples you evaluated. A matrix from 10 examples and one from 10,000 cannot be compared by eye. Counts also hide the class mix. A cell holding 50 means one thing in a class with 60 examples and another in a class with 5,000.
Normalization fixes both problems. Each cell becomes a fraction between 0 and 1, and you pick the denominator to match your question.
The three normalization modes
scikit-learn's confusion_matrix takes a normalize argument with three useful values.
| `normalize` | Divide each cell by | Each... sums to 1 | Question answered |
|---|---|---|---|
| `"true"` | its row total (actual class size) | row | Of the examples that truly belong to this class, where did the model put them? |
| `"pred"` | its column total (predicted class size) | column | Of the examples the model assigned to this class, what were they really? |
| `"all"` | the grand total | whole matrix | What share of all examples fall in each cell? |
| `None` (default) | nothing | not applicable | Raw counts |
Here is the binary example from earlier chapters, with all three modes applied.
import numpy as np
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]
for mode in ("true", "pred", "all"):
cm = confusion_matrix(y_true, y_pred, labels=[0, 1], normalize=mode)
print(mode)
print(np.round(cm, 3))
# true
# [[0.667 0.333]
# [0.25 0.75 ]]
# pred
# [[0.8 0.4]
# [0.2 0.6]]
# all
# [[0.4 0.2]
# [0.1 0.3]]The raw matrix was [[4, 2], [1, 3]]. Each mode divides it differently.
Row normalization: the diagonal is recall
With normalize="true", row 0 holds the actual negatives. It reads [0.667, 0.333]. Two thirds of the negatives were predicted negative, and one third became false positives.
Row 1 holds the actual positives. It reads [0.25, 0.75]. Three quarters were found and one quarter was missed.
Each diagonal cell is the recall of that class:
- Cell
[1, 1]isTP / (TP + FN), which is recall (sensitivity) for the positive class, 0.75. - Cell
[0, 0]isTN / (TN + FP), which is specificity, 0.667. This is recall for the negative class. - Cell
[0, 1]is the false positive rate, 0.333, which equals 1 minus specificity. - Cell
[1, 0]is the false negative rate, 0.25, which equals 1 minus recall.
Row normalization is the default choice for most reports. It answers "how well do we do on each real class?" It also ignores class sizes, so a rare class gets the same visual weight as a common one.
Column normalization: the diagonal is precision
With normalize="pred", column 1 holds everything the model called positive. It reads [0.4, 0.6]. Of the examples predicted positive, 60% truly were. That diagonal cell is precision (TP / (TP + FP)), and the 0.4 above it is the share of false alarms among positive predictions.
Use this view when you care about what a prediction is worth. A fraud analyst who reviews every flagged transaction wants to know what fraction of flags are real. That is a column question.
Total normalization: the joint distribution
With normalize="all", the four cells sum to 1. They show how the whole evaluation set splits across outcomes. Accuracy is the sum of the diagonal, 0.4 + 0.3 = 0.7.
The row sums here are the class prevalences. The sums are 0.6 for actual negatives and 0.4 for actual positives. The matrix therefore keeps the class-balance information that the other two modes remove. It is most useful for a quick look at where the bulk of the examples sit, or when you need cell probabilities for a cost calculation.
Prevalence changes column views but not row views
Row-normalized values describe the model's behavior on each class. They stay roughly the same if you change how many examples of each class you test on. Column-normalized values mix both classes, so they shift when the class mix shifts.
Take a model with recall 0.75 and false positive rate 0.25. Evaluate it on two sets.
| Test set | TP | FN | FP | TN | Row-normalized positive row | Precision (column view) |
|---|---|---|---|---|---|---|
| 100 positives, 100 negatives | 75 | 25 | 25 | 75 | 0.25, 0.75 | 0.75 |
| 100 positives, 1,000 negatives | 75 | 25 | 250 | 750 | 0.25, 0.75 | about 0.23 |
The model did not change, and the row view shows that. Precision fell from 0.75 to about 0.23 because negatives became ten times more common. Treat a column-normalized matrix as valid only for data with the class mix you evaluated on. If production prevalence differs from your test set, precision in production will differ too.
Empty rows and columns
A row or column that sums to zero cannot be divided. Here is the always-negative model from the accuracy-trap chapter.
import numpy as np
from sklearn.metrics import confusion_matrix
y_true = [0] * 95 + [1] * 5
y_pred = [0] * 100
print(confusion_matrix(y_true, y_pred, labels=[0, 1], normalize="true"))
# [[1. 0.]
# [1. 0.]]
print(confusion_matrix(y_true, y_pred, labels=[0, 1], normalize="pred"))
# [[0.95 0. ]
# [0.05 0. ]]The row view exposes the failure. The positive row is [1, 0], so recall is 0. The column view shows the other problem. Column 1 is empty, because the model never predicted a positive, so precision is undefined. scikit-learn replaces the resulting NaN with 0, which can look like "0% precision" when the honest answer is "no predictions to judge". When you see a column of zeros after normalizing, check the raw counts.
Normalizing a multiclass matrix
The same rules hold with more classes. Row normalization turns the diagonal into per-class recall. Column normalization turns it into per-class precision. Use the three-class animal example.
import numpy as np
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"]
by_row = confusion_matrix(y_true, y_pred, labels=labels, normalize="true")
by_col = confusion_matrix(y_true, y_pred, labels=labels, normalize="pred")
print(np.round(by_row, 2))
# [[0.75 0.25 0. ]
# [0. 0.67 0.33]
# [0. 0. 1. ]]
print(np.round(by_col, 2))
# [[1. 0.33 0. ]
# [0. 0.67 0.25]
# [0. 0. 0.75]]Reading the row view: 25% of birds were called cats, 33% of cats were called dogs, and no dog was misclassified. The diagonal gives recall of 0.75 for bird, 0.67 for cat and 1.0 for dog.
Reading the column view: everything predicted bird really was a bird, so bird precision is 1.0. Of the predictions of cat, one third were birds. Of the predictions of dog, a quarter were cats.
The two views give different diagonals for the same model. Dog has perfect recall but only 0.75 precision, because cats leak into it.
Choosing a mode
A practical default is to show the raw counts next to the row-normalized matrix. The proportions show the pattern, and the counts show how much data stands behind each cell.
Plotting a normalized matrix
ConfusionMatrixDisplay accepts the same argument, and it takes the labels list to keep the order fixed.
import matplotlib.pyplot as plt
from sklearn.metrics import ConfusionMatrixDisplay
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"]
ConfusionMatrixDisplay.from_predictions(
y_true, y_pred, labels=labels, normalize="true", values_format=".2f"
)
plt.show()Label the figure with the mode you used. A heatmap of proportions with no title leaves readers guessing whether rows or columns sum to 1.
Common mistakes
- Reading a column-normalized matrix as if it were row-normalized. Check which axis sums to 1 before you interpret anything.
- Comparing column-normalized matrices from datasets with different class mixes.
- Treating a zero from an empty row or column as a measured 0%.
- Comparing matrices from other libraries without checking orientation. Some tools put predictions on the rows, and then the meaning of "row" and "column" swaps.
- Ignoring the raw counts. A row of
[0.0, 1.0]could come from 2 examples or 2,000.
Exercise
A matrix has raw counts [[90, 10], [20, 80]] with rows as actual labels (negative, positive) and columns as predicted labels. Compute the row-normalized and column-normalized positive-class diagonal cells. What does each represent?
Show answer
The row total for actual positives is 20 + 80 = 100, so the row-normalized cell is 80 / 100 = 0.80. This is recall. The column total for predicted positives is 10 + 80 = 90, so the column-normalized cell is 80 / 90, about 0.889. This is precision.
Exercise
A model has recall 0.8 and false positive rate 0.1. On a test set of 100 positives and 100 negatives, what is its precision? What is the precision on a set with 100 positives and 1,000 negatives? Which normalization changed?
Show answer
Balanced set: TP = 80, FP = 10, so precision = 80 / 90, about 0.889. Skewed set: TP = 80, FP = 100, so precision = 80 / 180, about 0.444. The column-normalized view changed. The row-normalized view stayed at recall 0.8 and false positive rate 0.1, because each row is divided by its own class size.