Chapter 18 // Neural Networks

Optimizers.

Backpropagation gives exact gradients. Why was training still so slow?

Reading time
18 min
Data
Read first
Backpropagation

ended with a network that learned, but slowly: 2,000 steps to get 62% of the spiral right. The gradients were exact. What was crude was how we used them: subtract the gradient, times one fixed number, every time. The rule that turns gradients into updates is called an , and this chapter builds better ones, each fixing a specific weakness of the one before.

What plain gradient descent gets wrong

To see the weakness clearly we need a simple surface that shows it. Here is a long, narrow valley: gentle along its length, twenty times steeper across its width. Loss surfaces of real networks are full of shapes like this.

Figure

One learning rate for a lopsided valley

0, 0lowest-9, 3-8.91, 2.4-8.82, 1.92-8.73, 1.54-8.65, 1.23-8.56, 0.98-8.47, 0.79-8.39, 0.63-8.3, 0.5-8.22, 0.4-8.14, 0.32-8.06, 0.26-7.98, 0.21-7.9, 0.16-7.82, 0.13-7.74, 0.11-7.66, 0.08-7.59, 0.07-7.51, 0.05-7.44, 0.04-7.36, 0.03-7.29, 0.03-7.21, 0.02-7.14, 0.02-7.07, 0.01-7, 0.01-6.93, 0.01-6.86, 0.01-6.79, 0.01-6.72, 0-6.66, 0-6.59, 0-6.52, 0-6.46, 0-6.39, 0-6.33, 0-6.27, 0-6.21, 0-6.14, 0-6.08, 0-9, 3
Height after 10 steps
3.416
Height after 100 steps
0.543
Verdict
Not there after 100 steps
0.10
Each ring joins points of equal height. The path starts at the dark dot and takes 100 steps of plain gradient descent. Try it: start at 0.10 and read the verdict. Raise the rate slowly to 0.90, then on to 0.98, then past 1.00.

The trouble is that a single learning rate has to serve both directions.

  • At 0.10 the steps across the valley are well behaved, but progress along it is a crawl. After 100 steps the path is still well short of the bottom.
  • At 0.90 it arrives in 24 steps. That is as good as it gets.
  • At 0.98 each step overshoots the steep direction, and the path wastes its effort bouncing from wall to wall.
  • Just past 1.00 every bounce is bigger than the last, and the run diverges.

The steep direction sets a hard ceiling on the learning rate, and the gentle direction wants a rate far above that ceiling. The best single value sits on the edge of disaster, and you can only find it by trial and error. Real networks have millions of directions, each with its own steepness.

Start big, finish small

A first, easy improvement: do not keep the learning rate fixed. Large steps are useful early on, when the weights are far from anywhere good. Small steps are needed late, to settle instead of bouncing. shrinks the rate as training goes on.

ηt=η01+decay×t\eta_t = \frac{\eta_0}{1 + \text{decay} \times t}

current rate = starting rate ÷ (1 + decay × number of steps so far)

Figure

Letting the bouncing die away

0, 0lowest-9, 3-8.12, -2.88-7.32, 2.76-6.6, -2.65-5.96, 2.55-5.37, -2.45-4.85, 2.35-4.37, -2.25-3.94, 2.16-3.56, -2.08-3.21, 1.99-2.89, -1.91-2.61, 1.84-2.35, -1.76-2.12, 1.69-1.92, -1.63-1.73, 1.56-1.56, -1.5-1.41, 1.44-1.27, -1.38-1.14, 1.33-1.03, -1.27-0.93, 1.22-0.84, -1.17-0.76, 1.13-0.68, -1.08-0.62, 1.04-0.56, -1-0.5, 0.96-0.45, -0.92-0.41, 0.88-0.37, -0.85-0.33, 0.81-0.3, -0.78-0.27, 0.75-0.24, -0.72-0.22, 0.69-0.2, -0.66-0.18, 0.64-0.16, -0.61-9, 3
Height after 10 steps
4.493
Height after 100 steps
0.003
Verdict
Near the bottom in 64 steps
0.000
The starting rate is 0.98, slightly too large for the steep direction. Try it: with decay at zero, watch the path bounce. Raise the decay a little, to about 0.02. Then raise it a lot and see the opposite problem.

