Sub topic 5
Choosing and Computing Metrics
This chapter assumes you know Python, train/validation/test splits, loss, and the Hugging Face Trainer API. The goal is to measure a classifier in a way that matches the real cost of its mistakes.
What a metric measures
A text classifier produces a predicted label. A metric compares that prediction with the correct label, called the reference or ground-truth label.
For binary classification, such as positive versus negative sentiment:
- A true positive is a positive example predicted as positive.
- A true negative is a negative example predicted as negative.
- A false positive is a negative example predicted as positive.
- A false negative is a positive example predicted as negative.
| Metric | Main question | Useful when |
|---|---|---|
| Accuracy | What fraction of all predictions is correct? | Classes have similar sizes |
| Precision | When the model predicts a class, how often is it right? | False positives are costly |
| Recall | Of the examples belonging to a class, how many did it find? | False negatives are costly |
| F1 | How well does precision balance with recall? | Both error types matter |
Accuracy is calculated as correct predictions divided by all predictions. It can hide poor performance on a rare class. For example, a model that always predicts the majority class can reach 95% accuracy on a dataset with 95% majority examples while completely failing on the minority class.
Choosing an average
For multiple classes, precision, recall, and F1 need an averaging rule.
- Macro averaging calculates a score for each class, then gives every class equal weight. Use it when minority-class performance matters.
- Weighted averaging weights each class by its number of examples. It reflects overall performance but can hide weak rare-class results.
- Micro averaging combines all decisions before calculating one score. It is often close to accuracy when every example has one label.
For a balanced sentiment dataset, accuracy and macro-F1 may tell similar stories. For an imbalanced dataset, report per-class results and macro-F1, and explain which errors matter operationally.
Computing metrics during training
The model returns one vector of logits, which are unnormalized scores for each class. argmax selects the class with the largest score. The Trainer passes these predictions and the reference labels to compute_metrics.
import numpy as np
import evaluate
accuracy = evaluate.load("accuracy")
precision = evaluate.load("precision")
recall = evaluate.load("recall")
f1 = evaluate.load("f1")
def compute_metrics(eval_pred):
logits, labels = eval_pred
predictions = np.argmax(logits, axis=-1)
return {
"accuracy": accuracy.compute(
predictions=predictions,
references=labels,
)["accuracy"],
"macro_precision": precision.compute(
predictions=predictions,
references=labels,
average="macro",
)["precision"],
"macro_recall": recall.compute(
predictions=predictions,
references=labels,
average="macro",
)["recall"],
"macro_f1": f1.compute(
predictions=predictions,
references=labels,
average="macro",
)["f1"],
}Pass this function to Trainer through compute_metrics=compute_metrics. During evaluation, the trainer logs these values for the validation set. Use the same label IDs throughout the dataset, model, and metric function. A mismatch can produce plausible-looking but meaningless scores.
Reading metric patterns
Metrics describe different failure patterns. Compare them instead of treating one number as the whole result.
High precision with low recall means the model is cautious. It predicts a class only when confident, so it misses many examples. High recall with low precision means it finds most examples but raises many false alarms. F1 falls when either value is low.
Evaluate the test set only after choosing the model and settings with validation data. Repeatedly checking the test score turns the test set into another validation set and makes the final estimate less trustworthy.
Exercise
A classifier has 95% accuracy, but macro-F1 is 0.52 on a dataset where 95% of examples belong to one class. What should you investigate first?
Show answer
Inspect per-class precision, recall, support, and the confusion matrix. The accuracy probably reflects majority-class predictions while the minority class is being missed.