Sub topic 5
Choosing and computing metrics
This chapter assumes you can run the tokenization and Trainer code from earlier chapters. It also assumes you know what logits are, and that you know the difference between a training set and a validation set. The goal is to pick metrics that match your label distribution and compute them during training, so that load_best_model_at_end selects the checkpoint you actually want.
Why the metric is a design decision
The Trainer always reports a loss. Loss is useful for the optimizer, but it is hard to read. A validation loss of 0.31 does not tell you how many reviews you misclassify, or which kind of error you make.
A metric turns predictions into a number a person can reason about. The choice matters for two reasons:
- It defines what "better" means when you compare runs.
- It decides which checkpoint is kept when you set
metric_for_best_model.
A metric that hides a failure will let you ship a model that fails.
The confusion matrix is the source of every metric
For a binary task, each prediction falls into one of four cells. Call one class "positive". Here positive means a positive review.
| Row | Predicted positive | Predicted negative |
|---|---|---|
| Actually positive | True positive (TP) | False negative (FN) |
| Actually negative | False positive (FP) | True negative (TN) |
All the metrics below are ratios of these four counts.
- Accuracy is (TP + TN) / all examples. It is the fraction of correct predictions.
- Precision is TP / (TP + FP). Of everything the model called positive, how much really was.
- Recall is TP / (TP + FN). Of everything that really was positive, how much the model found.
- F1 is the harmonic mean of precision and recall: 2PR / (P + R). It is low if either one is low.
When accuracy misleads
Accuracy works when classes are roughly balanced and every error costs the same. IMDB is balanced, so accuracy is a fair headline number there.
Suppose instead that 2 percent of support tickets are urgent. A model that always predicts "not urgent" scores 98 percent accuracy and finds no urgent tickets. Its recall on the urgent class is 0.
The fix is to look at per-class numbers. Precision and recall for the rare class show what accuracy hides. The next sections describe how to combine per-class numbers into a single score.
Averaging F1 across classes
With more than one class, F1 is computed per class and then averaged. The averaging mode changes the result.
| Average | How it works | Use it when |
|---|---|---|
| `binary` | F1 of the one class you name as positive | You care about one class, such as "urgent" |
| `macro` | Unweighted mean of per-class F1 | Every class matters equally, including rare ones |
| `weighted` | Mean of per-class F1, weighted by class size | You want a score that follows the data distribution |
| `micro` | Pools all TP, FP, FN across classes | You want one global count. For single-label tasks it equals accuracy |
Macro F1 is a good default for model selection on imbalanced data, because a collapse on a small class pulls the score down. The chapter's example uses average="macro" for that reason.
Note that the evaluate library's f1 metric defaults to average="binary" with pos_label=1. If you forget to set average on a multi-class task, it raises an error. On a binary task it silently reports F1 for label 1 only. Always pass average explicitly.
Computing metrics inside the Trainer
The Trainer calls your compute_metrics function after each evaluation. It passes an EvalPrediction, which unpacks into two NumPy arrays: the logits with shape (n_examples, n_labels) and the integer labels with shape (n_examples,).
Your function does three things:
- Turn logits into predicted class ids with
argmax. - Compare predictions to labels.
- Return a dictionary of named floats.
import numpy as np
import evaluate
accuracy = evaluate.load("accuracy")
f1 = evaluate.load("f1")
def compute_metrics(eval_pred):
logits, labels = eval_pred
preds = np.argmax(logits, axis=-1)
return {
**accuracy.compute(predictions=preds, references=labels),
**f1.compute(predictions=preds, references=labels, average="macro"),
}Each compute call returns a dictionary such as {"accuracy": 0.91}, and the ** unpacking merges them. The Trainer prefixes every key with eval_. Your "f1" key therefore appears as eval_f1 in logs, and metric_for_best_model="f1" finds it because the Trainer adds the prefix when it looks the name up.
Add precision and recall
You can get per-class and aggregate precision and recall the same way:
import numpy as np
import evaluate
precision = evaluate.load("precision")
recall = evaluate.load("recall")
accuracy = evaluate.load("accuracy")
f1 = evaluate.load("f1")
def compute_metrics(eval_pred):
logits, labels = eval_pred
preds = np.argmax(logits, axis=-1)
out = {}
out.update(accuracy.compute(predictions=preds, references=labels))
out.update(precision.compute(predictions=preds, references=labels, average="macro"))
out.update(recall.compute(predictions=preds, references=labels, average="macro"))
out.update(f1.compute(predictions=preds, references=labels, average="macro"))
return outThe evaluate library loads metric scripts from the Hub the first time, so the first call needs network access. The precision, recall and f1 metrics depend on scikit-learn, so install it with pip install scikit-learn.
Selecting the best checkpoint by metric
Two TrainingArguments settings link metrics to checkpoint selection:
metric_for_best_model="f1"names the metric to rank checkpoints by.greater_is_bettertells theTrainerwhich direction is better. When you name a metric that does not end inloss, it defaults toTrue. If you use"loss", it defaults toFalse.
Evaluation and saving must happen on the same schedule. With load_best_model_at_end=True, eval_strategy and save_strategy must match, for example both "epoch". If they differ, TrainingArguments raises an error.
Metrics that need probabilities
Accuracy and F1 use the hard class decision. Sometimes you need to judge the model's ranking or confidence instead. Two common cases:
- ROC AUC measures how well the positive-class score separates the two classes across every threshold. It is useful when you will choose the threshold later.
- Log loss penalizes confident wrong answers. It checks whether the probabilities are well calibrated.
For these, convert logits to probabilities with softmax before you compute the metric. This version uses scipy, which installs with scikit-learn:
import numpy as np
import evaluate
from scipy.special import softmax
roc_auc = evaluate.load("roc_auc")
def compute_auc(eval_pred):
logits, labels = eval_pred
probs = softmax(logits, axis=-1)[:, 1]
return roc_auc.compute(prediction_scores=probs, references=labels)roc_auc takes prediction_scores, not predictions. Passing the wrong keyword is a common source of errors. This function works for two classes. For more classes you pass the full probability matrix and set multi_class.
Choosing a metric for your task
Start from the cost of each error, not from the metric name.
| Situation | Suggested primary metric | Reason |
|---|---|---|
| Balanced classes, equal error costs | Accuracy, plus macro F1 | Simple and honest |
| Imbalanced classes, all classes matter | Macro F1 | Rare classes count equally |
| Missing a positive is costly (fraud, safety) | Recall on the positive class, with precision tracked | Prioritizes finding positives |
| False alarms are costly (auto-moderation) | Precision on the positive class | Prioritizes being right when acting |
| Threshold chosen after training | ROC AUC or precision-recall curves | Independent of one cutoff |
Report more than one metric even when you select on one. Seeing accuracy, precision and recall together shows which direction an improvement came from.
Common errors
- Passing probabilities where labels are expected.
f1.computeneeds integer class ids. Applyargmaxfirst. - Wrong label order. If your labels are not
0..n-1, orid2labeldisagrees with the dataset, per-class scores attach to the wrong names. - Forgetting
average. Described above. Always set it. - Tuple logits. Some models return a tuple, so
logitscan arrive as a tuple whose first element holds the logits. DistilBERT sequence classification returns a plain array, but a custom head may not. Handle it withif isinstance(logits, tuple): logits = logits[0]. - Selecting on loss while reporting F1. The lowest validation loss and the highest F1 often come from different epochs. Decide which one you care about, and set
metric_for_best_modelto match it. - A noisy small validation set. With 200 validation examples, one example is 0.5 points of accuracy. Differences smaller than that between runs are not meaningful. Use a larger split, or repeat runs with different seeds.
Checking your metric code without training
You can test compute_metrics with hand-made inputs before spending GPU time. Build an EvalPrediction-like pair and check a case you can verify by hand:
import numpy as np
logits = np.array([[2.0, 0.1], [0.2, 1.5], [1.0, 0.9], [0.1, 3.0]])
labels = np.array([0, 1, 1, 1])
print(compute_metrics((logits, labels)))The predictions are [0, 1, 0, 1]. Three of four are correct, so accuracy is 0.75. Class 0 has precision 0.5 and recall 1.0, giving F1 of about 0.667. Class 1 has precision 1.0 and recall 0.667, giving F1 of 0.8. Macro F1 is the mean, about 0.733. If your function prints different numbers, the bug is in the metric code, not the model.
Exercise
A fraud dataset is 99 percent legitimate and 1 percent fraud. Your model predicts "legitimate" for every example. What are its accuracy and its recall on the fraud class, and which average setting and metric_for_best_model would you choose so that checkpoint selection does not reward this behavior?
Show answer
Accuracy is 0.99 and fraud recall is 0, because the model finds no fraud. Use macro F1 (average="macro", with metric_for_best_model="f1") so the near-zero F1 on the fraud class drags the score down. Recall or F1 on the fraud class alone (average="binary" with pos_label=1) is also reasonable if missing fraud is the costly error.
Exercise
Your compute_metrics returns the key "f1", and you set metric_for_best_model="f1". In the training logs, under what name does the metric appear, and why does the lookup still work?
Show answer
It appears as eval_f1. The Trainer adds the eval_ prefix to every key your function returns, and it also adds the prefix to the name in metric_for_best_model when it looks the value up.