With no decay the path takes 64 steps to settle. A decay of 0.02 cuts that to 27, because the bounces shrink as the rate does. But decay is one more setting that can be wrong: at 0.2 the rate collapses so quickly that the path runs out of energy before it arrives.

Momentum

The bouncing has a pattern worth exploiting. Across the valley, successive gradients point in opposite directions: left, right, left. Along the valley they all point the same way. If each step remembered the previous ones, the back-and-forth would cancel and the consistent direction would add up.

That is . Keep a running velocity. At each step, keep a fraction of the old velocity and add the new gradient step to it.

v←β v−η ∇Lw←w+vv \leftarrow \beta\,v - \eta\,\nabla L \qquad\qquad w \leftarrow w + v

velocity = momentum × old velocity − learning rate × gradient; then move by the velocity

The picture is a heavy ball rolling downhill. It does not turn on the spot when the slope changes; it carries on, and picks up speed where the slope keeps pointing the same way.

Figure

A ball that remembers

0, 0lowest-9, 3-8.91, 2.4-8.82, 1.92-8.73, 1.54-8.65, 1.23-8.56, 0.98-8.47, 0.79-8.39, 0.63-8.3, 0.5-8.22, 0.4-8.14, 0.32-8.06, 0.26-7.98, 0.21-7.9, 0.16-7.82, 0.13-7.74, 0.11-7.66, 0.08-7.59, 0.07-7.51, 0.05-7.44, 0.04-7.36, 0.03-7.29, 0.03-7.21, 0.02-7.14, 0.02-7.07, 0.01-7, 0.01-6.93, 0.01-6.86, 0.01-6.79, 0.01-6.72, 0-6.66, 0-6.59, 0-6.52, 0-6.46, 0-6.39, 0-6.33, 0-6.27, 0-6.21, 0-6.14, 0-6.08, 0-9, 3
Height after 10 steps
3.416
Height after 100 steps
0.543
Verdict
Not there after 100 steps
0.00
The learning rate is fixed at the cautious 0.10 that was too slow on its own. Try it: raise the momentum from 0 toward 0.90 and watch the path stretch out along the valley. Then push it to 0.98.

With momentum at 0.9, the cautious learning rate that never arrived now gets there in 24 steps, as fast as the best hand-tuned rate, and without sitting next to the cliff. The usual value is 0.9. Too much, and the ball has so much inertia that it sails past the bottom and has to come back.

Checkpoint

During training the gradient for one weight keeps flipping sign: +3, −3, +3, −3. What does momentum do to that weight's updates?

A step size for every weight

Momentum smooths the direction. A different idea attacks the original problem head on: why should every weight share one learning rate at all?

An gives each weight its own step size, set from that weight’s own history. A weight whose gradients have been large gets a smaller step. A weight whose gradients have been tiny gets a larger one. In the valley, that means short steps across and long steps along, automatically.

The mechanism is simple: keep a running total of each weight’s squared gradients, and divide its step by the square root of that total.

MethodWhat it remembersConsequence
AdaGradThe sum of all squared gradients so farSteps only ever shrink. Training can stall before it is finished.
RMSPropA fading average of recent squared gradientsSteps adapt to the current terrain and do not shrink for ever.
ExampleTwo weights, one update

Suppose two weights have recently seen gradients of typical size 10 and 0.1.

  • Plain gradient descent with rate 0.01 moves them by 0.1 and 0.001. The second weight is barely moving.
  • RMSProp divides each step by the typical gradient size: both move by about 0.01.

Every weight makes progress at a similar pace, whatever the scale of its gradients.

Adam, and a race

