Sub topic 9
Measuring Performance: Precision, Recall, F1, and the Confusion Matrix
This chapter assumes that you understand training and test sets, scikit-learn pipelines, TF-IDF features, and basic Python. You should also know that a classifier predicts a label for each document.
A test score is useful only when you know what it measures. Accuracy alone can hide serious errors, especially when one class is much larger than the others. Precision, recall, F1, and the confusion matrix give a more detailed view.
Start with held-out data
Evaluate the final model on data that was not used during training. This is called held-out data. The model must not use the test documents to build its vocabulary, calculate IDF values, or choose hyperparameters.
The basic workflow is:
- Fit the pipeline on training documents.
- Predict labels for test documents.
- Compare predictions with the known test labels.
- Calculate several metrics.
Precision and recall
For one class, imagine that the classifier marks documents as belonging to sci.space.
- A true positive is a space document correctly labeled as space.
- A false positive is a non-space document incorrectly labeled as space.
- A false negative is a space document incorrectly assigned another label.
- A true negative is a non-space document correctly rejected as space.
Precision answers: “When the model predicts this class, how often is it correct?”
Precision = true positives / (true positives + false positives)
High precision means that the model produces few false alarms.
Recall answers: “Of all documents that really belong to this class, how many did the model find?”
Recall = true positives / (true positives + false negatives)
High recall means that the model misses few relevant documents.
A model can have high precision but low recall. For example, it might predict sci.space only when it sees very strong evidence. Those predictions may be correct, but the model may miss many space documents.
F1 and averaging across classes
The F1 score combines precision and recall using their harmonic mean:
F1 = 2 × precision × recall / (precision + recall)
The harmonic mean gives a low score when either precision or recall is low. It is useful when you need a balance between false positives and false negatives.
In a multiclass problem, scikit-learn reports a score for each class. It also provides averages:
| Average | Meaning |
|---|---|
| Macro average | The unweighted mean across classes. Each class matters equally. |
| Weighted average | The mean across classes weighted by each class's support. Larger classes matter more. |
| Micro average | Counts all decisions together before calculating the metric. |
Support is the number of true test examples in a class. Use macro F1 when minority classes matter as much as majority classes. Weighted F1 may look strong even when a small class performs poorly.
The confusion matrix
A confusion matrix is a table that counts true labels against predicted labels. In scikit-learn, rows represent true labels and columns represent predicted labels.
The diagonal contains correct predictions. Off-diagonal cells show which classes the model confuses. For example, many rec.autos documents predicted as sci.space may indicate overlapping vocabulary or weak training data.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
classification_report,
confusion_matrix,
ConfusionMatrixDisplay,
)
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
docs = [
"the spacecraft entered orbit around the planet",
"astronomers observed a bright distant galaxy",
"the rocket launched a satellite into space",
"NASA planned a mission to study Mars",
"the telescope detected a new star",
"the car engine needs an oil change",
"the sedan has excellent fuel economy",
"the mechanic replaced the brake pads",
"the tires have good traction on wet roads",
"the driver compared two sports cars",
"the government introduced a new tax policy",
"the election debate focused on education",
"the senator proposed changes to the law",
"voters discussed the national budget",
"the parliament passed a public policy bill",
]
labels = [
"sci.space", "sci.space", "sci.space", "sci.space", "sci.space",
"rec.autos", "rec.autos", "rec.autos", "rec.autos", "rec.autos",
"talk.politics", "talk.politics", "talk.politics",
"talk.politics", "talk.politics",
]
X_train, X_test, y_train, y_test = train_test_split(
docs, labels, test_size=0.4, random_state=7, stratify=labels
)
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2)),
LogisticRegression(max_iter=1000),
)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(classification_report(y_test, predictions, zero_division=0))
labels_in_order = ["rec.autos", "sci.space", "talk.politics"]
matrix = confusion_matrix(
y_test, predictions, labels=labels_in_order
)
print(matrix)
display = ConfusionMatrixDisplay(
confusion_matrix=matrix,
display_labels=labels_in_order,
)
display.plot()classification_report prints precision, recall, F1, and support for every class. Always inspect support before comparing scores. A class with two test examples gives a much less stable estimate than a class with hundreds.
Exercise
Exercise
A classifier has precision 0.90 and recall 0.40 for a class. What does this tell you?
Show answer
Its predictions for that class are usually correct, but it finds only a small portion of the documents that truly belong to the class. The model has high precision and low recall.