Gradient Descent
Chapter Fifty-One
Syllabus topic Module 2, "Gradient descent"
Pages 277 to 283 of 591
In one line
Gradient descent finds the lowest point of a curve by repeatedly taking a small step downhill.
In the wording a student can write in an examination: gradient descent minimises a differentiable loss function by iteratively moving each parameter in the direction opposite to the gradient, the vector of partial derivatives. The update rule is
w <- w - rate * gradient
where the learning rate controls the step size. It converges to a global minimum for a convex loss and to a local minimum otherwise. A rate too small converges slowly; a rate too large overshoots and may diverge.
What the derivative is, for this purpose
MU's own word is intuitive, so the calculus is reduced to the one fact needed.
The derivative of a function at a point is the slope of the curve there: how much the output changes for a small change in the input.
- Positive slope: the curve is going up as you move right, so the low ground is to the left.
- Negative slope: the curve is going down as you move right, so the low ground is to the right.
- Zero slope: the curve is flat, so you are at the bottom, the top, or a shelf.
The update rule follows from those three lines and nothing else. Subtract the slope: if the slope is positive, subtracting moves left; if negative, subtracting moves right; if zero, nothing moves. Downhill in both cases, with one rule. That is the whole of the intuition MU asks for.
The gradient is the same idea with several parameters: one partial derivative for each, collected into a vector. Each parameter is moved by its own slope, so each moves in the direction that reduces the loss fastest for it alone.
Four steps by hand, then convergence
The loss is f(w) = (w - 3)**2 + 2, a valley whose lowest point is 2, at w = 3. Its slope is 2(w - 3).
# Gradient descent, worked by hand for four steps and then run to convergence,
# and the learning rate shown too small, right, and too large.
# The loss: f(w) = (w - 3)**2 + 2, whose least value is 2 at w = 3.
def f(w):
return (w - 3) ** 2 + 2
def slope(w):
"""The derivative, 2(w - 3). At w = 3 it is 0: that is the bottom."""
return 2 * (w - 3)
print("the loss is f(w) = (w - 3)**2 + 2. its slope is f'(w) = 2(w - 3).")
print("the rule is: w <- w - rate * slope(w).")
print()
print("FOUR STEPS BY HAND, starting at w = 10 with a rate of 0.2")
w = 10.0
print(" step | w before | slope | rate*slope | w after | loss")
for step in range(1, 5):
g = slope(w)
move = 0.2 * g
nxt = w - move
print(" %2d | %8.4f | %5.2f | %10.4f | %8.4f | %8.4f"
% (step, w, g, move, nxt, f(nxt)))
w = nxt
print()
print("run on to convergence, printing every fifth step:")
w = 10.0
for step in range(1, 41):
w -= 0.2 * slope(w)
if step % 5 == 0:
print(" step %2d: w = %.6f loss = %.6f slope = %+.6f"
% (step, w, f(w), slope(w)))
print()
print("THE LEARNING RATE decides everything. 30 steps from w = 10:")
print(" rate | w after 30 steps | loss | what happened")
for rate in (0.001, 0.05, 0.2, 0.9, 1.0, 1.05):
w = 10.0
diverged = False
for _ in range(30):
w -= rate * slope(w)
if abs(w) > 1e12:
diverged = True
break
if diverged:
note = "DIVERGED, w ran away to infinity"
print(" %5.3f | %16s | %8s | %s" % (rate, "-", "-", note))
continue
err = abs(w - 3)
if rate == 1.0:
note = "OSCILLATES between 10 and -4 forever"
elif err > 7.0:
note = "OVERSHOOTING, and getting worse every step"
elif err > 1.0:
note = "still crawling, nowhere near"
elif err < 1e-4:
note = "arrived"
else:
note = "close, a few more steps would do it"
print(" %5.3f | %16.6f | %8.4f | %s" % (rate, w, f(w), note))
print()
print("too small and it never arrives; too large and it overshoots and diverges;")
print("at exactly 1.0 it jumps to the mirror image of where it was, forever.")Gradient Descent
the loss is f(w) = (w - 3)**2 + 2. its slope is f'(w) = 2(w - 3).
the rule is: w <- w - rate * slope(w).
FOUR STEPS BY HAND, starting at w = 10 with a rate of 0.2
step | w before | slope | rate*slope | w after | loss
1 | 10.0000 | 14.00 | 2.8000 | 7.2000 | 19.6400
2 | 7.2000 | 8.40 | 1.6800 | 5.5200 | 8.3504
3 | 5.5200 | 5.04 | 1.0080 | 4.5120 | 4.2861
4 | 4.5120 | 3.02 | 0.6048 | 3.9072 | 2.8230
run on to convergence, printing every fifth step:
step 5: w = 3.544320 loss = 2.296284 slope = +1.088640
step 10: w = 3.042326 loss = 2.001792 slope = +0.084653
step 15: w = 3.003291 loss = 2.000011 slope = +0.006583
step 20: w = 3.000256 loss = 2.000000 slope = +0.000512
step 25: w = 3.000020 loss = 2.000000 slope = +0.000040
step 30: w = 3.000002 loss = 2.000000 slope = +0.000003
step 35: w = 3.000000 loss = 2.000000 slope = +0.000000
step 40: w = 3.000000 loss = 2.000000 slope = +0.000000
THE LEARNING RATE decides everything. 30 steps from w = 10:
rate | w after 30 steps | loss | what happened
0.001 | 9.591956 | 45.4539 | still crawling, nowhere near
0.050 | 3.296738 | 2.0881 | close, a few more steps would do it
0.200 | 3.000002 | 2.0000 | arrived
0.900 | 3.008666 | 2.0001 | close, a few more steps would do it
1.000 | 10.000000 | 51.0000 | OSCILLATES between 10 and -4 forever
1.050 | 125.145816 | 14921.6003 | OVERSHOOTING, and getting worse every step
too small and it never arrives; too large and it overshoots and diverges;
at exactly 1.0 it jumps to the mirror image of where it was, forever.Gradient Descent
The four hand steps are what a paper asks for. At w = 10 the slope is 14, so the step is 0.2 * 14 = 2.8 and w becomes 7.2. The loss falls from 51 to 19.64. Each step the slope is smaller, so the step is smaller, and the descent slows as it approaches the bottom without being told to.
That automatic slowing is the property worth naming. Nothing schedules it: the slope IS the distance from the minimum here, so the step shrinks in proportion. By step 30 w is 3.000002 and the slope is 0.000003.
The learning rate, in both directions
Read the last table, because every row is a different failure or success.
0.001 is too small. After 30 steps w has moved from 10 to 9.59. It is going the right way and will take thousands of steps.
0.2 arrives, to six decimal places, in 30 steps.
1.0 oscillates forever. From w = 10 the slope is 14 and the step is 14, landing at -4. From -4 the slope is -14 and the step takes it back to 10. It never diverges and it never converges; it jumps between the two points forever, and the table shows it exactly back at 10 after 30 steps.
1.05 diverges. Each step overshoots by slightly more than it came, so w grows without bound: 125.1 after 30 steps, and the loss is 14,921.
There is a threshold and for this loss it is exactly 1.0. Below it the method converges; at it the method cycles; above it the method diverges. For a general quadratic loss the threshold is 2 divided by the curvature, and the practical consequence is the one to remember: a loss that is sharply curved in some direction forces a small rate on every direction, which is why real optimisation uses the refinements below.
Gradient Descent
The three variants, which is what a paper asks for
The loss in machine learning is a sum over the training examples, and the variants differ in how many examples are used per step.
| Batch | Stochastic (SGD) | Mini-batch | |
|---|---|---|---|
| Examples per step | all of them | one | a small group, often 32 to 256 |
| Direction of the step | the exact gradient | a very noisy estimate | a reasonable estimate |
| Steps per pass over the data | 1 | n | n / batch size |
| Cost per step | high | tiny | moderate |
| Path to the minimum | smooth | erratic | fairly smooth |
| Can escape a shallow local minimum | no | yes, the noise helps | somewhat |
| Used in practice | rarely, only on small data | rarely, alone | almost always |
The reason mini-batch wins is worth one sentence: a noisy estimate of the gradient computed a hundred times is worth far more than an exact one computed once, because the errors partly cancel while the hundred steps make real progress.
One epoch means one complete pass through the training data. It is the unit training is usually reported in, and it is not the same as a step.
Why it does not always find the best answer
Three honest limits, and a paper can ask for any.
Local minima. On a loss with several valleys, gradient descent settles in whichever one it started above. The loss in this chapter is convex, a single valley, so the starting point does not matter; a neural network's loss is not, and the starting point does matter.
Saddle points and plateaus. Places where the gradient is nearly zero but the point is not a minimum. In many dimensions these are far more common than local minima, and they stall progress without stopping it.
It needs the loss to be differentiable. A loss with a jump in it has no gradient at the jump. This is why classification is usually trained on a smooth surrogate such as cross-entropy rather than directly on the number of mistakes, which is a step function and has zero gradient almost everywhere.
The standard refinements, named
None is on MU's label and all four appear in any library, so one line each.
- Momentum: add a fraction of the previous step to this one, so the parameter keeps moving in a consistent direction and crosses flat regions faster.
- AdaGrad, RMSProp: give each parameter its own rate, scaled down for parameters whose gradients have been large, so one sharply curved direction no longer forces a small rate on all of them.
- Adam: momentum and a per-parameter rate together. It is the usual default.
- A learning rate schedule: start large and reduce the rate over time, so early steps are fast and later ones settle.
Gradient Descent
Where it appears in the rest of this book
The cross-chapter list, because this is the one method that recurs.
| Chapter | What gradient descent fits |
|---|---|
The Artificial Neuron and the Perceptron | the weights of one unit |
The Multilayer Network and Backpropagation | every weight of the network, with the gradient computed by the chain rule |
The Soft Margin and the Kernel | the hinge loss, in one standard solver |
Maximum Likelihood Estimation | the parameters, when no closed form exists |
Q-Learning | the update is a gradient step on a squared temporal-difference error |
And the one place it is not used: the straight line of What Machine Learning Is has a closed-form solution, so nothing is iterated. Gradient descent is what you use when there is no formula, and most models in this module have none.
Distinctions
| Batch | Stochastic | |
|---|---|---|
| Gradient per step from | all examples | one example |
| Step direction | exact | noisy |
| Progress per pass | one step | n steps |
| Escapes shallow minima | no | yes |
| Learning rate too small | Too large | |
|---|---|---|
| Behaviour | converges, very slowly | overshoots, then diverges |
| In the table | 0.001, reached 9.59 after 30 steps | 1.05, reached 125.1 |
| At exactly the threshold | 1.0, oscillates forever |
| Convex loss | Non-convex loss | |
|---|---|---|
| Valleys | one | many |
| Where it converges to | the global minimum | a local minimum |
| Starting point matters | no | yes |
| Example | this chapter's, and linear regression | a neural network's |
What it does not mean
The gradient does not point at the minimum. It points in the direction of steepest increase at the current point, and the step is the opposite direction. On a long narrow valley that is nearly across the valley rather than along it.
A zero gradient does not mean a minimum. It may be a maximum, a saddle point or a plateau.
A smaller learning rate is not safer in every sense. It cannot diverge, and it may never arrive.
Gradient descent does not need the loss to be the error. It minimises whatever differentiable function it is given, which is how the penalty of Regularization is included: add it to the loss and its gradient joins the step.
Stochastic gradient descent is not an approximation to be apologised for. Its noise helps it escape shallow minima, and many small noisy steps beat one exact one.
It is not always necessary. A closed-form solution, where one exists, is exact and faster.
Quick revision
- Update rule:
w <- w - rate * gradient. Subtracting the slope moves downhill whichever way the slope points. - The gradient is the vector of partial derivatives, one per parameter.
- Four hand steps from
w = 10at rate 0.2: slope 14 gives 7.2, then 5.52, 4.512, 3.9072, with the loss falling 51, 19.64, 8.35, 4.29, 2.82. The steps shrink by themselves because the slope shrinks. - Learning rate: 0.001 crawls, 0.2 arrives, 1.0 oscillates between 10 and -4 forever, 1.05 diverges to 125.1. The threshold here is exactly 1.0, and in general
2 / curvature. - Variants: batch (all examples, exact, slow), stochastic (one, noisy, fast), mini-batch (a group, and what is actually used). One epoch is one pass over the data.
- Limits: local minima on a non-convex loss, saddle points and plateaus, and the loss must be differentiable, which is why classification uses a smooth surrogate.
- Refinements: momentum, AdaGrad and RMSProp, Adam, learning rate schedules.
- Used to fit the perceptron, a neural network by backpropagation, the hinge loss, maximum likelihood where no closed form exists, and the Q-learning update. Not used where a closed form exists.
Gradient Descent
Test yourself
1. State the update rule and explain why subtracting the gradient moves downhill. w <- w - rate * gradient. The gradient is the slope, which points uphill: positive slope means the low ground is to the left and negative slope means it is to the right. Subtracting therefore moves left when the slope is positive and right when it is negative, which is downhill in both cases.
2. Work the first two steps for f(w) = (w - 3)2 + 2 from w = 10 with a rate of 0.2.** The slope is 2(w - 3). At w = 10 it is 14, so the step is 2.8 and w becomes 7.2, where the loss is 19.64. At 7.2 the slope is 8.4, so the step is 1.68 and w becomes 5.52, where the loss is 8.3504.
3. Why do the steps get smaller without anything scheduling them? Because the step is the rate times the slope, and the slope shrinks as the minimum is approached. For this loss the slope is exactly twice the distance from the minimum, so the step shrinks in proportion to how far there is still to go.
4. Describe what happens at learning rates of 0.001, 1.0 and 1.05 on this loss. At 0.001 it converges correctly but far too slowly, reaching only 9.59 after thirty steps. At exactly 1.0 it jumps from 10 to minus 4 and back forever, neither converging nor diverging. At 1.05 each step overshoots by more than it came, so the parameter grows without bound, reaching 125.1 after thirty steps.
5. Distinguish batch, stochastic and mini-batch gradient descent, and say which is used. Batch uses every training example for each step, giving the exact gradient at high cost. Stochastic uses one example, giving a very noisy direction very cheaply. Mini-batch uses a small group, giving a reasonable direction at moderate cost, and it is what is used in practice, because many approximate steps make more progress than one exact one.
Gradient Descent
6. Give three reasons gradient descent may fail to find the best answer. On a non-convex loss it settles in whichever valley it started above, so the starting point decides the result. It stalls at saddle points and plateaus where the gradient is nearly zero but the point is not a minimum. And it requires a differentiable loss, so a loss such as the count of mistakes, which is a step function, cannot be used directly.
7. Why is the straight line of the first chapter not fitted by gradient descent? Because least squares for a linear model has a closed-form solution, which gives the exact answer in one calculation. Gradient descent is for losses with no formula, which is the case for almost every other model in this module.
The rest of this subject
These notes are cut from the University's printed syllabus. Open the syllabus itself, or the past papers, for the same subject.