Sub topic 10
Computing the metrics with scikit-learn
This chapter assumes you know basic Python, what a labeled binary classification problem is, and how the confusion matrix, accuracy, precision, recall, and F1 are defined. Earlier chapters computed these by hand. Here you will get the same numbers from scikit-learn and use the manual counts to check them.
The working model
Every function in sklearn.metrics used here takes two sequences of the same length: the true labels first, then the predictions. Each function compares them and returns a number or a matrix.
The order matters. Accuracy gives the same result either way, but precision and recall swap places if you reverse the arguments. Always write y_true first.
Reproducing the manual results
The data below is the same ten-example set from the hand calculation. The manual counts were TP=3, FP=1, TN=5, FN=1.
from sklearn.metrics import (
accuracy_score,
confusion_matrix,
f1_score,
precision_score,
recall_score,
)
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]
print(confusion_matrix(y_true, y_pred)) # [[5 1] [1 3]]
print(accuracy_score(y_true, y_pred)) # 0.8
print(precision_score(y_true, y_pred)) # 0.75
print(recall_score(y_true, y_pred)) # 0.75
print(f1_score(y_true, y_pred)) # 0.75All four scores match the manual formulas. That agreement is a useful habit: when you compute a metric by hand once and by library once, a mismatch usually points to swapped arguments or a wrong label.
Reading the confusion matrix
confusion_matrix returns a 2D array. Rows are the true classes and columns are the predicted classes, both in sorted label order (0, then 1).
| Row | Predicted 0 | Predicted 1 |
|---|---|---|
| **True 0** | TN = 5 | FP = 1 |
| **True 1** | FN = 1 | TP = 3 |
This layout is the opposite of what many textbooks draw, which often put the positive class first. To avoid misreading it, unpack the four cells by name:
from sklearn.metrics import confusion_matrix
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
print(tn, fp, fn, tp) # 5 1 1 3ravel() flattens the matrix row by row, so the order is TN, FP, FN, TP. This only works for binary problems where both classes appear. If y_true and y_pred contain a single class, the matrix is 1x1 and the unpacking fails. Passing labels=[0, 1] forces a 2x2 matrix.
Choosing the positive class
Precision, recall, and F1 treat label 1 as the positive class by default. If your positive class is something else, such as the string "fraud", set pos_label.
from sklearn.metrics import recall_score
y_true = ["fraud", "ok", "ok", "fraud", "ok"]
y_pred = ["fraud", "ok", "fraud", "ok", "ok"]
print(recall_score(y_true, y_pred, pos_label="fraud")) # 0.5Here one of the two real fraud cases was found, so recall is 0.5. Without pos_label, scikit-learn raises an error because the labels are strings and it cannot guess which one is positive.
Zero-division cases
Precision is tp / (tp + fp). If the model never predicts the positive class, the denominator is zero. By default scikit-learn returns 0.0 and prints a warning. You can set the value explicitly with zero_division.
from sklearn.metrics import precision_score, recall_score
y_true = [0, 0, 1]
y_pred = [0, 0, 0] # never predicts the positive class
print(precision_score(y_true, y_pred, zero_division=0)) # 0.0
print(recall_score(y_true, y_pred)) # 0.0Choose the value deliberately. Reporting 0.0 is the cautious choice. Reporting 1.0 can make a model that never predicts anything look perfect.
Common errors
- Swapped arguments.
precision_score(y_pred, y_true)returns the recall you wanted, and the reverse. Keepy_truefirst. - Scores instead of labels. These functions expect hard labels (0 or 1). If you pass probabilities such as 0.83, scikit-learn raises an error about mixing binary and continuous targets. Apply a threshold first, as in the threshold chapter:
[int(s >= 0.5) for s in scores]. - Wrong positive class. On string labels or a positive class other than 1, set
pos_label. - Scoring on training data. Compute metrics on the held-out test set. Scores from the training set flatter the model.
Exercise
You run precision_score(y_pred, y_true) with the ten-example data above, with the arguments reversed. What value do you get, and why?
Show answer
You get 0.75, the model's actual recall. Reversing the arguments makes the predictions act as the "truth", so the false positives become false negatives and the recall formula is computed under the name precision. Here precision and recall are both 0.75, so the mistake hides itself. On data where they differ, the numbers would be swapped.
Exercise
Given y_true = [1, 1, 0, 0] and y_pred = [1, 0, 0, 0], which confusion_matrix(y_true, y_pred).ravel() result is correct: (2, 0, 1, 1) or (1, 1, 0, 2)?
Show answer
(2, 0, 1, 1). The order is tn, fp, fn, tp. There are 2 true negatives, no false positives, 1 false negative (the second example), and 1 true positive.