Sub topic 3
The Confusion Matrix at One Threshold
This chapter assumes you know binary classification, the meaning of true and false positives and negatives, and basic NumPy. You should also have a classifier that outputs a score or probability for the positive class. The previous chapter turned scores into labels with a threshold. This chapter counts how those labels agree with the truth. A ROC curve is built from many of these counts, so each one needs to be right.
One threshold, one confusion matrix
A confusion matrix summarizes a classifier's decisions on a fixed dataset. It is only defined for hard predictions, so it depends on the threshold. Change the threshold and the matrix changes, even though the model and the data stay the same.
The recipe has three steps:
- Pick a threshold
t. - Predict positive when
score >= t, and negative otherwise. - Compare each prediction with its true label and count the four outcomes.
The four cells
Here the positive class is the one you want to detect, labeled 1.
| Row | Predicted negative | Predicted positive |
|---|---|---|
| **Actually negative** | True negative (TN) | False positive (FP) |
| **Actually positive** | False negative (FN) | True positive (TP) |
Each name has two parts. The second word is the prediction: "positive" or "negative". The first word says whether that prediction was right. A false positive is a negative example that was predicted positive. A false negative is a positive example that was missed.
Two sums stay the same no matter which threshold you use:
- TP + FN equals the number of actual positives.
- FP + TN equals the number of actual negatives.
The threshold decides how each actual positive and each actual negative is split between the two columns. It never changes the row totals. The next chapter uses this fact, because dividing by a fixed row total is what makes rates comparable across thresholds.
Counting by hand
We use the same four-example set that appears throughout this tutorial. Two examples are negative and two are positive.
| Example | True label | Score |
|---|---|---|
| A | 0 | 0.10 |
| B | 0 | 0.40 |
| C | 1 | 0.35 |
| D | 1 | 0.80 |
Take t = 0.5. Only D scores at least 0.5, so the predictions are [0, 0, 0, 1].
- A is a negative predicted negative, so it is a TN.
- B is a negative predicted negative, so it is a TN.
- C is a positive predicted negative, so it is a FN.
- D is a positive predicted positive, so it is a TP.
The counts are TN = 2, FP = 0, FN = 1, TP = 1. Here is the same calculation in NumPy:
import numpy as np
y_true = np.array([0, 0, 1, 1])
y_score = np.array([0.1, 0.4, 0.35, 0.8])
def confusion_counts(y_true, y_score, threshold):
actual = np.asarray(y_true) == 1
pred = np.asarray(y_score) >= threshold
tp = int((pred & actual).sum())
fp = int((pred & ~actual).sum())
fn = int((~pred & actual).sum())
tn = int((~pred & ~actual).sum())
return tn, fp, fn, tp
tn, fp, fn, tp = confusion_counts(y_true, y_score, 0.5)
print(tn, fp, fn, tp) # 2 0 1 1The function uses boolean arrays, so each count is a sum of an element-wise AND. The ~ operator flips a boolean array. No loop is needed.
Checking against scikit-learn
sklearn.metrics.confusion_matrix returns a 2-by-2 array. Its layout is a frequent source of mistakes:
- Rows are the true classes. Columns are the predicted classes.
- Classes are sorted in ascending order, so for labels 0 and 1 the array is
[[TN, FP], [FN, TP]].
Calling .ravel() flattens it row by row, which gives the order 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])
pred = (y_score >= 0.5).astype(int)
cm = confusion_matrix(y_true, pred, labels=[0, 1])
print(cm)
# [[2 0]
# [1 1]]
tn, fp, fn, tp = cm.ravel()
print(tn, fp, fn, tp) # 2 0 1 1Passing labels=[0, 1] fixes the order explicitly. Without it, a test split that happens to contain only one class would produce a 1-by-1 matrix, and the unpacking on the last line would fail.
How the matrix changes as the threshold moves
Now apply four thresholds to the same data. They are the distinct scores, from highest to lowest.
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.8, 0.4, 0.35, 0.1]:
pred = (y_score >= t).astype(int)
tn, fp, fn, tp = confusion_matrix(y_true, pred, labels=[0, 1]).ravel()
print(f"t={t}: TN={tn} FP={fp} FN={fn} TP={tp}")The counts it prints are:
| Threshold | TN | FP | FN | TP |
|---|---|---|---|---|
| 0.80 | 2 | 0 | 1 | 1 |
| 0.40 | 1 | 1 | 1 | 1 |
| 0.35 | 1 | 1 | 0 | 2 |
| 0.10 | 0 | 2 | 0 | 2 |
Three patterns appear in this table, and they hold for any dataset:
- Lowering the threshold never reduces the number of predicted positives. Every example predicted positive at a higher threshold is still positive at a lower one.
- TP and FP therefore never decrease as the threshold falls. FN and TN never increase.
- A single example moves at a time unless scores tie. Between 0.40 and 0.35, example C flips from predicted negative to predicted positive, turning one FN into one TP.
At the highest threshold you are almost certain to predict nothing positive, and at the lowest you predict everything positive. The matrices at these two extremes are the endpoints of the ROC curve.
The `>=` convention and ties
This tutorial predicts positive when score >= t, which is the convention scikit-learn uses for roc_curve thresholds. Some code uses a strict >. The two differ only for examples whose score equals the threshold exactly.
That difference matters most when scores are coarse. A decision tree with shallow depth outputs a handful of distinct probabilities, and many examples share each one. All tied examples cross the threshold together, so the matrix can jump by several counts at once. You cannot split a group of tied examples across the two predictions.
Common errors
- Thresholding hard labels.
model.predict(X)already applied a cutoff, usually 0.5 for probabilities. Sweeping thresholds over those 0s and 1s gives only one meaningful threshold. Usepredict_proba(X)[:, 1]ordecision_function(X). - Using the wrong probability column.
predict_probareturns one column per class, in the order ofmodel.classes_. Column 1 is the positive class only if the classes are[0, 1]. - Assuming scores are probabilities. Scores from
decision_functionor a margin-based model can be negative or exceed 1. A threshold of 0.5 means nothing there. Thresholds are on the scale of whatever score you pass in. - Mixing up rows and columns. See the warning above. When unsure, test on a case with an obvious answer, such as the four-example set here.
- Evaluating on training data. Counts from the data the model was fit on usually look better than they will on new data. Compute the matrix on held-out data.
What comes next
The four counts are the raw material. The next chapter divides TP and FP by the fixed row totals to get the true positive rate and the false positive rate. Each threshold then gives one point, and the set of points forms the ROC curve.
Exercise
A model gives scores [0.2, 0.6, 0.6, 0.9] for examples with true labels [0, 0, 1, 1]. Compute TN, FP, FN and TP at threshold 0.6 using the rule "positive when score >= t". Then compute them again using a strict ">" rule. Why do the two results differ?
Show answer
With ">=", the predictions are [0, 1, 1, 1], so TN = 1, FP = 1, FN = 0, TP = 2. With ">", the predictions are [0, 0, 0, 1], so TN = 2, FP = 0, FN = 1, TP = 1. They differ because two examples have a score exactly equal to 0.6 (one negative, one positive). The ">=" rule predicts both positive, and the ">" rule predicts both negative. The row totals are the same in both cases: TP + FN = 2 and FP + TN = 2.