Papa Programmer
Lesson 19 of 36

Overfitting and underfitting

9 min read

Optional

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.

python
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:

text
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 scoreValidation scoreFirst thing to try
UnderfittingPoorPoorCheck data and masks, raise the rate, train longer
OverfittingVery goodMuch lowerStop earlier, add varied data, regularise
Good fitGoodClose to trainingMove on to the test set
Which problem do you have
Read the gapThe distance between training and validation scores shows overfitting.
Test on unseen dataA model that memorised scores perfectly on the data it has seen.
Add varied examplesNew cases that match the errors help more than copies of old ones.

Your reading position is saved

0%

0 of 36 complete

Contents

Learning tools