Gradient descent, explained with pictures

Momentum, Nesterov (NAG), AdaGrad, RMSProp, Adam. The names sound hard, but they are all ways to "roll a ball downhill to find the bottom." No math needed. Try it yourself.

Short answer. Gradient descent moves downhill one step at a time, using the slope where it stands. The other five add two ideas to it: inertia (momentum, Nesterov) and a different step size for each direction (AdaGrad, RMSProp). Adam combines both.

Definitions

The text below uses a ball rolling on ground of height f. These are the textbook definitions. x is a position made of n numbers (in training, all the weights), f is the function to make as small as possible (the loss), and η > 0 is the learning rate.

gradient
The vector ∇f(x) of the n partial derivatives of f. It is what this page calls the slope. At x it points in the direction in which f grows fastest.

∇f(x)=(∂f∂x1,…,∂f∂xn)

gradient descent
A method that looks for the minimum of f by moving, again and again, against the gradient at the current position, scaled by the learning rate η. One step is below.

x←x−η∇f(x)

momentum
A method that remembers the last step (the velocity) v and makes the new step μ times the last step plus the gradient descent step. The momentum coefficient μ is at least 0 and less than 1. With μ = 0 it is the same as gradient descent.

v←μv−η∇f(x),x←x+v

Nesterov accelerated gradient (NAG)
The same as momentum, except that the gradient is measured not at the current position x but at x + μv, the spot the remaining velocity would carry it to.

v←μv−η∇f(x+μv),x←x+v

adaptive learning rate
A method that remembers the size of past gradients and sets the actual step size separately for each entry (direction) of the position. AdaGrad adds the square of the gradient g to G entry by entry and steps as below (squares, division and square roots are done entry by entry). RMSProp replaces G with an exponential moving average of recent values, and Adam adds momentum to that.

G←G+g2,x←x−ηGg

minibatch SGD
When f is the mean of the losses of N examples, this is gradient descent that picks B examples at each step and takes one step with the mean gradient of that minibatch. ℓᵢ is the loss of example i in the minibatch. With B = 1 it is called stochastic gradient descent (SGD), and with B = N batch gradient descent.

x←x−ηB∑i=1B∇ℓi(x)

1. A function graph and its slope

A function is a rule: put in x, and you get one height out. Draw those heights from left to right and you get a line. That line is the graph.

The slope is how steep the line is at a spot. If it is +, the line goes uphill to the right. If it is −, it goes downhill to the right. If it is 0, the spot is flat (a bottom or a top). Finding the slope is called "differentiation."

Orange line and arrow: the slope where the ball is, pointing uphill · Blue arrow: the next step (the other way, step size × slope far) and its sum · Grey dots and line: spots already passed

Move over the graph to see the slope there. Click to drop a ball.

You can write: numbers, x, + − * / ^, parentheses, sin cos tan exp log sqrt abs pi. Examples: 2x^2-3, sin(2x)/x

Rolling a ball downhill: gradient descent

The ball cannot see the whole graph. It only knows the slope where it stands. So it takes one step the opposite way from the slope, which is downhill. A big step where it is steep, a small step where it is gentle. Do this again and again, and it reaches the bottom. Click the graph to drop a ball, then press "One step." The blue arrow is the next step.

Try this. ① On x², raise the step size to 1.1. The ball jumps over the bottom and ends up farther away each time. ② On "Two valleys," drop the ball on the right. It stops in the shallow valley. There is a deeper one, but the ball does not know.

2. Add inertia: momentum and Nesterov

This time the ground is a long, narrow bowl. It is steep across the narrow side and gentle along the long side. The white circle in the middle is the bottom. Three balls start from the same spot.

MethodWhat it doesThink of it as
Gradient descentTakes one step using only the slope at the current spotA person who stops and starts again at every step
MomentumKeeps the speed it already had and adds the slope to itA rolling ball. Fast, but it rolls past the bottom and swings back and forth
NesterovFixes its course using the slope at the spot its speed would reach firstA ball that looks ahead and brakes early

