With a good optimizer, a network can drive its training loss almost to zero. That power cuts both ways. A model that can fit anything can also fit the noise, and Part I showed where that leads. This chapter brings the lessons of the generalization and regularization chapters to neural networks, and adds one technique that is unique to them.
A network that memorises
Give a network far more capacity than its data needs. Here are just 45 points on three spiral arms, and a network with 64 hidden neurons: 387 learnable numbers for 45 examples.
A network with 387 weights is trained on only 45 points. Its training loss falls all the way through. What will the loss on new points from the same spirals do?
Forty-five points, 387 weights
- Loss on the 45 training points
- Loss on 450 new points
- Right on training points
- 33%
- Right on new points
- 38%
- Loss on new points
- 1.10
- Steps
- 0
The dark curve falls steadily toward zero, and the network ends up getting 96% of its training points right. The orange curve tells the real story. It falls for the first 50 steps or so, then turns and climbs for the rest of training. On new points the network gets 66%.
This is
A price on large weights
The first remedy is one you already know.
loss = how badly it fits the data + λ × the sum of all squared weights
In the backward pass this adds to each weight’s gradient: a steady pull toward zero, proportional to the weight’s size. A weight grows only if the data keeps pushing it harder than the penalty pulls it back. Sharp, twisted boundaries need large weights, so they become expensive.
Smaller weights, smoother regions
- Loss on the 45 training points
- Loss on 450 new points
- Right on training points
- 33%
- Right on new points
- 38%
- Loss on new points
- 1.10
- Steps
- 0
| Weight penalty λ | Right on training points | Right on new points | Loss on new points |
|---|---|---|---|
| off | 96% | 66% | 2.85 |
| 0.001 | 96% | 77% | 1.37 |
| 0.003 | 96% | 75% | 1.23 |
| 0.1 | 58% | 47% | 1.02 |
A modest penalty raises accuracy on new points from 66% to 77% without costing anything on the training points. The regions become broader and smoother, following the arms instead of the dots. Push the penalty too far and the weights cannot grow enough to bend the boundary at all: at 0.1 the network underfits both sets.
Dropout
The second remedy has no counterpart in Part I. It is called
A different network at every step
- Hidden neurons switched off
- 4 of 16
- Survivors are multiplied by
- 1.43
- Training steps drawn
- 1
Why would damaging the network help it? Because of what the network has to do to cope. If any neuron might vanish on the next step, no neuron can afford to depend on one particular partner, and no single neuron can be the only one that knows something important. Useful knowledge has to be spread across many neurons, each of which works reasonably on its own. Narrow, fragile arrangements that happened to fit a few training points do not survive.
Two details make it work in practice.
- The survivors are scaled up. If 30% of a layer is switched off, the remaining values are multiplied by , so the total signal reaching the next layer stays about the same.
- Dropout is for training only. When the network is used to make predictions, every neuron is on and nothing is scaled. The network that answers is the full one.
A network is trained with 50% dropout on a hidden layer. What happens in that layer when the finished network makes a prediction?
Dropout on the spiral
Here is the same over-sized network, with dropout applied to its hidden layer.
Training with neurons missing
- Loss on the 45 training points
- Loss on 450 new points
- Right on training points
- 33%
- Right on new points
- 38%
- Loss on new points
- 1.10
- Steps
- 0
With 30% dropout, accuracy on new points rises from 66% to 73%, and the loss on them falls from 2.85 to 1.20. Accuracy on the training points drops to 89%: the network is no longer able to memorise them, which is the point. At 50% or more it struggles to learn the shape at all.
A caution about how far to trust this. The experiment was repeated on 27 different small spiral datasets. Both remedies lowered the loss on new points in every one. The weight penalty also raised accuracy in 21 of them. Dropout raised accuracy in only 8. On a network this small, with so little data, dropout is the less reliable of the two. It earns its reputation on large networks with many layers, where there is much more for it to spread out.
Knowing when to stop
Look again at the first figure of this chapter. The loss on new points was lowest early in training and got worse from then on. The network at step 50 was, in that sense, better than the finished one.
The best network was an early one
- Loss on the 45 training points
- Loss on 450 new points
- Lowest loss on new points
- Right on training points
- 33%
- Right on new points
- 38%
- Loss on new points
- 1.10
- It was lowest at step
- –
It costs nothing and it is almost always worth doing. One rule matters: the data used to decide when to stop has now influenced the model, so it counts as a validation set. A final, untouched test set is still needed for the honest number at the end.
Underneath all three remedies is the oldest one: more data. Overfitting is a mismatch between how flexible a model is and how much evidence it has. The same network trained on 300 points, as in the last two chapters, reached 95% on new ones with no remedy at all.
During training, the loss on the training set keeps falling while the loss on the validation set has been rising for 200 steps. What is happening, and what should you do?
In code
The dense layer gains an optional penalty, and dropout is a new layer with a training switch. The full file is code/ch19_regularization.py (run it in Colab).
class Layer_Dense:
def backward(self, dvalues):
self.dweights = self.inputs.T @ dvalues
self.dbiases = np.sum(dvalues, axis=0, keepdims=True)
if self.weight_regularizer_l2 > 0:
self.dweights += 2 * self.weight_regularizer_l2 * self.weights # pull toward zero
self.dinputs = dvalues @ self.weights.T
class Layer_Dropout:
def __init__(self, rate, rng):
self.keep = 1 - rate
self.rng = rng
def forward(self, inputs, training):
if not training:
self.output = inputs # prediction: every neuron takes part
return
# Dividing by the keep rate leaves the expected total unchanged.
self.mask = self.rng.binomial(1, self.keep, size=inputs.shape) / self.keep
self.output = inputs * self.mask
def backward(self, dvalues):
self.dinputs = dvalues * self.mask # dropped neurons get no gradient
Run on its own random set of 45 points, the Python version scores 72% on new points with no remedy, 77% with a weight penalty of 0.001, and 73% with 30% dropout.
Key Takeaways
- A large network on little data memorises: training loss falls while the loss on new data rises.
- A weight penalty pulls every weight toward zero, so sharp, fragile boundaries become expensive.
- Dropout switches off random neurons during training, forcing knowledge to be spread out. It is off at prediction time.
- Early stopping keeps the weights from the point where held-out loss was lowest.
- Every remedy has a “too much” that underfits, and none beats more data.
- Spot a memorising network from its two loss curves.
- Add a weight penalty to a network and say what it does to the gradients.
- Explain how dropout works, and why outputs are scaled up during training.
- Use held-out loss to decide when to stop training.
Exercises
Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.
A layer outputs . Dropout at a rate of 50% happens to switch off the second and third neurons. What does the layer pass on, after scaling? Compare the average before and after.
Hint
The values that are kept are divided by the share that is kept.
Solution
The kept values are divided by the share that is kept, 0.5, which doubles them. The layer passes on .
The average before was . The average after is also .
That is the purpose of the scaling. The next layer learned its weights while seeing inputs of a certain typical size. Without scaling, its inputs would be twice as large at prediction time, when nothing is dropped, as they were in training.
A layer has the weights and a penalty strength of . What does the penalty add to the loss? What does it add to the gradient of each weight?
Hint
The penalty is λ times the sum of the squared weights. Its gradient for each weight is .
Solution
The penalty is times the sum of squared weights: .
It adds to each gradient: , and .
Gradient descent subtracts the gradient, so the weight of 3 is pulled down, the weight of −4 is pulled up, and both move towards zero. The pull is proportional to the size of the weight: the large weights feel it most and the small one hardly at all.
During training, the loss on held-out data at the end of each epoch is 0.90, 0.61, 0.48, 0.45, 0.47, 0.52 and 0.60. The training loss falls throughout. Which epoch’s weights should you keep? Why should you not stop the moment the held-out loss first rises?
Hint
Find the epoch with the lowest held-out loss. Then think about how noisy that number is.
Solution
Keep the weights from epoch 4, where the held-out loss was lowest at 0.45. After that the network keeps improving on its training data and gets worse on everything else.
Held-out loss is noisy, and it often wobbles upward for an epoch before continuing down. Stopping at the first rise would end many runs too early. The usual approach is to save the weights every time a new best is reached and stop only after several epochs in a row without one. That number of epochs is called the patience.
A network is right about 96% of its training examples and 70% of new ones. List four things you could try, starting with the one most likely to help.
Hint
The cause is too little data for the size of the network. Which remedy goes at the cause most directly?
Solution
- Get more training data. It attacks the cause directly: with more examples there is less room to memorise. Nothing else works as well when it is possible.
- Add a weight penalty or dropout. Both make memorising harder without changing the size of the network.
- Stop earlier. Keep the weights from the epoch where held-out loss was lowest.
- Use a smaller network. Fewer neurons or layers leave less capacity to fit noise.
In practice people combine several of these. Whatever you try, choose its strength using held-out data and not the test set.
In the figure “Smaller weights, smoother regions”, train with λ off, with λ = 0.001 and with λ = 0.1. Compare the shapes of the regions and the accuracy on new points with the table in the chapter. What has gone wrong at 0.1?
Hint
Look at the accuracy on the training points as well as on the new ones.
Solution
With the penalty off the regions have sharp, narrow fingers reaching for individual training points, and accuracy on new points is 66%. At λ = 0.001 the fingers are gone, the regions are smoother, and accuracy on new points rises to 77%, with training accuracy still at 96%.
At λ = 0.1 the network is right about only 58% of its own training points and 47% of new ones. The penalty is now so strong that keeping the weights small matters more than fitting the data, and the regions are nearly featureless. The cure for overfitting has become underfitting.
Going further
Penalising absolute values
The lasso penalty from Part I, the sum of absolute weights, also works on networks. It drives many weights to exactly zero, which can make a network smaller, but it is used less often than the squared penalty because it tends to hurt accuracy more for the same amount of regularization.
More data without collecting any
For images, new training examples can be manufactured from old ones: flip a picture, shift it a few pixels, change its brightness. The label stays the same and the network sees a slightly different input every time. This is called data augmentation, and for image models it is often the most effective regularizer of all.
References and further reading
- H. Kinsley and D. Kukieła, Neural Networks from Scratch in Python, chapters 14 and 15, nnfs.io.
- N. Srivastava, G. Hinton, A. Krizhevsky, I. Sutskever and R. Salakhutdinov, Dropout: a simple way to prevent neural networks from overfitting, Journal of Machine Learning Research, 2014.
- S. J. D. Prince, Understanding Deep Learning, chapter 9. Free at udlbook.github.io/udlbook.