Sub topic 1
Predicted labels versus actual labels
A confusion matrix is built from two lists of labels for the same examples. One list says what each example really is. The other says what the model claimed it was. This chapter defines those two lists, shows how they are produced, and covers the mistakes that make every later number wrong.
Prerequisites
This chapter assumes you know the following:
- The basic idea of supervised classification: a model learns from labeled examples and then assigns labels to new ones.
- Fractions and ratios, such as "7 out of 10".
- Short Python snippets. The examples use plain lists and scikit-learn.
You do not need to know any metric yet. Accuracy, precision and recall come in later chapters.
What a classifier produces
A classifier is a model that assigns each input to one of a fixed set of categories called classes. Typical examples are spam or not spam, a disease present or absent, and bird, cat or dog.
The class a model assigns to an example is its predicted label. The class the example truly belongs to is its actual label. You will also see these called the ground truth, the true label, or the target. The tutorial uses actual and predicted throughout.
The two labels can disagree, and the confusion matrix counts how often and in which direction.
Where each list comes from
The two lists come from different places, and the difference matters when you judge how far to trust a result.
- Actual labels come from outside the model. A person annotated them, a later event confirmed them, or a lab test produced them. They are the best available reference, not a perfect one. Annotators disagree, and some outcomes are recorded wrongly. If 3% of your actual labels are wrong, no metric can show you that.
- Predicted labels come from the model. Most models first produce a score for each class, such as a probability, and then a rule turns the score into a label. For two classes the rule is usually "predict positive if the score is at least a threshold". For several classes it is usually "predict the class with the highest score".
The following diagram shows both paths ending in one comparison.
Pairing the lists
The central operation is simple. For each example, write down the pair (actual, predicted). The confusion matrix is a table of how many examples fall into each distinct pair.
The following code does this by hand with the standard library.
from collections import Counter
y_true = ["spam", "ham", "spam", "ham", "ham", "spam"]
y_pred = ["spam", "ham", "ham", "ham", "spam", "spam"]
pairs = Counter(zip(y_true, y_pred))
for (actual, predicted), count in sorted(pairs.items()):
print(f"actual={actual:4} predicted={predicted:4} count={count}")This prints:
actual=ham predicted=ham count=2
actual=ham predicted=spam count=1
actual=spam predicted=ham count=1
actual=spam predicted=spam count=2Two pairs have matching labels, so those predictions were correct. Two pairs have different labels, so those were errors, and each error has a direction. Calling a real spam message "ham" is a different mistake from calling real ham "spam". A single accuracy number hides that difference, which is why the matrix exists.
From scores to predicted labels
You rarely hand a confusion matrix predicted labels directly. Usually the model outputs scores, and you choose the rule that converts them. The same scores give different predicted labels under different rules.
scores = [0.9, 0.2, 0.4, 0.8, 0.1] # model's probability of the positive class
def to_labels(scores, threshold):
return [1 if s >= threshold else 0 for s in scores]
print(to_labels(scores, 0.5)) # [1, 0, 0, 1, 0]
print(to_labels(scores, 0.3)) # [1, 0, 1, 1, 0]The third example has a score of 0.4. It is labeled 0 at a threshold of 0.5 and labeled 1 at a threshold of 0.3. The model did not change. Only the rule did, and the confusion matrix changes with it. A later chapter covers this effect in detail. For now, remember that a confusion matrix describes a model together with a decision rule, not the model alone.
For a multiclass model the usual rule picks the class with the largest score:
import numpy as np
classes = ["bird", "cat", "dog"]
probs = np.array([
[0.7, 0.2, 0.1],
[0.1, 0.5, 0.4],
[0.2, 0.3, 0.5],
])
y_pred = [classes[i] for i in probs.argmax(axis=1)]
print(y_pred) # ['bird', 'cat', 'dog']Argument order in scikit-learn
scikit-learn's confusion_matrix takes the actual labels first and the predicted labels second. This is the most common source of silent errors in this topic, because the function runs without complaint if you swap them.
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]
print(confusion_matrix(y_true, y_pred, labels=[0, 1]))
# [[4 2]
# [1 3]]
print(confusion_matrix(y_pred, y_true, labels=[0, 1])) # swapped by mistake
# [[4 1]
# [2 3]]Swapping the arguments transposes the matrix. The swapped version has the same numbers in different cells, so it looks plausible. Any metric you compute from it, such as precision, will actually be recall, and the reverse. Name your variables y_true and y_pred and always pass them in that order.
Rules for valid inputs
Before you build a matrix, check these conditions.
- Same length, same order. Entry
iin both lists must describe the same example. If you shuffle one list and not the other, the pairs are meaningless. - Same label encoding. If the actual labels are the strings
"yes"and"no"and the predictions are1and0, the pairs never match. Convert both lists to one encoding first. - Held-out data. Evaluate on examples the model did not train on. On training data the model has seen the answers, so the predicted labels agree with the actual labels more often than they will on new data. The matrix looks better than reality.
- Predicted labels, not scores. Passing raw probabilities such as
0.83to a function that expects labels raises an error in scikit-learn. A hand-written comparison would quietly treat every example as wrong. Convert scores with a threshold orargmaxfirst. - A fixed label list. If a class never appears in the actual labels or the predictions of a small sample, the matrix can silently lose a row or column. Passing
labels=[...]explicitly keeps the shape stable across runs.
Edge cases to know
- Noisy actual labels. When the reference labels contain mistakes, some "model errors" are really annotation errors. If the errors cluster in a single cell, inspect those examples by hand before you retrain.
- Delayed labels. In fraud detection or loan default, the actual label may arrive weeks after the prediction. Examples without a confirmed label must be excluded, and that can bias the sample toward cases that were investigated.
- Predictions that feed back. If the model's decision affects whether you ever see the actual label, as when a rejected loan applicant is never observed repaying, the actual labels only cover cases the model approved. The matrix then describes a filtered population.
- Abstention. Some systems may answer "unsure". Decide before you count whether "unsure" is its own predicted class or the example is dropped. Either choice is defensible, but each gives different numbers, so state the choice.
Summary of terms
| Term | Meaning | Source |
|---|---|---|
| Actual label | The class an example truly belongs to | Annotators, lab results, later outcomes |
| Predicted label | The class the model assigned | Model scores plus a decision rule |
| Pair | One (actual, predicted) combination for one example | Built by zipping the two lists |
| Correct prediction | A pair whose two labels match | Counted along the matrix diagonal |
| Error | A pair whose labels differ | Counted off the diagonal, with a direction |
The next chapter names the four possible pair types for a two-class problem and gives each a standard name.
Exercise
A teammate reports a confusion matrix of [[4 1] [2 3]] for a model, but your own run on the same data with confusion_matrix(y_true, y_pred, labels=[0, 1]) gave [[4 2] [1 3]]. What is the most likely cause, and why does it matter for any metric computed from the matrix?
Show answer
The teammate most likely passed the arguments in the wrong order, confusion_matrix(y_pred, y_true). Swapping the arguments transposes the matrix. Any metric that depends on which axis holds the actual labels, such as precision and recall, will come out swapped. Rerun with the actual labels first and compare the result to your own matrix.
Exercise
A model returns the scores [0.45, 0.62, 0.30, 0.55] for four examples whose actual labels are [1, 1, 0, 0]. Give the predicted labels at a threshold of 0.5 and at a threshold of 0.4, and say how many predictions are correct in each case.
Show answer
At 0.5 the predicted labels are [0, 1, 0, 1]. The pairs (1,0), (1,1), (0,0) and (0,1) give 2 correct predictions out of 4. At 0.4 the predicted labels are [1, 1, 0, 1]. The pairs (1,1), (1,1), (0,0) and (0,1) give 3 correct predictions out of 4. The model's scores are the same in both cases. Only the decision rule changed.