Sub topic 10
Computing the Metrics with scikit-learn
Earlier chapters computed accuracy, precision, recall, and F1 by hand from the four confusion matrix counts. This chapter shows how to get the same numbers from sklearn.metrics, how to read what the functions return, and where their defaults can mislead you.
This chapter assumes you know basic Python, how a binary classifier produces labels, how a train/test split works, and the formulas for the four metrics. It also assumes scikit-learn is installed.
The shape of the API
Every function in sklearn.metrics that we use here takes the true labels first and the predicted labels second:
metric(y_true, y_pred)Each function returns a plain number, except confusion_matrix, which returns a NumPy array, and classification_report, which returns text.
The metric functions do not call confusion_matrix internally in a way you can observe. The diagram shows the conceptual dependency, not the code path.
Reproducing the manual results
Use the same ten labels as the hand calculation. The results should match: accuracy 0.8, precision 0.75, recall 0.75, F1 0.75.
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.75If a scikit-learn number disagrees with your manual count, one of the two is wrong. Check the manual count first. A mismatch is a useful test of your understanding of the formulas.
Reading the confusion matrix
confusion_matrix returns a 2-by-2 array. Rows are the true classes and columns are the predicted classes, both in sorted label order. For labels 0 and 1, the layout is:
| Row | Predicted 0 | Predicted 1 |
|---|---|---|
| **True 0** | TN | FP |
| **True 1** | FN | TP |
The positive class sits in the bottom-right cell only because 1 sorts after 0. Many textbooks draw the positive class in the top-left, so do not assume a layout from a picture. Read it from the row and column order.
The usual way to extract the four counts is ravel(), which flattens the array row by row:
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 3Notice the order: tn, fp, fn, tp. It differs from the tp, fp, tn, fn order used in the manual code. Unpacking in the wrong order silently gives wrong metrics.
from sklearn.metrics import confusion_matrix
y_true = [0, 0, 0]
y_pred = [0, 0, 0]
print(confusion_matrix(y_true, y_pred)) # [[3]]
print(confusion_matrix(y_true, y_pred, labels=[0, 1])) # [[3 0] [0 0]]Accuracy as a count
accuracy_score returns a fraction by default. Pass normalize=False to get the number of correct predictions instead:
from sklearn.metrics import accuracy_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(accuracy_score(y_true, y_pred)) # 0.8
print(accuracy_score(y_true, y_pred, normalize=False)) # 8The count is tp + tn, which is 3 + 5 here. It is handy for checking the matrix: the sum of the diagonal equals the count.
Choosing the positive class with pos_label
Precision, recall, and F1 depend on which class you call positive. By default, scikit-learn treats the label 1 as positive. If your labels are strings, or the class you care about is 0, you must say so with pos_label.
from sklearn.metrics import confusion_matrix, precision_score, recall_score
y_true = ["spam", "ham", "spam", "spam", "ham"]
y_pred = ["spam", "spam", "ham", "spam", "ham"]
print(precision_score(y_true, y_pred, pos_label="spam")) # 0.6666666666666666
print(recall_score(y_true, y_pred, pos_label="spam")) # 0.6666666666666666
print(precision_score(y_true, y_pred, pos_label="ham")) # 0.5
print(confusion_matrix(y_true, y_pred, labels=["spam", "ham"]))
# [[2 1]
# [1 1]]Omitting pos_label here raises a ValueError, because 1 is not one of the labels. That error is helpful. The dangerous case is a dataset where the labels are 0 and 1 and your target class is 0. The call succeeds and reports metrics for the wrong class.
Passing labels=["spam", "ham"] to confusion_matrix puts the positive class first, so the matrix reads with TP in the top-left. This is a display choice. It does not change the metrics.
The classification report
classification_report prints precision, recall, F1, and support (the number of true examples) for every class, plus overall rows:
from sklearn.metrics import classification_report
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(classification_report(y_true, y_pred)) precision recall f1-score support
0 0.83 0.83 0.83 6
1 0.75 0.75 0.75 4
accuracy 0.80 10
macro avg 0.79 0.79 0.79 10
weighted avg 0.80 0.80 0.80 10The row labeled 1 matches the binary results above. The row labeled 0 treats class 0 as positive: its recall of 0.83 is 5 of 6 true negatives found. The macro and weighted rows combine the per-class scores. The chapter on multiclass problems explains how those averages differ. For binary work, read the row for your positive class.
For use in code rather than for reading, pass output_dict=True to get a dictionary:
report = classification_report(y_true, y_pred, output_dict=True)
print(report["1"]["recall"]) # 0.75The class keys are strings, even when the labels are integers.
Argument order matters
All of these functions accept two lists of the same length, so swapping them raises no error. Swapping changes the result for precision and recall, because the two metrics trade roles when the arguments are reversed.
from sklearn.metrics import 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(precision_score(y_true, y_pred)) # 0.75
print(recall_score(y_pred, y_true)) # 0.75, which is really precisionHere both values are 0.75 because precision and recall happen to be equal in this example. On most data they differ, and the swapped call returns the other metric under the wrong name. Accuracy and F1 are symmetric, so they hide the mistake. Always write (y_true, y_pred) and check it in code review.
Zero-division cases
Precision is tp / (tp + fp). If the model predicts no positives, the denominator is 0. Recall has the same problem when y_true has no positives. scikit-learn does not crash. It returns 0.0 and emits an UndefinedMetricWarning. The zero_division parameter controls both behaviors:
from sklearn.metrics import precision_score
y_true = [1, 1, 0, 0]
y_pred = [0, 0, 0, 0] # the model never predicts positive
print(precision_score(y_true, y_pred, zero_division=0)) # 0.0
print(precision_score(y_true, y_pred, zero_division=1)) # 1.0Setting zero_division=0 returns 0.0 and silences the warning. Setting it to 1 returns 1.0, which is the "no false alarms" reading. Pick one deliberately and report it. A model that predicts nothing and scores 1.0 precision looks perfect on that one number, which is why precision should always be read next to recall.
Sweeping the threshold with scikit-learn
Many classifiers produce a score or probability, and your code turns it into a label with a threshold. The metric functions only see the labels, so you compute them once per threshold. This repeats the earlier threshold example with the library functions:
from sklearn.metrics import precision_score, recall_score
y_true = [1, 1, 1, 0, 0, 0, 0, 0]
scores = [0.9, 0.6, 0.4, 0.7, 0.3, 0.2, 0.1, 0.05]
for threshold in (0.3, 0.5, 0.8):
y_pred = [int(s >= threshold) for s in scores]
p = precision_score(y_true, y_pred, zero_division=0)
r = recall_score(y_true, y_pred)
print(threshold, round(p, 2), round(r, 2))
# 0.3 0.6 1.0
# 0.5 0.67 0.67
# 0.8 1.0 0.33Raising the threshold makes the model predict positive less often. Precision rises and recall falls. The zero_division=0 guard matters here, because a very high threshold can leave no positive predictions at all.
Evaluating a real model on test data
In practice the predictions come from a fitted model on held-out data. The pattern is always the same: fit on the training split, predict on the test split, and compare against the test labels.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_samples=1000,
n_features=10,
weights=[0.9, 0.1], # about 10% positives
random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(classification_report(y_test, y_pred))Two choices in this code matter. stratify=y keeps the share of positives the same in both splits, which prevents a test set with too few positives to measure recall. The metrics use y_test and model.predict(X_test), never the training data, since a model scores optimistically on examples it has already seen.
model.predict applies a threshold of 0.5 for logistic regression. To use another threshold, call model.predict_proba(X_test)[:, 1] to get the positive-class probabilities and compare them yourself, as in the sweep above. The values printed by the report depend on the library version, so run the code and read your own output.
Scoring during cross-validation
The same metrics are available by name for model selection. Pass scoring to cross_val_score:
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
X, y = make_classification(
n_samples=1000, n_features=10, weights=[0.9, 0.1], random_state=0
)
model = LogisticRegression(max_iter=1000)
for name in ("accuracy", "precision", "recall", "f1"):
scores = cross_val_score(model, X, y, cv=5, scoring=name)
print(name, scores.mean().round(3))The strings "accuracy", "precision", "recall", and "f1" all assume the positive class is 1. For string labels, build a scorer with make_scorer(precision_score, pos_label="spam") instead. Choose the scoring name that matches the cost of errors you decided on earlier. A search that optimizes accuracy on imbalanced data will favor the model that ignores the rare class.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Swapping `y_true` and `y_pred` | Precision and recall trade places | Always write `(y_true, y_pred)` |
| Wrong `pos_label` | Metrics describe the wrong class | Set `pos_label` explicitly when the target is not 1 |
| Unpacking `ravel()` in the wrong order | Wrong TP, FP, TN, FN | Use `tn, fp, fn, tp` |
| Scoring on training data | Inflated results | Score on a held-out test set |
| Ignoring zero-division warnings | A silent 0.0 hides a degenerate model | Set `zero_division` and check recall too |
Exercise
A binary classifier is evaluated with y_true = [1, 1, 0, 0, 0, 0] and y_pred = [1, 0, 0, 1, 0, 0]. Using scikit-learn's convention, what does confusion_matrix(y_true, y_pred) return, and what are precision and recall for class 1?
Show answer
Class 0 has four true examples: three predicted 0 and one predicted 1. Class 1 has two true examples: one predicted 1 and one predicted 0. The matrix is [[3 1] [1 1]], so TN=3, FP=1, FN=1, TP=1. Precision is 1/(1+1) = 0.5 and recall is 1/(1+1) = 0.5.
Exercise
You call precision_score(y_true, y_pred) on string labels "yes" and "no", and scikit-learn raises a ValueError. What is the cause, and what is the fix?
Show answer
The default pos_label is 1, which is not one of the labels. The fix is to name the positive class explicitly, for example precision_score(y_true, y_pred, pos_label="yes").