The last step is to use both ideas together. keeps a momentum-style running average of the gradient and an RMSProp-style running average of its square, and divides one by the other.

It adds one small correction. Both averages start at zero, so for the first few steps they are too small. Adam divides each by a factor that undoes this, and the effect is that its very first step has a sensible size.

Here are four optimizers on the same valley, each with ordinary default-style settings and no tuning to this surface.

Figure

Four ways down the same valley

0, 0lowest-9, 3-9, 3-9, 3-9, 3
  • Plain SGD (rate 0.1)
  • Momentum (rate 0.1, momentum 0.9)
  • RMSProp (rate 0.3)
  • Adam (rate 0.5)
Plain SGD
height 13.050
Momentum
height 13.050
RMSProp
height 13.050
Adam
height 13.050
Step 0 of 100
All four start from the same point. Plain gradient descent uses the cautious rate, since its fast rate was on the edge of diverging. Try it: press Race and watch the order in which they arrive. Reset and use Step to follow the first ten moves one at a time.

Momentum, RMSProp and Adam all reach the bottom in 20 to 30 steps. Plain gradient descent is still on its way after 100.

To be fair to it: we saw that plain gradient descent can match them here, at a rate of 0.9. The difference is that it needed exactly the right rate, found by search, right next to the value at which it blows up. The others got there with settings chosen before looking at the surface. That robustness, more than raw speed, is why Adam became the default.

On a real network

Now the test that matters. This is the spiral network from , unchanged: same data, same 195 weights, same starting point. Only the optimizer differs.

Figure

The same network, five optimizers

