A model overfits when it fits the training data better than the patterns in that data justify. It learns details that are specific to the training examples, so its performance on new data is worse than its performance on the data it was trained on. This article shows how to see overfitting in the training and validation curves, what dropout, weight decay and early stopping do in PyTorch, and how much each of them changed the result in a measured experiment.
The setup
The experiment uses the 8x8 digits dataset from scikit-learn: 1,797 grayscale images of the digits 0 to 9, each flattened to 64 values. 797 images are kept aside as the validation set and are never trained on. The model is trained on only 100 images, which is small enough to overfit easily.
import torch import torch.nn as nn from sklearn.datasets import load_digits d = load_digits() X = torch.tensor(d.data, dtype=torch.float32) / 16.0 # pixels 0..16 -> 0..1 Y = torch.tensor(d.target) perm = torch.randperm(len(X), generator=torch.Generator().manual_seed(0)) X, Y = X[perm], Y[perm] x_train, y_train = X[:100], Y[:100] # 100 training images x_val, y_val = X[1000:], Y[1000:] # 797 validation images model = nn.Sequential( nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 10), ) opt = torch.optim.Adam(model.parameters(), lr=1e-3) loss_fn = nn.CrossEntropyLoss() The model has 50,826 parameters and the training set has 100 examples, so the model has far more capacity than it needs to memorize every training image. It is trained for 300 epochs with mini-batches of 32. After each epoch, the loss and accuracy are measured on both sets in eval mode under torch.no_grad().
Reading the curves
epoch 25 train loss 0.194 val loss 0.534 train acc 0.980 val acc 0.841 epoch 50 train loss 0.032 val loss 0.442 train acc 1.000 val acc 0.872 epoch 75 train loss 0.011 val loss 0.440 train acc 1.000 val acc 0.876 epoch 100 train loss 0.006 val loss 0.447 train acc 1.000 val acc 0.877 epoch 150 train loss 0.002 val loss 0.463 train acc 1.000 val acc 0.882 epoch 200 train loss 0.001 val loss 0.477 train acc 1.000 val acc 0.887 epoch 250 train loss 0.001 val loss 0.489 train acc 1.000 val acc 0.885 epoch 300 train loss 0.001 val loss 0.499 train acc 1.000 val acc 0.886 The training loss falls to 0.001 and the training accuracy reaches 100% by epoch 50. The validation loss reaches its lowest value, 0.438, at epoch 64, and then rises for the remaining 236 epochs. From epoch 64 on, the model is still improving on the training set and getting worse on the validation set. That divergence is overfitting.
Comparing the two curves gives three patterns:
| Training loss | Validation loss | Diagnosis | What to change |
|---|---|---|---|
| high, flat | high, flat | underfitting: the model cannot fit even the training data | more capacity (wider or deeper layers), more epochs, a higher learning rate |
| falling | falling, close to training | the model is learning | keep training |
| falling | rising, or flat far above training | overfitting | regularization, more data, a smaller model, early stopping |
Validation loss rises while validation accuracy does not fall
In the run above, the validation loss rose from 0.438 to 0.499, but the validation accuracy did not drop. It stayed between 0.875 and 0.887. The two measure different things. Accuracy counts how many predictions have the correct class as the largest output. Cross-entropy loss also measures how much probability the model gives to the correct class. As the model keeps fitting the 100 training images, its outputs become more confident on every input, including the validation images it gets wrong. A wrong prediction made with higher confidence has a larger loss, so the validation loss rises even when the number of wrong predictions stays the same.
For this reason, the validation loss is the curve to watch for overfitting and to use for early stopping. It shows the problem earlier than accuracy does.
Dropout
nn.Dropout(p) sets each element of its input to zero with probability p during training, and multiplies the remaining elements by 1 / (1 - p). In eval mode it returns its input unchanged:
torch.manual_seed(1) drop = nn.Dropout(0.5) x = torch.ones(10) drop.train(); print(drop(x)) drop.eval(); print(drop(x)) tensor([2., 2., 2., 2., 0., 2., 2., 0., 0., 2.]) tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) With p=0.5, the kept values are multiplied by 2. On a tensor of one million ones, 50.09% of the values were zeroed and the mean of the output was 0.9982. The scaling keeps the average size of the activations the same in training and in eval mode, so the next layer receives inputs of the same scale in both modes. This is also why model.eval() must be called before evaluation: in train mode, every forward pass drops a different random set of values.
Because a different random set of neurons is removed at every step, no neuron can rely on one specific other neuron being present. The network has to spread what it learns over many neurons, which makes it harder to memorize individual training examples.
Dropout goes after the activation of a hidden layer, and not after the output layer:
model = nn.Sequential( nn.Linear(64, 256), nn.ReLU(), nn.Dropout(0.3), nn.Linear(256, 128), nn.ReLU(), nn.Dropout(0.3), nn.Linear(128, 10), # no dropout on the output ) Typical values are 0.1 to 0.5. A dropout on the output layer would zero some of the logits that the loss function receives, which removes classes from the prediction at random.
Weight decay
Weight decay pulls every weight towards zero at each step. It is set with the weight_decay argument of the optimizer. What exactly it does depends on the optimizer, and the difference between Adam and AdamW matters.
To see the difference, this example takes one parameter tensor, sets the same gradient on it, and performs one step with lr=0.1 and weight_decay=0.01:
lr, wd = 0.1, 0.01 p0 = torch.tensor([2.0, -1.0, 0.5]) grad = torch.tensor([0.3, 0.3, 0.3]) def one_step(opt_cls): p = nn.Parameter(p0.clone()) opt = opt_cls([p], lr=lr, weight_decay=wd) p.grad = grad.clone() opt.step() return p.detach() SGD. SGD adds weight_decay * p to the gradient. For plain SGD this is the same as shrinking the weight by the factor (1 - lr * weight_decay) and then applying the normal update:
SGD step: tensor([ 1.9680, -1.0290, 0.4695]) by hand p*(1-lr*wd) - lr*g: tensor([ 1.9680, -1.0290, 0.4695]) Adam. Adam also adds weight_decay * p to the gradient. But Adam then divides each gradient by a running estimate of its own size. The decay term is divided by the same amount as the gradient, so it no longer acts as a fixed shrinking of the weight:
Adam step, weight_decay=0.01: tensor([ 1.9000, -1.1000, 0.4000]) Adam step, weight_decay=0: tensor([ 1.9000, -1.1000, 0.4000]) On the first step the two results are identical. Adam's first step moves every weight by about lr in the direction of the sign of its gradient, and adding 0.01 * p to a gradient of 0.3 does not change its sign. On later steps the decay term does change the update, but its effect is scaled differently for every weight. This form of weight decay is called L2 regularization.
AdamW. AdamW applies the decay separately from the gradient. It first multiplies every weight by (1 - lr * weight_decay) and then applies the normal Adam update computed from the gradient alone:
AdamW step: tensor([ 1.8980, -1.0990, 0.3995]) by hand p*(1-lr*wd), then Adam on grad: tensor([ 1.8980, -1.0990, 0.3995]) This is called decoupled weight decay. Every weight is shrunk by the same fraction, regardless of the size of its gradient. For training with Adam, use torch.optim.AdamW when weight decay is wanted:
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01) In the measurements below, Adam(weight_decay=0.01) reduced the validation accuracy from 0.888 to 0.853, while AdamW(weight_decay=0.01) left it at 0.888. Note that AdamW has a default of weight_decay=0.01, while Adam defaults to 0.
Early stopping
Early stopping ends training when the validation loss has not improved for a number of epochs, and keeps the model from the epoch with the lowest validation loss. The number of epochs to wait is called the patience.
import copy best_val, best_state, wait, patience = float("inf"), None, 0, 10 for epoch in range(1, 301): train_one_epoch(model, opt) # the usual training loop val_loss = validate(model) # eval mode + no_grad if val_loss < best_val: best_val, wait = val_loss, 0 best_state = copy.deepcopy(model.state_dict()) else: wait += 1 if wait >= patience: print(f"stopped at epoch {epoch}") break model.load_state_dict(best_state) copy.deepcopy is required when the best weights are kept in memory. model.state_dict() returns references to the model's live tensors, so without a copy best_state would change with every later training step and end up holding the final weights. Saving with torch.save(model.state_dict(), "best.pt") instead writes a copy to disk and does not need deepcopy.
On the 100-image setup with patience=10:
seed 0: stopped at epoch 74, best epoch 64, best model val loss 0.438, val acc 0.875 seed 1: stopped at epoch 74, best epoch 64, best model val loss 0.406, val acc 0.878 seed 2: stopped at epoch 83, best epoch 73, best model val loss 0.459, val acc 0.873 Training stopped after 74 to 83 epochs instead of 300, and the model that was kept is the one with the lowest validation loss. A patience that is too small stops on random noise in the validation loss. A patience that is too large trains for many epochs past the best one. Values of 5 to 10 epochs are common, and larger values are used when the validation loss is noisy.
Comparing the techniques
Each setup below was trained for 300 epochs on the same 100 images, three times with different seeds, and the numbers are averages over the three runs, measured at the last epoch:
setup train acc val acc gap val loss no regularization 1.000 0.888 0.112 0.492 Dropout(0.3) 1.000 0.880 0.120 0.550 Dropout(0.5) 1.000 0.878 0.122 0.549 Adam weight_decay=0.01 1.000 0.853 0.147 0.493 AdamW weight_decay=0.01 1.000 0.888 0.112 0.487 AdamW weight_decay=0.1 1.000 0.890 0.110 0.450 smaller model 64->32->10 1.000 0.875 0.125 0.417 Dropout(0.3) + AdamW weight_decay=0.01 1.000 0.878 0.122 0.546 more data: 1000 images, no reg. 1.000 0.972 0.028 0.142 On this dataset:
- Every setup trained on 100 images reached 100% training accuracy. None of the regularization techniques prevented the model from fitting all 100 images.
- Dropout and weight decay changed the validation accuracy by at most about one percentage point. The stronger
AdamW(weight_decay=0.1)and the smaller model gave lower validation losses (0.450 and 0.417) than no regularization (0.492). - Dropout raised the validation loss slightly, and so did the combination of dropout with weight decay. Techniques do not always add up.
-
Adam(weight_decay=0.01)lowered the validation accuracy to 0.853, for the reason shown in the weight decay section. - Training on 1,000 images instead of 100, with no regularization at all, raised the validation accuracy from 0.888 to 0.972 and reduced the gap from 0.112 to 0.028.
The effect of a regularization technique depends on the data, the model and the strength setting, so it has to be measured on the validation set rather than assumed. More training data was by far the largest improvement here. With 100 examples there is little information to learn from, and regularization cannot add information that the data does not contain. Data augmentation is the way to get more variety from the same images: random crops, small rotations or colour changes applied in the training transforms, so the model sees a slightly different version of each image every epoch. An augmentation should not change the correct label. A horizontal flip is fine for photos of cats, but not for digits or letters, where a mirrored character is no longer the same character.
Summary
| Technique | PyTorch code | What it does |
|---|---|---|
| Detect overfitting | log train and val loss every epoch | training loss falls while validation loss rises |
| Dropout | nn.Dropout(0.1 to 0.5) after hidden activations | zeroes random activations in training, does nothing in eval mode |
| Weight decay with Adam | torch.optim.AdamW(..., weight_decay=0.01) | multiplies every weight by (1 - lr * wd) each step |
| Weight decay with SGD | torch.optim.SGD(..., weight_decay=1e-4) | same shrinking, added through the gradient |
| Early stopping | patience counter on val loss + copy.deepcopy(model.state_dict()) | keeps the weights from the best epoch |
| Smaller model | fewer or narrower layers | less capacity to memorize |
| More data / augmentation | more examples, or random transforms in training | more variety to learn from |
- Overfitting shows as a training loss that keeps falling while the validation loss rises. Watch the validation loss, not only the accuracy: it can rise while the accuracy stays the same.
-
nn.Dropoutscales the kept values by1 / (1 - p)in training and is the identity in eval mode. Put it after hidden activations, never on the output. -
Adam(weight_decay=...)adds the decay to the gradient, where Adam's scaling changes its effect.AdamWshrinks the weights directly. UseAdamWfor weight decay with Adam. - Early stopping keeps the best epoch's weights. Copy the
state_dictwithcopy.deepcopy, or save it to disk. - Measure each technique on the validation set. In this experiment, ten times more data improved validation accuracy far more than any regularization setting.
This is one chapter's worth of an idea from my book, PyTorch From Ground Up, which builds everything from tensors upward so nothing stays vague. If it helped: 8 chapters are free, no email required, there's a free one-page tensor cheat-sheet here, every example runs in the companion notebooks on GitHub, and the full book is on Leanpub or in paperback and Kindle on Amazon.
Video version: the same material is taught on my YouTube channel, Deep Clarity. The beginner course PyTorch From Ground Up gets a new episode every day, two puzzles from each episode are solved as Shorts, and a separate playlist has short explanations of ML concepts.
More in this series
How Training Actually Works:
- PyTorch Autograd Explained: What
.backward()Actually Does - Backpropagation by Hand: Two Layers, a Pen, and Then Autograd Agrees
- What
optimizer.step()Actually Does: SGD, Momentum and Adam by Hand - What Your Loss Function Actually Tells the Model
- nn.Module Explained: The Same Model Built with Raw Tensors and with nn.Module
- model.train() vs model.eval() vs torch.no_grad() in PyTorch
- Saving and Loading Models in PyTorch: state_dict, Checkpoints and Resuming Training
- Moving a PyTorch Model to the GPU: device, .to() and the Same-Device Error
Shape mechanics:
- Reshape vs View in PyTorch
- PyTorch Broadcasting Explained
- What Does
unsqueezeDo in PyTorch? - What Does
keepdimDo in PyTorch? - PyTorch
permutevstranspose
Next in this series: metrics that matter, beyond accuracy.