Sub topic 2
Choosing and Computing Metrics
This chapter assumes you have tokenized train_ds and val_ds from the previous step, you know what a training and validation set are, and you understand that a loss measures how wrong a model is.
Choosing and computing metrics
Accuracy is the share of correct predictions. It is simple, but it misleads when one label is rare. If 90% of reviews are positive, a model that always says "positive" scores 90% accuracy. Macro F1 computes the F1 score for each class and averages them equally, so a model that ignores the rare class scores poorly.
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"),
}The Trainer calls this function after each evaluation with the raw logits and true labels. It must return a dictionary of named numbers.
Training with the Trainer API
The Trainer handles batching, the training loop, evaluation, and checkpointing. You configure it with TrainingArguments.
from transformers import (
AutoModelForSequenceClassification,
DataCollatorWithPadding,
Trainer,
TrainingArguments,
)
model = AutoModelForSequenceClassification.from_pretrained(
"distilbert-base-uncased", num_labels=2
)
args = TrainingArguments(
output_dir="imdb-distilbert",
learning_rate=2e-5,
per_device_train_batch_size=16,
per_device_eval_batch_size=32,
num_train_epochs=3,
weight_decay=0.01,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="f1",
)
trainer = Trainer(
model=model,
args=args,
train_dataset=train_ds,
eval_dataset=val_ds,
data_collator=DataCollatorWithPadding(tokenizer),
compute_metrics=compute_metrics,
)
trainer.train()Tuning the main hyperparameters
The learning rate sets the step size of each update. A value that is too high makes the loss jump or diverge. A value that is too low learns slowly. Batch size trades memory for update stability. Epochs set how many passes the model makes over the training data. Weight decay penalizes large weights to reduce overfitting. Change one setting at a time and compare validation F1, not training loss.
| Setting | Typical start | If too high | If too low |
|---|---|---|---|
| learning_rate | 2e-5 | Loss diverges | Slow learning |
| per_device_train_batch_size | 16 | Out of memory | Noisy updates |
| num_train_epochs | 2 to 4 | Overfitting | Underfitting |
| weight_decay | 0.01 | Weak regularization | Overly constrained weights |
Exercise
Exercise
Your dataset is 90% positive, and a model always predicts positive. Roughly what are its accuracy and macro F1?
Show answer
Accuracy is about 0.90. The positive class has precision 0.90 and recall 1.0, so its F1 is about 0.95. The negative class has F1 0. Macro F1 is the average, about 0.47.