Click the ground to start again from that spot. Press "View from above" to see it like a map. Each band is one height (contour lines).

MethodStepsHeight nowResult

Try this. ① With the starting values, gradient descent reaches the bottom in 216 steps, momentum in 78 steps, and Nesterov in 38 steps. ② Set inertia to 0 and all three balls move the same way. ③ Raise inertia to 0.97. Momentum swings widely and actually gets slower (231 steps). Nesterov swings less (79 steps). ④ Push the step size all the way up (0.22). Gradient descent and Nesterov fly off. Momentum swings widely but still reaches the bottom in 75 steps.

The one way Nesterov differs from momentum

Speed so far Slope at the current spot Actual step
Momentum. Measures the slope at the current spot and adds it to the speed so far.
Look-ahead spot Slope there Actual step
Nesterov. Measures the slope at the spot its speed would carry it to first. If it is about to roll past the bottom, the slope there points back, so the step gets shorter.

How the formula is built: from gradient descent to Nesterov

The three methods in the lab above are one formula with pieces added one at a time. On the same long bowl, from the same start (−3.5, 2), add one piece at a time and watch how the path changes. A spot is two numbers (sideways, up-down), and the formula writes both together as x. The height of the bowl is f = 0.5 × (sideways² + 10 × up-down²). ∇f(x) is an arrow that holds the slope in each direction (the gradient). It always points up the steepest way. For this bowl, ∇f = (sideways, 10 × up-down). The g in the table of section 4 is this ∇f(x).

Press "Next" to go one step at a time. A piece is added to the formula on top (the orange background marks the new piece), the path for that formula is drawn, and the reason appears below. Paths from earlier steps stay faded. The ground is the "Long bowl" from the lab above, seen from straight above. Orange is gradient descent, blue is momentum, purple is Nesterov. The step size η and inertia μ are the starting values of the lab above (0.02 and 0.9).

  1. Step down by the slope: x ← x − ∇f(x). The slope points uphill, so subtracting it goes downhill. The slope at the start is (−3.5, 20). Subtract all of it and you get (−3.5, 2) − (−3.5, 20) = (0, −18). That is off the map, and the height goes up from 26.13 to 1620. Why: the slope tells you how steep it is, not how far to go. Up and down, the slope is 20 but the bottom is only 2 away.
  2. Multiply by a step size: x ← x − η·∇f(x). Multiply by η = 0.02 and go only 1/50 of the slope. The first step is (0.07, −0.4), and the ball reaches the bottom in 216 steps. Why: on this bowl, each step cuts the up-down distance left by 10·η (20% when η = 0.02) and the sideways distance by η (2%). If 10·η is over 1, the ball jumps over the bottom up and down. If it is over 2, every jump lands farther away and the ball flies off. So η must stay below 0.2 (at exactly 0.2 it swings between 2 and −2 forever). With η that small, the sideways distance shrinks only 2% per step. After 20 steps the ball is at (−2.34, 0.02): up-down is almost done, sideways is far from it. One step size cannot fit both the steep side and the gentle side.
  3. Remember the last step (momentum): v ← μ·v − η·∇f(x), x ← x + v. v is the last step (the speed). The new step is 0.9 (μ) times the last step plus the step from ②. With μ = 0, v = −η·∇f(x), which is the same formula as ② (in the lab above, set inertia to 0 and all three balls move the same way). Why: on the gentle sideways side, the slope points the same way at every step, so the steps pile up. If the slope stayed the same, the step would grow up to 1 + μ + μ² + … = 1 ÷ (1 − μ), which is 10 times. Here the sideways step grows from 0.07 to 0.32 by step 9, and the ball arrives in 78 steps. But the built-up speed carries it past the bottom, out to 1.03 sideways, before it comes back, and it crosses the middle line of the valley (up-down 0) 11 times.
  4. Measure the slope ahead (Nesterov): v ← μ·v − η·∇f(x + μ·v), x ← x + v. Only one thing changes: where the slope is measured. Not at the current spot x, but at x + μ·v, the spot the leftover speed would reach first. Why: when the ball is about to roll past the bottom, that look-ahead spot is already beyond the bottom, and the slope there points back. So the ball slows down before it rolls past. The distance past the bottom drops from 1.03 to 0.79 sideways, the crossings of the middle line drop from 11 to 6, and the ball arrives in 38 steps. This is the complete formula, the third row of the table in section 4.

