Sub topic 9
Measuring performance: precision, recall, F1, confusion matrix
A trained pipeline always returns predictions, so a model that runs says nothing about whether it works. This chapter covers how to measure a text classifier honestly and how to read the numbers that scikit-learn reports.
It assumes you can build the TfidfVectorizer and LogisticRegression pipeline from the previous chapter. It also assumes you know why a model is scored on data it did not train on.
Why accuracy alone is not enough
Accuracy is the fraction of documents whose predicted label equals the true label. It is easy to compute and easy to misread, for two reasons:
- With uneven classes, a model can score high by always predicting the majority class. If 95% of emails are not spam, a model that never flags spam is 95% accurate and useless.
- Accuracy hides which kinds of mistakes the model makes. Missing a spam message and flagging a real message as spam have very different costs.
The metrics below separate these error types. They all derive from four counts, defined for one class at a time, which we call the positive class:
- True positives (TP): documents of the class that the model labeled as that class.
- False positives (FP): documents of other classes that the model labeled as this class.
- False negatives (FN): documents of the class that the model labeled as something else.
- True negatives (TN): all remaining documents.
Precision, recall, and F1
Precision answers: of the documents the model assigned to this class, how many really belong to it?
precision = TP / (TP + FP)Recall answers: of the documents that really belong to this class, how many did the model find?
recall = TP / (TP + FN)F1 is the harmonic mean of the two:
F1 = 2 * precision * recall / (precision + recall) = 2TP / (2TP + FP + FN)The harmonic mean is dominated by the smaller value. A model with precision 1.0 and recall 0.1 gets F1 of about 0.18, not the 0.55 an ordinary average would give. F1 is high only when both numbers are reasonably high.
A worked example: a classifier labels 50 documents as "sci.space". Of those, 40 are correct (TP = 40) and 10 are not (FP = 10). The test set holds 60 real "sci.space" documents, so 20 were missed (FN = 20).
- Precision = 40 / 50 = 0.80
- Recall = 40 / 60 = 0.667
- F1 = 80 / (80 + 10 + 20) = 0.727
The confusion matrix
A confusion matrix is a table with one row per true class and one column per predicted class. Cell (i, j) counts documents whose true class is i and whose predicted class is j. Correct predictions sit on the diagonal, and every off-diagonal cell is a specific kind of mistake.
For class k, the matrix gives you the four counts directly:
- TP is the diagonal cell (k, k).
- FN is the rest of row k.
- FP is the rest of column k.
This is why recall uses row sums and precision uses column sums. Reading the matrix tells you which classes the model confuses, and that information guides what to fix.
Computing the metrics in scikit-learn
The code below trains the pipeline from the previous chapter and prints the confusion matrix. It also recomputes precision and recall from that matrix by hand, so you can check them against the library.
import numpy as np
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.pipeline import make_pipeline
categories = ["sci.space", "rec.autos", "talk.politics.misc"]
remove = ("headers", "footers", "quotes")
train = fetch_20newsgroups(subset="train", categories=categories, remove=remove)
test = fetch_20newsgroups(subset="test", categories=categories, remove=remove)
model = make_pipeline(
TfidfVectorizer(sublinear_tf=True, ngram_range=(1, 2), min_df=2, stop_words="english"),
LogisticRegression(C=1.0, max_iter=1000),
)
model.fit(train.data, train.target)
pred = model.predict(test.data)
print("accuracy:", round(accuracy_score(test.target, pred), 3))
cm = confusion_matrix(test.target, pred)
print(test.target_names)
print(cm)
tp = np.diag(cm)
precision = tp / cm.sum(axis=0) # column sums: everything predicted as the class
recall = tp / cm.sum(axis=1) # row sums: everything that truly is the class
print("precision:", precision.round(3))
print("recall: ", recall.round(3))
print(classification_report(test.target, pred, target_names=test.target_names))The by-hand precision and recall arrays should match the first two columns of classification_report. The report's support column is the row total, which is the number of true documents per class in the test set.
Class order is the same everywhere: confusion_matrix sorts labels, and test.target_names follows the integer labels. If your labels are strings, pass labels=[...] to confusion_matrix to fix the order explicitly.
Averaging across classes
With more than two classes, you get one precision, recall, and F1 per class. To summarize them in a single number you must choose an averaging method:
| Average | How it is computed | Behavior |
|---|---|---|
| macro | Unweighted mean of the per-class scores | Every class counts equally, so weak small classes pull the score down |
| weighted | Mean of the per-class scores, weighted by support | Large classes dominate |
| micro | Pools TP, FP, and FN across all classes before computing | For single-label problems, equals accuracy |
Use macro F1 when rare classes matter as much as common ones. Use weighted F1 when you want a summary that reflects the real class mix. You can request each one with precision_recall_fscore_support:
from sklearn.metrics import precision_recall_fscore_support
for avg in ["macro", "weighted", "micro"]:
p, r, f, _ = precision_recall_fscore_support(test.target, pred, average=avg)
print(avg, round(p, 3), round(r, 3), round(f, 3))For multi-class, single-label data, micro precision, recall, and F1 are all identical to accuracy. This is expected and not a bug.
Moving the decision threshold
predict picks the class with the highest probability. For a two-class problem, that amounts to a 0.5 threshold on predict_proba. You can move that threshold to trade precision for recall without retraining. The sketch below treats "sci.space" as the positive class and the other two as negative:
from sklearn.metrics import precision_recall_curve
space = list(test.target_names).index("sci.space")
scores = model.predict_proba(test.data)[:, space]
y_true = (test.target == space).astype(int)
precisions, recalls, thresholds = precision_recall_curve(y_true, scores)
for t in [0.3, 0.5, 0.7]:
i = np.searchsorted(thresholds, t)
print(f"threshold {t}: precision {precisions[i]:.3f}, recall {recalls[i]:.3f}")Raising the threshold generally increases precision and lowers recall. Choose the operating point from the costs of your errors, and choose it on validation data, never on the test set.
Common mistakes
- Scoring on training data. A high-dimensional TF-IDF model with many n-grams can nearly memorize its training set, so training scores look excellent and mean little.
- Fitting the vectorizer on all the text before splitting. The vocabulary and IDF values then carry information from the test documents. The Pipeline avoids this by fitting the vectorizer on training text only.
- Leaky text. In 20 Newsgroups, headers, footers, and quoted replies reveal the newsgroup directly. That is why the code removes them. Without
remove, scores jump, but the model is learning metadata, not content. Check for similar shortcuts in your own data, such as signatures, source tags, or boilerplate. - Reporting one number. A single accuracy or macro F1 hides per-class behavior. Always look at the per-class report and the confusion matrix too.
- Ignoring duplicates. Near-duplicate documents on both sides of a split inflate scores. Deduplicate before splitting if your corpus is scraped.
- Trusting a small test set. A class with 30 test documents gives a noisy recall estimate, since one document changes it by more than 3 points. Look at
supportbefore comparing models that differ by a point or two.
Choosing a metric
- Balanced classes and equal error costs: accuracy and macro F1 both work.
- Rare classes that matter: macro F1, plus per-class recall.
- Missing a positive is costly, such as flagging abuse: focus on recall, and lower the threshold.
- A false alarm is costly, such as auto-deleting messages: focus on precision, and raise the threshold.
- Several models to compare on one number: pick one averaged metric before looking at results, and use it for tuning as well. The tuning chapter uses
scoring="f1_macro"for this reason.
Exercise
A classifier labels 40 documents as "urgent". Of those, 30 are truly urgent. The test set contains 35 urgent documents in total. Compute precision, recall, and F1 for the "urgent" class.
Show answer
TP = 30. FP = 40 - 30 = 10. FN = 35 - 30 = 5. Precision = 30/40 = 0.75. Recall = 30/35 = 0.857. F1 = 230 / (230 + 10 + 5) = 60/75 = 0.80.
Exercise
A three-class test set has 900 documents of class A, 80 of class B, and 20 of class C. A model gets 95% of A right, 50% of B, and 10% of C. Is accuracy or macro recall the better summary if class C matters, and why?
Show answer
Macro recall is better. Accuracy is (855 + 40 + 2) / 1000 = 0.897, which is dominated by class A and hides the weak result on C. Macro recall is (0.95 + 0.50 + 0.10) / 3 = 0.517, which gives class C the same weight as A and exposes the problem.
Exercise
In a confusion matrix with rows as true classes and columns as predicted classes, which part of the matrix do you sum to get the false positives for class k, and which to get the false negatives?
Show answer
False positives for class k are the off-diagonal cells in column k, since those are documents of other classes predicted as k. False negatives are the off-diagonal cells in row k, since those are documents of class k predicted as something else.