Sub topic 3
The confusion matrix at one threshold
This chapter assumes you know binary classification, can read NumPy code, and have seen predicted scores from a model such as logistic regression. The previous chapter showed how a score becomes a label once you pick a threshold. Here you count what happens when you do that for one fixed threshold.
Four outcomes
Every example has a true label (0 or 1) and a predicted label (0 or 1). That gives four combinations:
- True positive (TP): the example is positive and you predicted positive.
- False positive (FP): the example is negative and you predicted positive.
- True negative (TN): the example is negative and you predicted negative.
- False negative (FN): the example is positive and you predicted negative.
A confusion matrix is a 2 by 2 table of these four counts.
| Row | Predicted negative | Predicted positive |
|---|---|---|
| **Actually negative** | TN | FP |
| **Actually positive** | FN | TP |
The counts always add up to the number of examples. The matrix is tied to one threshold. Change the threshold and the counts change.
A worked example
Use four examples with these true labels and scores:
| Example | True label | Score |
|---|---|---|
| 1 | 0 | 0.10 |
| 2 | 0 | 0.40 |
| 3 | 1 | 0.35 |
| 4 | 1 | 0.80 |
Set the threshold to 0.5 and predict positive when the score is at or above it. Only example 4 is predicted positive. Example 4 is a TP. Examples 1 and 2 are TNs. Example 3 is a positive that scored 0.35, so it is an FN. The counts are TN=2, FP=0, FN=1, TP=1.
Now lower the threshold to 0.35. Examples 2, 3 and 4 are predicted positive. Example 2 becomes an FP, and example 3 becomes a TP. The counts are TN=1, FP=1, FN=0, TP=2.
Lowering the threshold caught the missed positive. It also created a false alarm. This trade-off is what a ROC curve tracks across all thresholds.
Computing it in code
scikit-learn's confusion_matrix returns rows for the true class and columns for the predicted class. With labels=[0, 1], the flattened order is TN, FP, FN, TP.
import numpy as np
from sklearn.metrics import confusion_matrix
y_true = np.array([0, 0, 1, 1])
y_score = np.array([0.1, 0.4, 0.35, 0.8])
for t in [0.5, 0.35]:
y_pred = (y_score >= t).astype(int)
tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel()
print(f"threshold={t}: TN={tn} FP={fp} FN={fn} TP={tp}")The output is:
threshold=0.5: TN=2 FP=0 FN=1 TP=1
threshold=0.35: TN=1 FP=1 FN=0 TP=2These match the hand counts above.
Common errors
- Swapped axes. In scikit-learn, rows are true labels and columns are predictions. Some textbooks and tools use the opposite layout. Check the layout before you read off FP and FN.
- Strict versus non-strict comparison. This tutorial predicts positive when
score >= threshold. Using>changes the counts when a score equals the threshold exactly. - Passing scores as predictions.
confusion_matrixneeds hard 0/1 labels. Passing raw probabilities raises an error because they are not valid labels. - Forgetting the threshold. Reporting a confusion matrix without its threshold makes the numbers impossible to interpret. Many classifiers'
predictuses 0.5 by default, which may not suit your problem.
What comes next
The four counts are the raw material for the next chapter. TPR and FPR divide them by the number of actual positives and actual negatives. A ROC curve plots those two rates as the threshold sweeps from high to low.
Exercise
Using the scores and labels from the worked example, what are TN, FP, FN and TP at a threshold of 0.4 (predict positive when score >= 0.4)?
Show answer
The predicted labels are [0, 1, 0, 1]. Example 1 is a TN. Example 2 is an FP, because it is negative but scored exactly 0.4. Example 3 is an FN, because it is positive but scored 0.35. Example 4 is a TP. The counts are TN=1, FP=1, FN=1, TP=1.