# Chapter 19: Keeping Networks Honest

> Weight penalties and dropout against overfitting. Opening question: The network scores 96% on its training data. Why is that not good news?

From *The Book of Machine Learning*, a free interactive machine learning textbook. Interactive version, with figures to use: https://thebookofml.com/keeping-networks-honest/

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.

**Check your understanding:** 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?

- Fall together with the training loss — That happens when there is plenty of data for the size of the network. Here there are almost nine weights for every point.
- Fall for a while, then climb **(correct)** — Early on the network learns the broad shape of the spirals, which helps everywhere. Then it starts fitting individual points, which helps only those points.
- Stay level from the start — The network does learn something real at first, so new points benefit for a while.

> **Interactive figure: Forty-five points, 387 weights.** Left: the training points and the regions the network assigns. Right: the loss on those points (dark) and on 450 new points from the same spirals (orange).
> Try it: press Train and watch the two loss curves separate. When it finishes, show the new points and look at how the regions treat them.
> (Use it at https://thebookofml.com/keeping-networks-honest/)

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 overfitting, exactly as in Part I. The network has carved its regions tightly around the individual points it was shown, including their accidents. A new point from the same arm, a little to one side, lands in the wrong region.

**Note:** Accuracy on new points barely changes while their loss triples. The network is not making many more mistakes. It is becoming far more confident about the mistakes it makes, which is what the loss measures and accuracy cannot see.

## A price on large weights

The first remedy is one you already know. [The regularization chapter](https://thebookofml.com/regularization/) added a penalty on the size of the weights to the loss, so that the model had to justify every large weight. The same weight penalty works for a network.

$$
\text{loss} = \text{data loss} + \lambda \sum w^2
$$

In the backward pass this adds $2\lambda w$ 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.

> **Interactive figure: Smaller weights, smoother regions.** The same network and the same 45 points. Changing the penalty restarts training from the same initial weights.
> Try it: set λ to 0.001 and train. Compare the shape of the regions, and the accuracy on new points, with the run without a penalty. Then try 0.1.
> (Use it at https://thebookofml.com/keeping-networks-honest/)

| 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 dropout, and the idea is disarmingly crude: during training, switch off a random selection of neurons at every step.

> **Interactive figure: A different network at every step.** Dark circles are active. Crossed circles are switched off for this training step.
> Try it: press the button several times and watch the pattern change. Then raise the dropout rate.
> (Use it at https://thebookofml.com/keeping-networks-honest/)

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 $1 / 0.7 \approx 1.43$, 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.

**Check your understanding:** A network is trained with 50% dropout on a hidden layer. What happens in that layer when the finished network makes a prediction?

- Half the neurons are switched off at random — That would make predictions random. Dropout is applied only during training.
- All neurons are active, with no scaling **(correct)** — Scaling the survivors during training keeps the expected signal the same as when every neuron is on, so nothing needs adjusting at prediction time.
- All neurons are active and their outputs are doubled — The doubling happens during training, to make up for the missing half. At prediction time nothing is missing.

## Dropout on the spiral

Here is the same over-sized network, with dropout applied to its hidden layer.

> **Interactive figure: Training with neurons missing.** The loss curves are measured with every neuron on, which is how the network would be used.
> Try it: set the dropout rate to 30% and train. Then try 60% and see what too much does.
> (Use it at https://thebookofml.com/keeping-networks-honest/)

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.

Early stopping uses this directly. Watch the loss on held-out data during training, and keep the weights from the moment it was lowest.

> **Interactive figure: The best network was an early one.** The dashed line marks the step at which the loss on new points was lowest so far.
> Try it: train to the end and read where the lowest point was. Notice how much longer training carried on after it.
> (Use it at https://thebookofml.com/keeping-networks-honest/)

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.

**Check your understanding:** 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?

- The learning rate is too high; lower it — A learning rate that is too high makes the training loss itself unstable. Here the training loss is behaving well.
- The network is overfitting; keep the weights from when the validation loss was lowest **(correct)** — Falling training loss with rising validation loss is the signature of overfitting. Early stopping keeps the best point; a weight penalty, dropout or more data address the cause.
- Nothing is wrong; train for longer — More training will widen the gap. The network is fitting details of the training set that do not carry over.

**Common mistake: Leaving dropout switched on**

Dropout belongs to training only. If it is still active when the network is used, every prediction is made by a random half of the network, so the same input can give different answers on different calls, and accuracy drops for no visible reason. Every library has a switch between training and prediction modes. Forgetting to flip it is one of the most common bugs in deep learning, and the symptom to look for is a network that does worse when deployed than it did during validation.

## In code

The dense layer gains an optional penalty, and dropout is a new layer with a `training` switch. The full file is [ch19_regularization.py](https://github.com/kamileren/quickproject/blob/master/code/ch19_regularization.py).

```python
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**.

## What you should now be able to do

- 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

### Exercise (by hand)

A layer outputs $[2,\ 4,\ 6,\ 8]$. 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 $[4,\ 0,\ 0,\ 16]$.

The average before was $20 / 4 = 5$. The average after is also $20 / 4 = 5$.

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.

### Exercise (by hand)

A layer has the weights $[3,\ -4,\ 0.5]$ and a penalty strength of $\lambda = 0.01$. 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 $2\lambda w$.

**Solution:**

The penalty is $\lambda$ times the sum of squared weights: $0.01 \times (9 + 16 + 0.25) = 0.2525$.

It adds $2\lambda w$ to each gradient: $0.06$, $-0.08$ and $0.01$.

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.

### Exercise (think)

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.

### Exercise (think)

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

1. **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.
2. **Add a weight penalty or dropout.** Both make memorising harder without changing the size of the network.
3. **Stop earlier.** Keep the weights from the epoch where held-out loss was lowest.
4. **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.

### Exercise (with the figure)

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

- H. Kinsley and D. Kukieła, *Neural Networks from Scratch in Python*, chapters 14 and 15, [nnfs.io](https://nnfs.io).
- N. Srivastava, G. Hinton, A. Krizhevsky, I. Sutskever and R. Salakhutdinov, [Dropout: a simple way to prevent neural networks from overfitting](https://jmlr.org/papers/v15/srivastava14a.html), *Journal of Machine Learning Research*, 2014.
- S. J. D. Prince, *Understanding Deep Learning*, chapter 9. Free at [udlbook.github.io/udlbook](https://udlbook.github.io/udlbook/).

## Next

The network now learns quickly and generalises. It still does only one job: choosing one class out of several. The next chapter shows that predicting a number, or answering yes or no, needs a change to the last layer and nothing else.