Try this. ① In the first step, a dashed orange line runs from the start down and off the map. It lands at (0, −18). ② Press "Next" once. An orange path appears whose first step is 1/50 of the one in ①. It comes down first, then crawls sideways, and reaches the bottom in 216 steps. ③ Press it again. The blue path goes past the bottom out to 1.03 sideways and comes back (78 steps). ④ In the last step, the purple path goes past only to 0.79 and arrives in 38 steps. The faded blue ring and the solid purple ring mark the farthest spot past the bottom for each path. ⑤ In the lab above, set the step size to 0.2. Gradient descent swings up and down forever and does not reach the bottom within 500 steps. At 0.21 it flies off.

3. A different step size for each direction: AdaGrad, RMSProp, Adam

In the lab above, gradient descent is slow because it has only one step size. Fit it to the steep side, and it is too small on the gentle side. Fit it to the gentle side, and the ball flies off on the steep side. The three methods below set a separate step size for each direction. Where the slope has been large, they shrink the step. Where it has been small, they grow it.

MethodWhat it doesWeakness
AdaGradFor each direction, keeps adding up the size of every slope it has seen. Where a lot has piled up, it takes smaller stepsIt only ever adds, so the steps keep shrinking until they stop
RMSPropInstead of adding everything up, it remembers only recent slopes. It slowly forgets old onesThe steps do not shrink, so it can jitter near the bottom
AdamRMSProp plus inertia (momentum)It remembers two things, so it needs a bit more computing

At the start, all three balls head straight for the bottom. That is because they set the step for the steep side and the gentle side separately.

MethodStepsHeight nowResult

Try this. ① Lower the step size to 0.1. AdaGrad does not reach the bottom within 500 steps, because its steps shrink as slopes pile up. ② Switch to "Curved valley" (step size 0.2). RMSProp jitters near the bottom and cannot stop, but Adam gets there. ③ Raise the step size to 1. RMSProp shakes a lot.

How the step size is set: watch the bars

See, in numbers, what the three methods in the lab above remember at each step and what they divide by. There is no ball, just two directions. On the steep side the slope comes out as 20 and −20 by turns (like a ball jumping back and forth across a narrow valley). On the gentle side it is always 1. These slopes are made up, and the step size is η = 0.1. With the same slopes, gradient descent would take steps of η·g: 2 on the steep side and 0.1 on the gentle side.

g: this step's slope · G: gathered squares · m: speed (Adam only) · step: the amount taken off x. The middle vertical line is 0, a dashed outline is the previous step's bar, and the black arrow shows how much the step changed. The end of each bar is the largest value in that row over the 20 steps (separately for each method).

The formulas are the ones in the table of section 4. With the correction on, Adam uses m̂ and Ĝ instead of m and G.

Try this. ① AdaGrad's first step is 0.1 in both directions. The slopes differ by 20 times, but the steps are the same. Each time you press "Next," G grows by 400 on the steep side and by 1 on the gentle side, and the step shrinks to 0.0707, 0.0577, 0.05, down to 0.0224 at step 20. ② RMSProp's first step is 0.316, bigger than η. That is because G starts at 0 and is only 40 so far. At step 20, G is 351 and grows less as it nears 400, and the step is 0.107. ③ Adam's first step is 0.1 in both directions. At step 2, the steep side's m̂ cancels down to −1.05 and the step size drops to 0.00526, while the gentle side stays at 0.1 for all 20 steps. ④ Turn off Adam's correction. The first step is 0.316 in both directions, and on the gentle side it reaches 0.653 at step 10, more than 6 times η.

4. Everything in one table

Write the position as x, the step size as η, the inertia as μ, and the slope at that spot as g. Then:

