Sub topic 3
Spotting overfitting and picking a checkpoint
This chapter assumes you have run the Trainer from the previous chapter, know the train, validation, and test splits, and can read accuracy and macro F1. Overfitting means the model memorizes training examples and scores worse on new text.
Watch the validation F1 after each epoch. It usually rises, peaks, and then falls while training loss keeps dropping. Keep the checkpoint at the peak. The earlier setup does this with load_best_model_at_end=True and metric_for_best_model="f1".
Predicting on new text
A pipeline wraps the tokenizer and model in one call. It returns a label and a score for each input.
from transformers import pipeline
classifier = pipeline("text-classification", model="distilbert-base-uncased")
print(classifier("The plot dragged, but the lead actor was superb."))Replace the model name with your saved folder when you have one. The score is the model's confidence, not a calibrated probability.
Dealing with imbalanced classes
If one label is rare, accuracy can look high while the rare class fails. Check per-class recall and macro F1. You can weight the loss toward the rare class or move the decision threshold, and tune either choice on the validation set only.
Reading the model's mistakes
Collect validation examples where the prediction differs from the label. Group them by pattern, such as sarcasm, very short reviews, or long reviews. Truncation at 256 tokens is a common cause: a long review loses its ending, and the ending often carries the verdict.
Fine-tuning with LoRA
LoRA (low-rank adaptation) freezes the pretrained weights and trains small added matrices. It suits tight GPU memory or many task-specific adapters on one base model. Full fine-tuning often gives slightly higher accuracy on a single task.
from peft import LoraConfig, TaskType, get_peft_model
from transformers import AutoModelForSequenceClassification
base = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased", num_labels=2)
config = LoraConfig(task_type=TaskType.SEQ_CLS, r=8, lora_alpha=16,
lora_dropout=0.1, target_modules=["q_lin", "v_lin"])
model = get_peft_model(base, config)
model.print_trainable_parameters()Saving and reusing the model
trainer.save_model writes the weights and config, and tokenizer.save_pretrained writes the tokenizer. Keep both in one folder so the pipeline can load them. A LoRA save stores only the adapter, so you must load the same base model before attaching it.
Exercise
Validation F1 peaks at epoch 2 and falls at epoch 3 while training loss keeps dropping. Which checkpoint should you keep, and why?
Show answer
Keep the epoch 2 checkpoint. It has the best validation F1, and the later epochs show overfitting: the model fits training examples better but generalizes worse.