Sub topic 12
Common pitfalls when reporting metrics
This chapter covers the mistakes that make a correct-looking metric misleading. It assumes you can compute accuracy, precision, recall, and F1 from a confusion matrix. It also assumes you know what a train/test split is and can read basic scikit-learn code. Every pitfall below is one where the arithmetic is right and the report is still wrong.
Evaluating on the wrong data
A metric measures how a model behaves on data it has not seen. If the evaluation data influenced the model in any way, the number is optimistic.
The most obvious case is scoring on the training set. A flexible model can memorize its training data:
from sklearn.datasets import make_classification
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = make_classification(
n_samples=1000, weights=[0.9, 0.1], random_state=0
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=0
)
model = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print(accuracy_score(y_train, model.predict(X_train))) # 1.0
print(accuracy_score(y_test, model.predict(X_test))) # lowerThe unpruned tree fits the training data perfectly, so the training score says nothing about generalization. Report the test score.
Leakage is subtler and more common. These are the usual sources:
- Tuning on the test set. If you try ten models or thresholds and keep the one with the best test score, the test set has become a training signal. Use a separate validation set (or cross-validation) for choices, and touch the test set once at the end.
- Preprocessing fitted on all data. Fitting a scaler or imputer on the full dataset before splitting lets test statistics leak into training. Fit on the training split only, or use a
Pipeline. - Duplicates across the split. Repeated rows, or several rows from the same customer or patient, can land on both sides. The model then gets credit for recognizing records it has already seen. Split by group when rows are not independent.
- Random splits on time-ordered data. If the model will predict the future, test on a later period than it trained on.
- Non-stratified splits on rare classes. A random split can leave very few positives in the test set. Pass
stratify=yso both splits keep the class ratio.
Undefined ratios and zero-division cases
Precision is TP / (TP + FP). If the model never predicts the positive class, the denominator is 0 and precision is undefined. Recall has the same problem when the test set contains no real positives, because TP + FN is 0.
scikit-learn does not guess silently. By default it returns 0.0 and emits an UndefinedMetricWarning. The zero_division argument lets you pick the value explicitly:
from sklearn.metrics import precision_score, recall_score
y_true = [0, 0, 1, 0]
y_pred = [0, 0, 0, 0] # the model never predicts the positive class
print(precision_score(y_true, y_pred, zero_division=0)) # 0.0
print(precision_score(y_true, y_pred, zero_division=1)) # 1.0
print(recall_score(y_true, y_pred)) # 0.0The two choices tell different stories. With zero_division=1, a model that never predicts a positive scores perfect precision, which is technically defensible (it made no wrong positive calls) and practically misleading. Pick a value deliberately, state it in the report, and do not let the warning scroll by unread.
An undefined metric is also a sign. If it appears, ask whether the model collapsed to a constant prediction or whether the test split lost a class.
Reporting a single number without a baseline
"Accuracy is 95%" means nothing until you know what a trivial model scores. On data that is 95% negative, predicting "negative" every time also gets 95%. Always report:
- The class distribution of the evaluation set.
- The score of a trivial baseline, such as always predicting the majority class.
- The full confusion matrix, or at least precision and recall for the positive class alongside accuracy.
A metric earns meaning by comparison, not by size.
Reporting a number without stating how it was computed
The same word can name different numbers. A report that says "recall: 0.62" is ambiguous in at least these ways:
- Which class is positive?
- Which averaging was used for a multiclass problem?
- Which threshold turned scores into labels?
- Which data was scored?
Swapped arguments
scikit-learn metrics take y_true first and y_pred second. Swapping them does not raise an error. Precision and recall exchange roles, because a false positive in one direction is a false negative in the other:
from sklearn.metrics import precision_score, recall_score
y_true = [1, 1, 1, 1, 0, 0]
y_pred = [1, 0, 0, 0, 0, 0]
print(precision_score(y_true, y_pred)) # 1.0
print(recall_score(y_true, y_pred)) # 0.25
print(precision_score(y_pred, y_true)) # 0.25 (swapped: this is really recall)If a precision value looks suspiciously close to a recall value you computed elsewhere, check the argument order first.
Which class is positive
For binary problems, scikit-learn assumes the positive label is 1. With string labels it raises a ValueError unless you say which one counts. Choosing the wrong positive class silently changes the meaning of every metric except accuracy:
from sklearn.metrics import precision_score
y_true = ["spam", "ham", "spam", "ham"]
y_pred = ["spam", "spam", "ham", "ham"]
print(precision_score(y_true, y_pred, pos_label="spam")) # 0.5
print(precision_score(y_true, y_pred, pos_label="ham")) # 0.5Both values match here only because the example is symmetric. On real data they differ, so name the positive class in the report.
Multiclass averaging
For more than two classes, the default average="binary" raises an error, and each other choice gives a different number. In the example below, the micro average equals accuracy, while macro and weighted averages differ from each other:
from sklearn.metrics import accuracy_score, precision_score
y_true = [0, 1, 2, 2, 2, 2]
y_pred = [0, 0, 2, 2, 1, 2]
print(round(accuracy_score(y_true, y_pred), 2)) # 0.67
print(round(precision_score(y_true, y_pred, average="micro"), 2)) # 0.67
print(round(precision_score(y_true, y_pred, average="macro"), 2)) # 0.5
print(round(precision_score(y_true, y_pred, average="weighted"), 2)) # 0.75Class 2 dominates with four of the six samples and is predicted perfectly, so the weighted average (0.75) looks far better than the macro average (0.5). Macro treats all classes equally, so the failures on the small classes show up. Micro pools all decisions, which for single-label problems makes it identical to accuracy. Report the averaging mode by name, and consider showing per-class scores with classification_report.
The threshold
Precision and recall depend on the decision threshold, which defaults to 0.5 for most probabilistic classifiers but is not special. If you report metrics at 0.5 and deploy at 0.3, the deployed behavior is not what you reported. State the threshold, and pick it on validation data rather than test data.
Ignoring uncertainty on small test sets
On a small test set, one prediction can move a metric a lot. With four real positives, recall can only take the values 0, 0.25, 0.5, 0.75, or 1. Differences between two models of a few points are then noise.
A bootstrap gives a rough interval. Resample the evaluation pairs with replacement many times, recompute the metric on each resample, and read off the middle 95%:
import random
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]
pairs = list(zip(y_true, y_pred))
rng = random.Random(0)
recalls = []
for _ in range(2000):
sample = rng.choices(pairs, k=len(pairs))
hits = [p for t, p in sample if t == 1]
if hits: # skip resamples with no real positives: recall is undefined
recalls.append(sum(hits) / len(hits))
recalls.sort()
low = recalls[int(0.025 * len(recalls))]
high = recalls[int(0.975 * len(recalls)) - 1]
print(low, high) # a wide interval around the point estimate of 0.75The interval is wide, even though the point estimate is 0.75. That width is the honest answer to "how good is this model?" on ten examples. The bootstrap is approximate, so treat it as a warning about how noisy the estimate is, not as an exact bound.
Optimizing one metric and ignoring the rest
Pushing one metric alone has predictable failures. Maximizing recall alone is trivial: predict positive for everything. Maximizing precision alone is also trivial: predict positive only for the single most confident case. F1 reduces the problem but treats precision and recall as equally important, which is rarely the real cost structure. Choose the primary metric from the costs of errors, as discussed earlier in this tutorial, and report the others as guardrails.
A reporting checklist
The table below summarizes the pitfalls and their fixes.
| Pitfall | Symptom | Fix |
|---|---|---|
| Scoring on training data | Near-perfect scores | Score on a held-out test set |
| Tuning on the test set | Test score higher than live performance | Use a validation set or cross-validation |
| Preprocessing leakage | Gap between test and live results | Fit transformers on training data only, use a `Pipeline` |
| Zero division | `UndefinedMetricWarning` | Set `zero_division` and check for a constant model |
| Swapped arguments | Precision equals a known recall | Use `(y_true, y_pred)` order |
| Wrong positive class | Metrics describe the opposite class | Set `pos_label` explicitly |
| Unstated averaging | Multiclass numbers not comparable | Name macro, micro, or weighted |
| No baseline | A big number with no context | Report the majority-class score |
| Small test set | Differences within noise | Bootstrap an interval or collect more data |
Exercise
A fraud model is evaluated on a test set of 2,000 transactions containing 8 frauds. Your report says "precision 0.88, recall 0.75, accuracy 99.6%". List three things a careful reader would still need to know before trusting these numbers.
Show answer
Possible answers include: (1) the baseline, since always predicting "not fraud" already gives 99.6% accuracy (1,992 of 2,000), so accuracy adds no information here; (2) the uncertainty, since recall 0.75 on 8 positives means 6 caught and a single change moves it by 12.5 points; (3) the threshold used, and whether it was chosen on validation data rather than this test set; (4) whether the split was stratified, grouped by customer, and free of preprocessing leakage.
Exercise
A colleague reports macro-averaged recall of 0.40 and weighted recall of 0.92 for a three-class model. What does the gap suggest, and what would you ask to see next?
Show answer
The weighted average follows the large classes and the macro average counts every class equally, so the gap suggests the model does well on a dominant class and poorly on at least one small class. Ask for per-class precision and recall, for example with classification_report, and for the class counts.
Exercise
You call precisionscore(ypred, y_true) by mistake on a binary problem. Which metric have you effectively computed, and why does no error appear?
Show answer
You have computed recall for the original labeling. Swapping the arguments exchanges false positives and false negatives, so TP / (TP + FP) becomes TP / (TP + FN). No error appears because both arguments are valid label lists, and scikit-learn cannot tell which one holds the ground truth.