MethodWhat it remembersOne step
Gradient descentNothingx ← x − η·g
MomentumSpeed vv ← μ·v − η·g, x ← x + v
NesterovSpeed vSame as above, but g is measured at x + μ·v
AdaGradSum of slope sizes GG ← G + g², x ← x − η·g ÷ √G
RMSPropRecent slope size GG ← 0.9·G + 0.1·g², x ← x − η·g ÷ √G
AdamSpeed m and recent size Gm ← 0.9·m + 0.1·g, G ← 0.999·G + 0.001·g², x ← x − η·m ÷ √G

The last three rows are written in a shortened form. Real implementations add a tiny number ε to the denominator, √G + ε, so they never divide by 0, and Adam also applies a bias correction for the first few steps, when m and G start out too small.

To see the first three rows (gradient descent, momentum, Nesterov) built one piece at a time, see How the formula is built (there, g is written as ∇f(x)).

The last three do this math separately for each direction (each number). Adam also has a correction that makes m and G larger in the first few steps. The labs on this page include it, and you can turn it on and off in the bar lab of section 3.

Where is it used?

It is used to train AI models. Think of "how wrong the model is" as the height. Then training means finding the bottom of that ground. In real models there are not just two directions. Millions to billions of numbers move at once. The idea is the same as the ground on this page. These methods are called "optimizers."

# In PyTorch, you pick one with a single line
torch.optim.SGD(params, lr=0.01, momentum=0.9, nesterov=True)  # Nesterov
torch.optim.Adagrad(params, lr=0.01)
torch.optim.RMSprop(params, lr=0.01)
torch.optim.Adam(params, lr=0.001)

5. In real training: the slope of a batch instead of all the data

The ground on this page is a single formula, so the slope can be measured right away. In training, the height (the loss) is the average of how wrong the model is on each of N examples. To get the exact slope, every step would have to look at all the examples. With a lot of data, one step costs too much. So each step picks B examples and moves one step using the average slope over that batch.

x ← x − η·(∇ℓ₁(x) + ∇ℓ₂(x) + … + ∇ℓB(x)) ÷ B

The examples are picked at random, so on average this slope equals the full slope, but each pick is a little off. That makes the path shake. B = 1 is stochastic gradient descent (SGD) in the narrow sense, and anything between 1 and N is a minibatch. That is where the SGD in torch.optim.SGD above gets its name. The other methods in the table of section 4 also put this batch slope in the place of g. To see how much the path shakes for each batch size, and why the shaking shrinks as the batch grows, walk it yourself on the Batch size page.

Common questions

What is Nesterov accelerated gradient (NAG)?

It is a kind of gradient descent that uses momentum. It does not use the slope where it stands now. It uses the slope a little further ahead, where its current speed would take it, and fixes its direction from there. So it slows down before it rolls past the bottom.

How are momentum and Nesterov different?

Only in where they measure the slope. Momentum measures it at the current spot. Nesterov measures it at the spot its speed would carry it to first.

How are AdaGrad and RMSProp different?

Both set a separate step size for each direction. AdaGrad keeps adding up every slope it has seen, so its steps keep getting smaller. RMSProp slowly forgets old slopes, so its steps do not die out.

What is Adam?

It takes the per-direction step sizes of RMSProp and adds the inertia of momentum. It works well without much tuning, so it is a common default in deep learning.

So which one should I use?

There is no single right answer. Most people start with Adam (or AdamW). For well-studied tasks like image classification, SGD with momentum or Nesterov is also common.

Words

Word used hereWord used in textbooks
slopederivative. With many directions, the gradient
∇f(x)the gradient of f at x. ∇ is read "nabla"
step sizelearning rate
inertiamomentum coefficient (momentum)
heightloss, objective function
bottom / shallow valleyminimum / local minimum
a different step size for each directionadaptive learning rate
way of going downoptimizer
gradient descent on batchesminibatch stochastic gradient descent (minibatch SGD). In the narrow sense, B = 1 is stochastic gradient descent (SGD), and the whole data set is batch gradient descent

Sources

← BackpropagationReinforcement learning →