Regularisation and generalisation
How to stop a network from memorising and force it to generalise.
In chapter 9, we proved that gradient descent drives the score down, step after step, as long as the step stays reasonable. That is a real guarantee. But it concerns the training score, the one computed on the examples the network has in front of it. And a polynomial of degree nine can pass exactly through ten measurement points, with a score of zero, while oscillating wildly between them.
The question of this chapter is therefore: how can we tell whether a network has learned the trend or only the points? And above all, how do we stop it from memorising without stopping it from learning? We will see that the classical answers can be proven, and that they are closer to one another than they look.
Act 1: memorising is not learning
Picture a student preparing for an exam with the past papers of the last ten years. They have a prodigious memory: they retain every model answer, word for word. On past papers, they score full marks. On exam day, the paper is new. They are stuck. They learned the answers, not the method.
A neural network runs exactly the same risk. What we ask of it is to answer well on examples it has never seen: that is generalisation. What we make it minimise is the score on the training examples. The two do not coincide. When the training score is excellent but the performance on new examples is poor, we speak of overfitting Overfitting A situation where a model fits its training examples so closely that it also learns their noise: its training loss is excellent, but its performance on new examples is poor. It has memorised the points instead of the trend. Source: Goodfellow, Bengio and Courville, 2016 .
The polynomial that goes everywhere. Take ten measurement points whose abscissas are all different. There always exists a polynomial of degree at most nine that passes through all of them. We can write it explicitly:
This is the Lagrange interpolation polynomial. It reads: for each point , we build a product that equals at and at every other , then multiply it by . At , every term vanishes except the one for , which equals . So for every point: the training score is exactly zero.
If the measurements are noisy, this polynomial also hugs the noise. Between the points, it makes loops that have nothing to do with the real trend, especially near the edges. Runge (1901) showed that, even without noise, interpolation through equally spaced points can oscillate more and more strongly as the degree increases.
A network does the same. The universal approximation theorem of chapter 5 says that a wide enough network can represent almost any function. The flip side is brutal: it can also represent any memorisation. Zhang and his co-authors (2017) verified this spectacularly. They replaced the labels of an image dataset with labels drawn at random, with no link at all to the images. The networks still reached a perfect training score. On new images, of course, they answered at random. The training score alone therefore says nothing about generalisation.
Act 2: three datasets
Since the training score lies, we must measure something else. The idea is simple: we set aside examples that the network will never see during training, and we score it on them. We therefore split the data into three disjoint parts.
- The training set is used to compute gradients and update the weights.
- The validation set Validation set A held-out part of the data on which the network is never trained, used to make tuning choices: degree, regularisation strength, stopping time. It differs from the test set, which is kept for the final measurement only. is used to make choices: which degree, which regularisation strength, when to stop. The network never trains on it, but we consult it often.
- The test set serves a single purpose: announcing the final performance, once all choices have been made.
Why not merge validation and test? Because by repeatedly picking the setting that gives the best score on a set, we end up adapting to that set. Each choice is a small dose of learning. If we announced the validation score as the final performance, it would be optimistic. The test set must stay untouched until the very end.
Comparing the two scores gives a diagnosis:
- Both scores are poor: this is underfitting, the model is too simple.
- Training very good, validation poor: this is overfitting, the model has learned the noise.
- Both good and close: this is a good balance, the model has learned the trend.
The rest of the chapter presents remedies for overfitting. They share a common name: regularisation Regularisation Any change to training that aims to improve generalisation, even at the cost of a slightly worse training loss. Examples: L2 and L1 penalties on the weights, early stopping, dropout. Source: Goodfellow, Bengio and Courville, 2016 , meaning anything we add to training to improve generalisation, even at the price of a slightly worse training score.
Act 3: the L2 penalty, or weight decay
The degree-nine polynomial that oscillates has a signature: huge coefficients, which cancel each other out to pass through every point. A natural idea is therefore to penalise large weights. We no longer minimise the score alone, but the score plus a fine proportional to the squared norm of the weights:
It reads: the new score is the old one, plus times the sum of the squared weights. The number sets how heavy the fine is. At , we recover the original score. The larger , the more expensive large weights become.
The update rule. The gradient of is . A descent step on therefore reads
We group the terms in :
This line explains the name, weight decay Weight decay (L2 penalty) A regularisation that adds λ times the sum of the squared weights to the loss. Each descent step then multiplies the weights by 1 − 2ηλ before the gradient correction, hence the name. It mostly shrinks the directions that the data determine poorly. Source: Krogh and Hertz, 1992 . Even before the gradient correction, each step multiplies every weight by , a number slightly below . If the data do not call for a weight, it melts away on its own, step after step (Krogh and Hertz, 1992). In practice, only the weights are penalised, not the biases: a bias merely shifts an output, it does not create oscillations.
What the penalty does exactly. To find out, we study a score we know everything about: a sum of parabolas, one per weight,
Without a penalty, its minimum is . Each is the curvature along weight , exactly as in chapter 9. This case is not just a toy: near a minimum, any smooth score looks like a bowl of this kind, after a well-chosen change of axes (Goodfellow, Bengio and Courville, 2016, section 7.1.1).
Theorem (shrinkage). The minimum of is reached at
Proof. The penalised score is a sum of terms that each depend on a single weight:
We can therefore minimise each term separately. Fix and differentiate the term :
This derivative vanishes when , that is at . Finally, is a parabola whose coefficient is : it opens upwards, so this point is its unique minimum. □
How to read it. Each optimal weight is multiplied by a factor , between and . This factor depends on the curvature:
- if is large compared with , the factor is close to : the weight is almost untouched;
- if is small compared with , the factor is close to : the weight is crushed.
Now, a low curvature means that moving this weight barely changes the training score. The data do not really know what to do with it. It is precisely in these blurry directions that noise settles, because nothing stops it. The L2 penalty therefore leaves in place what the data determine clearly, and erases what they determine poorly. This is the ridge regression of Hoerl and Kennard (1970), rediscovered under another name by neural networks.
A bonus for descent. On the penalised score, the curvature along weight becomes . By chapter 9, descent therefore converges for in each direction. And the ravine softens: with curvatures and , the ratio between the steep and the flat direction is . With , it becomes .
Play with the lab. The ten points are noisy measurements of a sine wave, drawn as a dotted line. Start at degree nine with no penalty, then raise notch by notch.
Regularization lab
- Training error
- Validation error
- best
- current
Three things to watch as you play:
- At and degree nine, the curve passes exactly through the ten points: the training error is zero, but the validation error is poor. That is memorisation.
- As you raise , the training error always increases, while the validation error first drops, then rises again. The right-hand graph draws a U: the right setting sits at the bottom.
- With a very large , the curve flattens towards the mean of the points. That is underfitting, caused this time by a fine that is too heavy.
Act 4: the L1 penalty and sparsity
Another possible fine uses the absolute value instead of the square:
It looks like a detail. It is a difference in kind: the L1 penalty sets weights exactly to zero, which the L2 penalty never does. To see it, take the simplest case, a single weight with a score of curvature centred at .
Proposition (soft thresholding). For , the function reaches its minimum at
Proof. The absolute value changes formula at , so we reason by cases.
Case . We compare with . For , we have and
Since , the number is non-negative, so the bracket is strictly positive, and so is the product. For , we have and
Since , the number is non-positive, so the bracket is strictly negative. A negative number times a negative number is positive. In both cases, : the minimum is at .
Case . For , is an upward parabola, with derivative , which vanishes at . This point is indeed positive, so it is the minimum over . For , the derivative of is , which is strictly negative since : decreases down to , so nothing does better than , which is itself beaten by .
Case . This is the previous case seen in a mirror: replace with and with . □
How to read it. The L1 penalty moves each weight towards zero by a fixed amount, , and if the weight cannot afford it, it falls to zero and stays there. Compare with L2 in the same situation: the minimum of is , which is never zero as long as . L2 trims every weight proportionally. L1 switches some of them off.
A model in which many weights are exactly zero is called sparse. This is useful when we suspect that only a few inputs really matter: L1 does the sorting on its own. This is the lasso of Tibshirani (1996). When the score has several weights with curvatures , the same computation gives a threshold of per weight.
Act 5: early stopping
The third method does not touch the score. It touches the schedule. During training, we measure the validation score at every epoch. At first, it goes down along with the training score. Then, at some point, it starts climbing while the training score keeps falling: the network is starting to learn the noise. We keep the weights from the best moment, and we stop. This is early stopping Early stopping A regularisation that monitors the validation loss during training and keeps the weights from the moment it was lowest, before the network learns the noise. On a quadratic loss, stopping after t steps acts like an L2 penalty of strength about 1/(2ηt). Source: Prechelt, 1998 .
In practice, we do not stop at the first rise, which may only be a hiccup. We allow a patience of a few epochs, and we keep in memory the best weights seen so far (Prechelt, 1998).
It looks like an engineering trick. We will see that it is a regularisation in the full sense, and even a very close cousin of L2.
Theorem (exact trajectory). Take the score again, and run gradient descent without a penalty from , with a rate . After steps, each weight equals
Proof. The derivative of the score with respect to is . A descent step therefore gives
We subtract from both sides and factor:
This is exactly the geometric sequence of chapter 9, applied to the gap from the minimum. At the start, the gap is . After steps, it is therefore . We add to recover the weight, and we get the formula. □
How to read it. As with L2, each final weight is multiplied by a factor between and that depends on the curvature. Steep directions converge in a few steps: their factor quickly reaches . Flat directions barely move: their factor stays close to while is small. Stopping early therefore means keeping the well-determined directions and leaving the blurry ones behind. Exactly what the L2 penalty did.
Corollary (same envelope as L2). Assume , the zone of calm descent from chapter 9. Then the early stopping factor and the L2 factor satisfy
If we choose , both factors therefore lie under the same line .
Proof. The second inequality is immediate: enlarging a denominator, by adding to it, makes a positive fraction smaller. For the first, set , which lies between and . It is enough to show Bernoulli’s inequality,
We proceed by induction. For , it reads . If it holds at rank , we multiply it by , which is non-negative, so the inequality keeps its direction:
The last term is non-negative, so : this is rank . □
How to read it. The number of steps plays the role of the inverse of the penalty: . Stopping very early amounts to regularising very strongly, letting it run for a long time amounts to barely regularising. Be careful about exactly what the corollary says: it proves that both factors share the same envelope for flat directions, and that both tend to for steep directions. It does not say they are equal. The equivalence between early stopping and L2 is an approximation, very good in practice, analysed in detail by Sjöberg and Ljung (1995) and by Goodfellow, Bengio and Courville (2016, section 7.8). Exercise 5 will have you measure the gap.
Switch the lab to early stopping mode. Descent starts from zero coefficients, at degree nine, with no penalty.
Regularization lab
- Training error
- Validation error
- best
- current
Three things to watch as you play:
- At first, the curve is flat, then it takes the shape of the sine wave: the steep directions, the overall trend, are learned first.
- The validation error reaches its minimum fairly early, then rises again while the curve twists to catch every point.
- Compare the best validation error with the one for the best in penalty mode. They are very close: two different roads to the same regularisation.
Act 6: dropout
The last method was born with deep networks. During training, at each step, we randomly switch off some of the hidden neurons. Each neuron is kept with probability , and switched off otherwise, independently of the others. At the next step, we draw again. This is dropout Dropout A regularisation that, at each training step, randomly switches off each hidden neuron with probability 1 − p. The kept outputs are divided by p to preserve their mean, so the full network is used at prediction time without any correction. Source: Srivastava et al., 2014 (Hinton et al., 2012; Srivastava et al., 2014).
Think of a football team that trains without ever knowing which players will show up. Nobody can rely entirely on one specific teammate, so everyone learns to be useful on their own. In a network, the matching danger is called co-adaptation: neurons that only work together, correcting each other, often to fit the noise. Dropout breaks up these arrangements.
Inverted dropout. For each hidden neuron , we draw a mask equal to with probability and otherwise. The output of the neuron is replaced by
It reads: if the neuron is kept, its output is divided by , hence amplified; if it is switched off, the output is zero. Why amplify?
Proposition (the mean is preserved). On average over the mask draws, .
Proof. The mask equals with probability and with probability , so its mean is
Since and are fixed during the draw, we get
By linearity, the weighted sum received by the next layer, , also has mean . Practical consequence: at prediction time, we turn dropout off and use the full network, with no correction at all. The exact mean is only guaranteed before the activation function. After a non-linearity, preservation is only approximate, which works very well in practice.
A crowd of sub-networks. Each mask defines a sub-network. With hidden neurons, there are of them, and they all share the same weights. With neurons, that is , more than . Training with dropout means training each of them a little. Predicting with the full network means letting this whole crowd vote, approximately. And an average of many models has a lower variance than each of them: we find the third term of the bias-variance decomposition again. Srivastava and his co-authors recommend for hidden neurons and a value closer to , such as , for inputs.
Exercises
Grab something to write with. The solutions are deliberately detailed, line by line.
Exercise 1. Three networks give the following errors (training, validation): network A , network B , network C . Give a diagnosis for each. Then: to choose the strength of a penalty, on which set do you compare the settings, and why not on the test set?
Exercise 2. A weight equals , and backpropagation gives . Take a descent step with and an L2 penalty of strength . Compare with the same step without a penalty.
Exercise 3. A two-weight score is . With an L2 penalty of strength , where is the minimum? Which direction is shrunk the most, and why?
Exercise 4. Three weights have the unpenalised minimum , each on a score . Compute the optimal weights with an L1 penalty of strength , then with an L2 penalty of the same strength.
Exercise 5. A direction has curvature and minimum . We start from with and stop after steps. Compute the resulting weight, check the corollary’s bound, then compare with the associated L2 penalty .
In one sentence
A network can learn its examples by heart, and regularisation (the L2 penalty that shrinks blurry directions, the L1 penalty that switches weights off, early stopping that acts like an L2 penalty of strength , dropout that lets a crowd of sub-networks vote) trades a little training score for much better generalisation, tuned on a validation set.
Quiz
1. A network has a training error of 0.01 and a validation error of 0.30. What is happening?
2. On a score Σ aᵢ (wᵢ − wᵢ*)², what does an L2 penalty of strength λ do?
3. Which penalty can set a weight exactly to zero?
4. Why is early stopping said to be a form of regularisation?
5. With inverted dropout, what do we do at prediction time?
Towards chapter 11
Early stopping starts from zero weights, and the L2 penalty pulls the weights towards zero. Everything pushes towards zero. So why not simply start a network with all its weights at zero? Because it would be fatal. Go back to the toy network of chapter 8, with its two hidden neurons. If their weights are identical at the start, they compute the same output, receive the same error signal, and undergo exactly the same update. At the next step, they are still identical, and so on forever. Two twin neurons are worth only one: the network has lost its hidden layer. Conversely, initial weights that are too large saturate the sigmoids, and we fall back on the vanishing gradient of chapter 8. We therefore need to start from weights that are small, but different, and at the right scale. Chapter 11 computes that scale, then shows how to maintain it layer after layer throughout training: this is initialisation, and batch normalisation.
Sources
- Runge, C. (1901). “Über empirische Funktionen und die Interpolation zwischen äquidistanten Ordinaten.” Zeitschrift für Mathematik und Physik 46, 224-243. archive.org
- Hoerl, A. E. & Kennard, R. W. (1970). “Ridge Regression: Biased Estimation for Nonorthogonal Problems.” Technometrics 12(1), 55-67. DOI 10.1080/00401706.1970.10488634
- Krogh, A. & Hertz, J. A. (1992). “A Simple Weight Decay Can Improve Generalization.” Advances in Neural Information Processing Systems 4, 950-957.
- Geman, S., Bienenstock, E. & Doursat, R. (1992). “Neural Networks and the Bias/Variance Dilemma.” Neural Computation 4(1), 1-58. DOI 10.1162/neco.1992.4.1.1
- Sjöberg, J. & Ljung, L. (1995). “Overtraining, regularization and searching for a minimum, with application to neural networks.” International Journal of Control 62(6), 1391-1407. DOI 10.1080/00207179508921605
- Tibshirani, R. (1996). “Regression Shrinkage and Selection via the Lasso.” Journal of the Royal Statistical Society, Series B 58(1), 267-288. DOI 10.1111/j.2517-6161.1996.tb02080.x
- Prechelt, L. (1998). “Early Stopping, But When?” In Neural Networks: Tricks of the Trade, LNCS 1524, Springer, 55-69. DOI 10.1007/3-540-49430-8_3
- Hinton, G. E., Srivastava, N., Krizhevsky, A., Sutskever, I. & Salakhutdinov, R. (2012). “Improving neural networks by preventing co-adaptation of feature detectors.” arXiv:1207.0580
- Srivastava, N., Hinton, G., Krizhevsky, A., Sutskever, I. & Salakhutdinov, R. (2014). “Dropout: A Simple Way to Prevent Neural Networks from Overfitting.” Journal of Machine Learning Research 15, 1929-1958. jmlr.org
- Zhang, C., Bengio, S., Hardt, M., Recht, B. & Vinyals, O. (2017). “Understanding deep learning requires rethinking generalization.” ICLR 2017. arXiv:1611.03530
- Goodfellow, I., Bengio, Y. & Courville, A. (2016). Deep Learning. MIT Press. Chapter 7, especially sections 7.1.1 (L2 penalty) and 7.8 (early stopping). https://www.deeplearningbook.org