Vanishing & Exploding Gradients
Source: Unit 2 §10
When training deep networks, the computed derivatives can become very large (exploding) or very small (vanishing), and either one makes training difficult or impossible.
Why it happens
Consider a deep net with all biases 0 and a linear activation . Then the output is simply a product of all the weight matrices:
- If each weight matrix scales its input by, say, 1.5, then over layers the factor is , which explodes for large .
- If it scales by 0.5, the factor is , which vanishes exponentially.
- The gradients used in gradient descent behave the same way, so they explode or vanish as a function of the depth .
Exploding gradients announce themselves - the loss goes to infinity or NaN.
Vanishing gradients look like a network that simply is not learning: the
early layers receive a gradient of approximately 0, so their weights never move
and training silently stalls.
The solution: careful weight initialisation
A partial solution is a more careful choice of random weight initialisation.
For a single neuron computing : the larger (the number of inputs), the smaller each should be, so that neither blows up nor collapses. That is achieved by setting the variance of the weights:
In code, per layer, where the layer has inputs:
| Activation | Recommended variance | Name |
|---|---|---|
| tanh | 1 / n^{[L−1]} | Xavier initialisation |
| ReLU | 2 / n^{[L−1]} (works better) | He initialisation |
tanh takes Xavier (); ReLU takes He (). ReLU zeroes out roughly half its inputs, so it needs twice the variance to keep the same signal scale leaving the layer.