0, 00, 0.010, 0.020, 0.030, 0.040.04, 0.030.03, 0.050.04, 0.060.05, 0.070.08, 0.040.09, 0.040.11, 0.020.12, 0.030.1, 0.080.14, -0.020.14, 0.050.15, -0.050.17, -0.010.18, -0.020.19, 0.010.2, -0.030.2, -0.080.16, -0.150.22, -0.060.23, -0.090.22, -0.120.25, -0.070.16, -0.220.04, -0.28-0.03, -0.290.08, -0.290.04, -0.310.02, -0.32-0.08, -0.32-0.03, -0.34-0.1, -0.34-0.16, -0.330.04, -0.37-0.3, -0.24-0.22, -0.32-0.32, -0.25-0.05, -0.41-0.34, -0.25-0.26, -0.35-0.44, -0.07-0.31, -0.33-0.45, -0.12-0.46, 0.1-0.48, 0-0.49, -0.09-0.5, -0.07-0.51, -0.08-0.53, -0.01-0.53, -0.07-0.53, 0.12-0.56, -0.02-0.37, 0.43-0.4, 0.42-0.33, 0.48-0.27, 0.53-0.22, 0.57-0.29, 0.54-0.17, 0.6-0.23, 0.59-0.23, 0.6-0.03, 0.66-0.02, 0.670.32, 0.590.22, 0.650.14, 0.680.29, 0.650.62, 0.360.46, 0.560.35, 0.650.32, 0.670.71, 0.270.67, 0.380.78, 0.040.79, 0.020.79, 0.140.8, 0.140.81, 0.080.82, 0.070.82, 0.190.79, 0.30.84, 0.180.71, -0.50.88, 00.71, -0.530.49, -0.750.31, -0.860.89, -0.210.72, -0.590.46, -0.820.48, -0.82-0.06, -0.960.49, -0.830.46, -0.86-0.16, -0.98-0.36, -0.930, 00.01, -0.010.01, -0.010.02, -0.020.03, -0.020.04, -0.030.03, -0.050.04, -0.060.03, -0.070, -0.090.04, -0.090.05, -0.1-0.02, -0.12-0.07, -0.11-0.07, -0.12-0.01, -0.15-0.04, -0.16-0.07, -0.16-0.06, -0.17-0.15, -0.12-0.18, -0.1-0.12, -0.17-0.15, -0.17-0.21, -0.1-0.24, -0.06-0.25, -0.03-0.23, -0.13-0.26, -0.07-0.28, 0-0.29, -0.02-0.3, 0.06-0.31, 0.02-0.32, 0.06-0.24, 0.23-0.21, 0.27-0.31, 0.17-0.24, 0.27-0.32, 0.2-0.2, 0.32-0.19, 0.35-0.16, 0.37-0.02, 0.41-0.12, 0.41-0.17, 0.4-0.11, 0.43-0.05, 0.450.02, 0.460.04, 0.470.29, 0.390.27, 0.410.17, 0.480.4, 0.330.42, 0.310.33, 0.420.16, 0.520.5, 0.230.56, 0.090.47, 0.330.58, -0.070.59, -0.070.61, 00.61, 0.110.6, -0.160.59, -0.230.63, -0.150.64, -0.160.64, 0.20.67, -0.110.27, -0.630.4, -0.570.47, -0.520.44, -0.560.42, -0.590.29, -0.680.29, -0.69-0.1, -0.75-0.18, -0.75-0.04, -0.780.14, -0.77-0.4, -0.690.09, -0.8-0.46, -0.67-0.47, -0.68-0.69, -0.48-0.37, -0.76-0.77, -0.38-0.62, -0.61-0.6, -0.65-0.72, -0.53-0.85, -0.28-0.89, -0.16-0.83, -0.39-0.83, 0.41-0.93, 0.12-0.94, 0.16-0.91, 0.3-0.92, 0.31-0.93, 0.3-0.89, 0.43-0.99, 0.10, 0-0.01, 0-0.02, -0.01-0.03, 0-0.04, 0.01-0.05, -0.01-0.06, -0.01-0.07, 0-0.07, 0.04-0.03, 0.08-0.1, 0.03-0.11, 0.03-0.06, 0.11-0.12, 0.05-0.04, 0.14-0.1, 0.110.01, 0.160, 0.17-0.02, 0.18-0.03, 0.19-0.05, 0.20, 0.21-0.07, 0.21-0.03, 0.230.06, 0.23-0.01, 0.250.03, 0.260.15, 0.230, 0.280.18, 0.230.07, 0.290.24, 0.20.24, 0.220.32, 0.080.3, 0.170.35, 0.010.32, 0.170.37, 0.040.37, 0.090.39, -0.080.38, -0.140.4, -0.120.42, -0.060.42, -0.110.44, -0.080.09, -0.450.21, -0.410.42, -0.220.46, -0.160.27, -0.420.26, -0.430.05, -0.510.42, -0.320.03, -0.53-0.08, -0.540.22, -0.510.21, -0.53-0.29, -0.5-0.12, -0.57-0.41, -0.43-0.3, -0.53-0.27, -0.56-0.41, -0.47-0.49, -0.4-0.62, -0.18-0.58, -0.32-0.24, -0.62-0.68, 0.04-0.61, -0.32-0.7, -0.04-0.68, -0.18-0.71, 0.08-0.68, -0.26-0.74, -0.04-0.72, 0.19-0.72, 0.22-0.74, 0.22-0.49, 0.6-0.69, 0.39-0.39, 0.7-0.73, 0.34-0.68, 0.460.03, 0.83-0.45, 0.71-0.09, 0.84-0.21, 0.83-0.22, 0.84-0.44, 0.760.23, 0.86-0.39, 0.810.25, 0.870.22, 0.890.67, 0.650.32, 0.880.71, 0.630.83, 0.470.64, 0.730.34, 0.920.89, 0.430.76, 0.65
  • Class 1, and where the network predicts it
  • Class 2, and where the network predicts it
  • Class 3, and where the network predicts it
Steps
0
Loss
1.173
Right on the 300 shown
32%
Right on 300 new points
34%
Each run starts from identical weights. Choosing an optimizer resets the network. Try it: train with plain SGD for a few hundred steps to remember how slow it was. Then choose Adam and train again.

After 2,000 steps each:

