Sub topic 11
Axis conventions in scikit-learn and other tools
This chapter assumes you can already name the four outcomes (TP, FP, FN, TN) and compute precision and recall from them. You should also be able to read short Python snippets. The topic here is orientation: the same four counts can be arranged in more than one way, and a metric computed from the wrong arrangement is silently wrong.
Why orientation matters
A confusion matrix is a grid of counts. Nothing in the numbers says which axis holds actual labels and which holds predicted labels. Two tools can print the same grid of numbers and mean different things by it.
The risk is concrete. If you swap the axes of a binary matrix, the false positive and false negative counts trade places. Precision then turns into recall and recall into precision. Accuracy does not change, so the mistake can survive a quick sanity check.
The scikit-learn convention
In scikit-learn, confusion_matrix(y_true, y_pred) returns a matrix C where C[i, j] is the number of samples whose actual class is i and whose predicted class is j.
- Rows are actual labels.
- Columns are predicted labels.
- The argument order is
y_truefirst,y_predsecond.
The class order along both axes is the sorted order of the labels found in y_true and y_pred, unless you pass labels=. For binary data with labels 0 and 1, the order is [0, 1]. The negative class comes first, so the layout is:
| Row | Predicted 0 | Predicted 1 |
|---|---|---|
| **Actual 0** | TN | FP |
| **Actual 1** | FN | TP |
This is why cm.ravel() returns tn, fp, fn, tp in that order. It reads the cells row by row.
from sklearn.metrics import confusion_matrix
y_true = ["spam", "ham", "spam", "spam", "ham", "ham", "spam", "ham", "ham", "ham"]
y_pred = ["spam", "ham", "ham", "spam", "ham", "spam", "spam", "spam", "ham", "ham"]
# Default order is alphabetical: "ham" first, "spam" second.
cm = confusion_matrix(y_true, y_pred)
print(cm)
# [[4 2]
# [1 3]]
# Here "ham" is treated as the negative class, so ravel() gives the
# counts we want when "spam" is the positive class.
tn, fp, fn, tp = cm.ravel()
print(tn, fp, fn, tp) # 4 2 1 3With string labels, the alphabet decides which class counts as "negative" in ravel(). Here that works out by luck. If your positive class sorts first, the unpacking is wrong.
Fixing the order with `labels`
Always pass labels= when you unpack a binary matrix. Put the negative class first and the positive class second.
from sklearn.metrics import confusion_matrix
y_true = ["spam", "ham", "spam", "spam", "ham", "ham", "spam", "ham", "ham", "ham"]
y_pred = ["spam", "ham", "ham", "spam", "ham", "spam", "spam", "spam", "ham", "ham"]
# Wrong for unpacking: the positive class comes first.
wrong = confusion_matrix(y_true, y_pred, labels=["spam", "ham"])
print(wrong)
# [[3 1]
# [2 4]]
print(wrong.ravel()) # [3 1 2 4]: "tn" would really be the true positives
# Right: negative first, positive second.
right = confusion_matrix(y_true, y_pred, labels=["ham", "spam"])
tn, fp, fn, tp = right.ravel()
print(tn, fp, fn, tp) # 4 2 1 3The first matrix is not incorrect. It is a valid matrix with a different class order. The mistake is applying the tn, fp, fn, tp unpacking to it.
Other tools use other layouts
There is no universal standard. The table lists common conventions. Check the documentation of the version you use, because conventions and defaults can change.
| Tool or source | Rows | Columns |
|---|---|---|
| scikit-learn `confusion_matrix` | Actual (true) | Predicted |
| `ConfusionMatrixDisplay` plot | Actual (y-axis, "True label") | Predicted (x-axis, "Predicted label") |
| TensorFlow `tf.math.confusion_matrix` | Labels (actual) | Predictions |
| torchmetrics `ConfusionMatrix` | Target (actual) | Predicted |
| R `caret::confusionMatrix` | Prediction | Reference (actual) |
| Many textbooks and web articles | Often predicted | Often actual |
Two further points apply across tools.
- Some texts place the positive class first, so TP is in the top-left cell. scikit-learn's default binary layout puts TP in the bottom-right. The pattern "TP top-left" in a diagram does not carry over.
- Hand-built tables, spreadsheets, and
pandas.crosstabfollow whatever order you give them. Inpd.crosstab(a, b),abecomes the rows andbthe columns.
A probe that tests any tool
When you are unsure about a tool, feed it one deliberately lopsided example and see where the count lands. Take a single sample whose actual class is 1 and whose predicted class is 0. That sample is a false negative, and it should appear in the cell for actual 1, predicted 0.
from sklearn.metrics import confusion_matrix
# One sample: actual = 1, predicted = 0 (a false negative).
print(confusion_matrix([1], [0], labels=[0, 1]))
# [[0 0]
# [1 0]]
# The count sits in row 1 (actual), column 0 (predicted).If the count appears in row 1, column 0, then rows are actual and columns are predicted. If it appears in row 0, column 1, the tool is transposed. This takes seconds and avoids a long search through documentation.
Converting between layouts
Transposing a matrix converts one convention to the other. For scikit-learn output, cm.T has predicted labels on rows and actual labels on columns.
import pandas as pd
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]]
print(cm.T)
# [[4 1]
# [2 3]] rows are now predicted, columns are actual
# A labelled version removes the guesswork:
table = pd.crosstab(
pd.Series(y_true, name="actual"),
pd.Series(y_pred, name="predicted"),
)
print(table)
# predicted 0 1
# actual
# 0 4 2
# 1 1 3In the transposed matrix, the cell in row 0, column 1 holds 1. That is now the false negative count, where scikit-learn's own layout has it at row 1, column 0. Metric formulas that index by position must change with the layout. Formulas written in terms of TP, FP, FN, and TN do not.
Plotting: let the axis titles do the work
ConfusionMatrixDisplay draws the matrix with axis titles. Use display_labels so the class names appear on the ticks.
import matplotlib.pyplot as plt
from sklearn.metrics import ConfusionMatrixDisplay
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 0]
y_pred = [1, 0, 0, 1, 0, 1, 1, 1, 0, 0]
ConfusionMatrixDisplay.from_predictions(
y_true,
y_pred,
labels=[0, 1],
display_labels=["negative", "positive"],
)
plt.show()The plot shows "True label" on the vertical axis and "Predicted label" on the horizontal axis. When you share a matrix as a figure or a table, always include those titles. A bare grid of numbers forces the reader to guess the convention.
A reading routine
The routine has one rule behind it. Turn positions into named counts first, then compute metrics from the names. This keeps the formulas the same in every tool.
Common errors
- Assuming rows are predictions. This is the textbook layout in some sources and the reverse of scikit-learn. Precision and recall swap.
- Unpacking
ravel()withoutlabels=. The positive class lands in the wrong variable when labels sort differently than expected. - Passing arguments in the wrong order.
confusion_matrix(y_pred, y_true)runs without error and returns the transpose. - Comparing matrices across tools. Two matrices that look identical can describe different results. Compare them only after you have put them in the same layout.
- Trusting position for the positive class. Do not assume TP is top-left or bottom-right. Check the class order.
Exercise
A colleague sends this matrix from an unknown tool: [[50, 10], [5, 35]] for classes [0, 1]. They say the rows are predicted labels and the columns are actual labels, and class 1 is positive. What are TP, FP, FN, and TN, and what is the precision?
Show answer
With rows as predicted and columns as actual, the cell at row 1, column 1 is TP = 35. The cell at row 1, column 0 is predicted 1 and actual 0, so FP = 5. The cell at row 0, column 1 is predicted 0 and actual 1, so FN = 10. The cell at row 0, column 0 is TN = 50. Precision = TP / (TP + FP) = 35 / 40 = 0.875. If you wrongly read the rows as actual, you would get FP = 10 and precision = 35 / 45, about 0.778.
Exercise
You call confusionmatrix(ytrue, y_pred) on string labels "fraud" and "legit", with "fraud" as the positive class, and unpack cm.ravel() into tn, fp, fn, tp. Which variable holds the true positives, and how do you fix the code?
Show answer
The default order is alphabetical, so "fraud" comes first and acts as index 0. The first cell, which ravel() assigns to tn, is the count of actual fraud predicted as fraud, which is the true positives. The variable tp then holds the true negatives. The fix is to call confusionmatrix(ytrue, y_pred, labels=["legit", "fraud"]) so the negative class comes first, and then unpack as before.