Overfitting
Learning versus memorising.
Imagine a student who memorises last year's exam answers. They score perfectly on that exam. But give them new questions, and they fail. Models can do the same thing. It's called overfitting.
- Memorising last year's answers
- Perfect on old questions
- Fails on new ones
Two loss curves
Here's how to spot it. We track two losses during training. The training loss, on examples the model learns from. And the validation loss, on examples it never trains on. At first, both go down. The model is learning. Then the validation loss stops falling, and starts rising, while training loss keeps dropping. That's overfitting. The best moment to stop is at the bottom of the validation curve.
Overfitting on purpose
Let's cause some overfitting on purpose. We train on only twenty examples, for eight epochs, with a higher learning rate. Then we print both losses, for every epoch. Run it. The training loss drops fast, to below zero point seven. But the validation loss falls only slowly, and stays above one point three. That growing gap is the warning sign. The model is memorising twenty examples, not learning the task.
from train import trainer
trainer.train_dataset = trainer.train_dataset.shuffle(seed=0).select(range(20))
trainer.args.num_train_epochs = 8
trainer.args.learning_rate = 1e-4
trainer.train()
train = [l["loss"] for l in trainer.state.log_history if "loss" in l]
evals = [l["eval_loss"] for l in trainer.state.log_history if "eval_loss" in l]
for epoch, (t, e) in enumerate(zip(train, evals), 1):
print(f"epoch {epoch}: train loss {t:.3f} eval loss {e:.3f}")epoch 1: train loss 1.608 eval loss 1.583 epoch 2: train loss 1.430 eval loss 1.554 epoch 3: train loss 1.295 eval loss 1.509 epoch 4: train loss 1.059 eval loss 1.446 epoch 5: train loss 0.914 eval loss 1.400 epoch 6: train loss 0.698 eval loss 1.363 epoch 7: train loss 0.718 eval loss 1.340 epoch 8: train loss 0.682 eval loss 1.329
Also uses prep.py
from datasets import load_dataset
from transformers import AutoTokenizer
INTENTS = ["order_status", "return", "price", "stock", "complaint"]
label2id = {name: i for i, name in enumerate(INTENTS)}
id2label = {i: name for i, name in enumerate(INTENTS)}
MODEL = "distilbert/distilbert-base-uncased"
tok = AutoTokenizer.from_pretrained(MODEL)
def prepare(row):
enc = tok(row["message"], truncation=True, max_length=32)
enc["label"] = label2id[row["intent"]]
return enc
data = load_dataset("json", data_files={"train": "tickets_train.jsonl",
"test": "tickets_test.jsonl"})
data = data.map(prepare, remove_columns=["message", "intent", "book"])Also uses train.py
import numpy as np
from transformers import (AutoModelForSequenceClassification, DataCollatorWithPadding,
Trainer, TrainingArguments)
from prep import tok, data, MODEL, label2id, id2label
model = AutoModelForSequenceClassification.from_pretrained(
MODEL, num_labels=5, id2label=id2label, label2id=label2id)
args = TrainingArguments(output_dir="intent-model", num_train_epochs=2,
per_device_train_batch_size=16, learning_rate=5e-5,
eval_strategy="epoch", logging_strategy="epoch",
save_strategy="no", report_to="none")
def accuracy(pred):
return {"accuracy": (np.argmax(pred.predictions, -1) == pred.label_ids).mean()}
trainer = Trainer(model=model, args=args, train_dataset=data["train"],
eval_dataset=data["test"], data_collator=DataCollatorWithPadding(tok),
compute_metrics=accuracy)How to fight overfitting
Here's how to fight it. Get more, and more varied, data. That's the best fix. Train for fewer epochs. Use a smaller learning rate. And always watch the validation loss, and keep the model from the best epoch. With LoRA, there's one more trick. Training fewer parameters already makes overfitting less likely.
| Fix | Why it helps |
|---|---|
| More varied data | less to memorise |
| Fewer epochs | stop before it memorises |
| Smaller learning rate | gentler changes |
| Watch validation loss | keep the best epoch |
| LoRA | fewer weights to overfit |
Summary
Let's recap. Overfitting means memorising, instead of learning. Watch for a growing gap between training and validation loss. And fix it with more data, fewer epochs, and a smaller learning rate. Next, saving our model.
Key takeaways- Memorising ≠ learning
- Watch the gap
- More data, fewer epochs