OptimizerLossRight on the training pointsRight on new points
Plain SGD0.78862%58%
AdaGrad0.75163%60%
RMSProp0.23892%85%
SGD with momentum and decay0.03199%96%
Adam0.01599%95%

Adam passes 96% within the first 300 steps. Nothing about the network or the data changed. The gradients were always good enough; they only needed to be used well.

Checkpoint

You are starting a new project and have to pick an optimizer before knowing anything about the loss surface. What is the sensible default?

In code

All the optimizers share one small base class that handles the decay. Here are the two most used. The full file, code/ch18_optimizers.py (run it in Colab), has all five and runs the comparison.

class Optimizer_SGD(Optimizer):
    def update_params(self, layer):
        # Keep part of the last step, add the new gradient step.
        layer.weight_momentums = self.momentum * layer.weight_momentums - self.current_learning_rate * layer.dweights
        layer.weights += layer.weight_momentums
        # ...and the same two lines for the biases

class Optimizer_Adam(Optimizer):
    def update_params(self, layer):
        # Momentum: a running average of the gradients.
        layer.weight_momentums = self.beta_1 * layer.weight_momentums + (1 - self.beta_1) * layer.dweights
        # Cache: a running average of the squared gradients.
        layer.weight_cache = self.beta_2 * layer.weight_cache + (1 - self.beta_2) * layer.dweights ** 2
        # Both start at zero, so early on they are too small. Dividing corrects that.
        step = self.iterations + 1
        weight_momentums = layer.weight_momentums / (1 - self.beta_1 ** step)
        weight_cache = layer.weight_cache / (1 - self.beta_2 ** step)

        layer.weights -= self.current_learning_rate * weight_momentums / (np.sqrt(weight_cache) + self.epsilon)

In the training loop, the single line that updated the weights is the only thing that changes. The Python version, run for 2,000 epochs, gives 53% with plain SGD and 99% with either momentum or Adam.

Key Takeaways

  • Plain gradient descent uses one learning rate for every direction, and the steepest direction limits it.
  • Decay starts with large steps and ends with small ones.
  • Momentum carries speed from step to step: consistent directions build up, back-and-forth cancels.
  • RMSProp gives each weight its own step size, based on its recent gradients.
  • Adam combines momentum and per-weight step sizes, and is the usual default.
You can now
  • Explain why one learning rate cannot suit a lopsided loss surface.
  • Work out a decayed learning rate and a momentum update by hand.
  • Say what RMSProp and Adam each add, and why Adam is the usual first choice.
  • Pick sensible starting settings for an optimizer.

Exercises

Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.

Exerciseby hand

A run uses a starting learning rate of 1 and a decay of 0.1. What is the learning rate at step 0, at step 10 and at step 90?

Hint

Current rate = starting rate ÷ (1 + decay × steps so far).

Solution

The rule is: current rate = starting rate ÷ (1 + decay × steps so far).

  • Step 0: 1/(1+0)=11 / (1 + 0) = 1
  • Step 10: 1/(1+1)=0.51 / (1 + 1) = 0.5
  • Step 90: 1/(1+9)=0.11 / (1 + 9) = 0.1

The rate halves in the first ten steps and then takes another eighty to fall to a tenth. Decay acts quickly at first and ever more gently later.

Exerciseby hand

With momentum, each update is 0.9 times the previous update, minus the learning rate times the gradient. The learning rate is 0.1. First suppose the gradient is 1 at every step: what are the first three updates, and what do they approach? Then suppose the gradient alternates between 1 and −1: what are the first three updates?

Hint

Compute each update from the one before: 0.9 times the previous update, minus 0.1 times the gradient.

Solution

Steady gradient. The updates are −0.1-0.1, then 0.9×(−0.1)−0.1=−0.190.9 \times (-0.1) - 0.1 = -0.19, then 0.9×(−0.19)−0.1=−0.2710.9 \times (-0.19) - 0.1 = -0.271. They keep growing and approach −0.1/(1−0.9)=−1-0.1 / (1 - 0.9) = -1. In a direction where the gradient always agrees with itself, momentum ends up moving ten times as fast as a plain step.

