Overfitting and underfitting
9 min read
A model that memorises
Suppose a model gets a task right on every training example. That sounds like success until you test it on examples it has never seen and it fails on a quarter of them. It learned the particular wording of the training data, including its accidents and wrong labels, and not the rule behind it.
Fine-tuning on small datasets is especially exposed. With a few hundred examples and a model with billions of weights, memorising is easy, and the training loss can reach almost zero.
See it in a small experiment
The program below makes 60 points on a line. The true rule is that a point is positive when it is above 0.5, and 15 percent of the labels are flipped to stand in for labelling mistakes. A memoriser predicts the label of the nearest training point. A simple rule uses one threshold. A constant always predicts the most common label. It scores all three on the training points and on 60 fresh points.
import random
random.seed(7)
def make(n):
points = []
for _ in range(n):
x = random.random()
label = x > 0.5
if random.random() < 0.15:
label = not label
points.append((x, label))
return points
train, validation = make(60), make(60)
def memoriser(x, data):
return min(data, key=lambda p: abs(p[0] - x))[1]
def threshold(x, data):
return x > 0.5
majority = sum(label for _, label in train) * 2 > len(train)
def constant(x, data):
return majority
def accuracy(model, data, reference):
return sum(model(x, reference) == label for x, label in data) / len(data)
for name, model in [("memoriser", memoriser), ("simple rule", threshold), ("constant", constant)]:
print(f"{name:12} train {accuracy(model, train, train):.0%} validation {accuracy(model, validation, train):.0%}")It prints:
memoriser train 100% validation 77%
simple rule train 87% validation 85%
constant train 55% validation 52%The memoriser scores 100% on the training points, because each point is its own nearest neighbour, and only 77% on the validation points, which is the honest number. The simple rule scores lower on training (87%) and higher on validation (85%), because it learned the pattern and ignored the noise. The constant scores 55% and 52%, which is underfitting: it has not learned anything about the input. These numbers come from one seed, so a different seed gives different values, but the memoriser's gap stays large.
The training score alone cannot tell these cases apart. The gap between training and validation does.
What the curves show
Reading a training run described the shapes. In short:
- Both scores poor. Underfitting. The model has not learned the task, the learning rate may be too low, or the data and labels may not contain a clear signal.
- Training good, validation much worse. Overfitting. The gap is the sign, and it often widens as training goes on.
- Both good and close. The model generalises.
Treat curves as evidence, and check data quality and the setup before naming a cause.
Fixes for overfitting
Stop earlier. Early stopping ends the run when the validation score has not improved for a set number of checks, and keeps the best checkpoint. Choose the measure and the patience before you compare runs.
Add varied data. More examples help when they cover cases the training set missed, and correctly labelled ones help most. Copies of the same examples add nothing new. Look at the validation errors first, and collect examples that match them. This is the loop in Error analysis and the next round.
Fewer epochs or a lower rate. Both limit how far the model drifts towards the training set.
Regularise. Weight decay pulls weights gently towards zero, and dropout randomly switches off part of the network during training. Both can reduce overfitting in some setups, and their values interact with the model and data, so compare candidates on the same validation set.
Train fewer weights. An adapter method such as LoRA, covered in Why train fewer parameters, has less room to memorise.
Fixes for underfitting
Raise the learning rate or train longer, check that labels and masks are right, use a larger model or a higher adapter rank, and make sure the examples contain enough signal. Print a batch and read the data, as Tokenisation for training advises, because a label or masking mistake looks exactly like underfitting.
| Training score | Validation score | First thing to try | |
|---|---|---|---|
| Underfitting | Poor | Poor | Check data and masks, raise the rate, train longer |
| Overfitting | Very good | Much lower | Stop earlier, add varied data, regularise |
| Good fit | Good | Close to training | Move on to the test set |
Which pair describes overfitting?
A model is tested on its training set and on new data.
The model memorised the training set rather than learning the general rule.
Which fix helps underfitting?
Both training and validation scores are poor.
The model has not learned enough. Give it more capacity or time.
What helps against overfitting?
The validation loss starts rising.
Stop at the best validation point and add variety to the data.
Your reading position is saved
0 of 36 complete
Lesson complete
Overfitting and underfitting
Up next