Alternating gradient. The updates are −0.1-0.1, then 0.9×(−0.1)+0.1=0.010.9 \times (-0.1) + 0.1 = 0.01, then 0.9×0.01−0.1=−0.0910.9 \times 0.01 - 0.1 = -0.091. They never build up, and none is larger than a plain step, because each one is partly cancelled by what came before.

That is the whole benefit: fast along the valley, calm across it.

Exerciseby hand

The valley in this chapter is f(x,y)=0.05x2+y2f(x, y) = 0.05x^2 + y^2. With plain gradient descent, each step multiplies yy by (1−2η)(1 - 2\eta) and xx by (1−0.1η)(1 - 0.1\eta). Use this to explain why the run diverges just above a learning rate of 1, and why it is slow even at 0.9.

Hint

A value multiplied by a number larger than 1 in size grows. One multiplied by 0.91 shrinks slowly.

Solution

The limit. The size of yy grows whenever 1−2η1 - 2\eta is below −1, which happens as soon as η\eta is above 1. The steep direction sets the limit.

The slowness. At η=0.9\eta = 0.9 the flat direction is multiplied by 1−0.09=0.911 - 0.09 = 0.91 at each step. Shrinking xx to a tenth of its starting value takes about 24 steps, since 0.9124≈0.10.91^{24} \approx 0.1. The learning rate that xx would like, about 10, is ten times beyond what yy can survive.

One rate has to serve two directions with very different steepness. Momentum and the adaptive methods are both ways out of that bind.

Exercisethink

Two weights have gradients that are steadily 100 and 0.01. With plain gradient descent and a learning rate of 0.01, how far does each move in one step? Roughly how far does each move in one step of Adam with the same learning rate? What does that tell you about when Adam helps?

Hint

Plain gradient descent moves a weight by the rate times its gradient. Adam first divides the gradient by its typical size.

Solution

Plain gradient descent moves each weight by the rate times its gradient: 1 for the first weight and 0.0001 for the second. One of them is moving ten thousand times faster than the other.

Adam divides each gradient by its own typical size before applying the rate, so both weights move by about 0.01.

Adam helps when gradients differ greatly in size from weight to weight, which is normal in a deep network: layers near the output usually see larger gradients than layers near the input. It removes the need to find one rate that suits them all.

Exercisewith the figure

In the figure “A ball that remembers”, raise the momentum from 0 to 0.9 and count the steps to settle. Then try 0.98. What goes wrong, and how does it differ from a learning rate that is too large?

Hint

With plain steps and a cautious rate, the run never arrived within 100 steps.

Solution

With no momentum the cautious learning rate does not arrive in 100 steps. At 0.9 it gets there in 24, because steps along the valley floor all point the same way and build on each other.

At 0.98 the ball carries so much speed that it sails past the lowest point and has to come back, swinging to and fro before it settles. That is different from a learning rate that is too large. The ball still settles in the end, because friction removes a little speed at every step, whereas too large a learning rate makes each step bigger than the last and never recovers.

Going further

The learning rate still matters

Adaptive optimizers are forgiving, not magic. Adam’s rate still needs to be roughly right, and it is usually the first thing to adjust when training misbehaves: try values a factor of three or ten apart. Schedules that warm the rate up from zero and then lower it are standard for large models.

When plain SGD is preferred

For some problems, especially image models trained for a long time, SGD with momentum and a careful schedule ends at solutions that generalize slightly better than Adam’s. It costs more tuning. Adam, and its variant AdamW with a corrected weight penalty, remain the place to start.

References and further reading

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 18.1What plain gradient descent gets wrong
  3. 18.2Start big, finish small
  4. 18.3Momentum
  5. 18.4A step size for every weight
  6. 18.5Adam, and a race
  7. 18.6On a real network
  8. 18.7In code
  9. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in