Chapter 3 // Learning from Data

Gradient Descent.

If there were no formula for the best line, how could a computer still find it?

Reading time
20 min
Data

In a formula handed us the best line for the twelve students. That was lucky. Most models in this book, and every neural network, have no such formula. What they do have is a way to measure how wrong they are.

This chapter shows how to turn “how wrong am I?” into “which way should I change?”, and then to repeat that until the model is good. The method is called gradient descent, and it is how almost all of modern machine learning is trained.

Learning by luck

Start with the simplest idea that could possibly work. Pick a slope and a bias at random. Measure the error. If it beats the best line so far, keep it. Repeat.

Figure

Guessing lines at random

1, 481.5, 532, 503, 603.5, 574, 665, 685.5, 756, 717, 828, 839, 91
  • Best guess so far
  • Latest guess
  • Earlier guesses
Guesses made
0
Best error so far
–
Guesses since it improved
–
Lowest possible
6.1
Each guess is a random slope and bias. The orange line is the best one found so far. Try it: guess once a few times, then press the 100 button three or four times. Watch how rarely the best error improves.

The first few guesses help a great deal, because almost anything beats a terrible line. After that, progress stalls. Hundreds of guesses go by without an improvement, and the best error stays well above the lowest possible.

The trouble is that each guess ignores everything learned from the previous ones. A good guess tells us roughly where good lines live, and random search throws that away. With two numbers to choose this is merely slow. With two million it is hopeless.

Feeling the slope

Here is a better idea. Imagine standing on a hillside in thick fog. You cannot see the valley, but you can feel which way the ground tilts under your feet. Step downhill, feel again, step again.

To make that concrete, freeze the bias at its best value and vary only the slope ww. Every value of ww has an error, so we can draw the error as a curve over ww. For squared error that curve is a bowl.

Figure

The error as a bowl

5.31, 6.13lowest point
Slope w
1.00
Steepness of the curve
-52.5
So to go downhill
move right (w up)
Error
119.3
0.020
The dark curve is the error for each slope w. The dashed orange line touches the curve where you are standing and shows how steep it is there. Try it: drag the dot to the left of the lowest point, then to the right, and watch the sign of the steepness flip. Then press the step button a few times.

The steepness of the curve where you stand is its derivative. Its sign is the useful part:

  • Negative steepness: the curve falls to the right, so increasing ww lowers the error.
  • Positive steepness: the curve rises to the right, so decreasing ww lowers the error.
  • Zero: the ground is flat. You are at the bottom.

In every case, moving against the sign of the steepness goes downhill. The toolkit chapter on derivatives explains how the steepness is calculated.

The update rule

That observation becomes a one-line rule. Take the current ww, subtract the steepness, and you have moved downhill. One refinement is needed: the steepness can be a big number, so we multiply it by a small number first to keep the step under control.

w  ←  w−η ∂L∂ww \;\leftarrow\; w - \eta\,\frac{\partial L}{\partial w}

new value = old value − learning rate × steepness of the error

The small number is the . The fraction is the steepness of the loss with respect to ww. Repeating this update is .

Notice a useful side effect. Far from the bottom the bowl is steep, so the steps are large. Near the bottom it flattens, so the steps shrink on their own.

ExampleOne step, with numbers

Start with a flat line: w=0w = 0, b=50b = 50. Its error on the twelve students is 467.

The steepness of the error is −64.7-64.7 in the ww direction and −34-34 in the bb direction. Both are negative, so both numbers should go up. With a learning rate of η=0.1\eta = 0.1:

w←0−0.1×(−64.7)=6.47b←50−0.1×(−34)=53.4w \leftarrow 0 - 0.1 \times (-64.7) = 6.47 \qquad b \leftarrow 50 - 0.1 \times (-34) = 53.4

The new line has an error of 199. One step removed more than half the error, without a single guess.

Checkpoint

At the current w, the steepness of the error is +8. With learning rate 0.1, what does the update do to w?

Two parameters, one map

A line has two parameters, so the error is really a surface over both ww and bb: a bowl you could pour water into. It is easiest to draw from above, like a hiking map. Each ring joins lines with the same error, and the rings close in on the lowest point.

With two parameters there are two steepnesses, one for each. Listed together they are called the . The gradient points in the direction where the error rises fastest, so each step goes the opposite way, and both parameters are updated at once:

w←w−η ∂L∂wb←b−η ∂L∂bw \leftarrow w - \eta\,\frac{\partial L}{\partial w} \qquad\qquad b \leftarrow b - \eta\,\frac{\partial L}{\partial b}
Figure

Gradient descent, seen two ways

1, 481.5, 532, 503, 603.5, 574, 665, 685.5, 756, 717, 828, 839, 91
5.31, 67lowest
  • Current line / position
  • Best line
  • Equal error
Step
0
Slope w
0.00
Bias b
50.0
Error
466.8
0.050

Before the first step you can drag the orange dot on the map to start somewhere else.

Left: the line moving through the data. Right: the same run drawn as a path on the map of the error. Every point on the map is one possible line. Try it: press Step a few times and watch both panels, then press Run. Reset, drag the starting dot to a different corner of the map, and run again.

Wherever you start, the path ends in the same place, and the line it ends on is the least-squares line from the last chapter. When further steps stop changing anything, the run has .

The two steepnesses for a line

For the mean squared error L=1n∑i(y^i−yi)2L = \frac{1}{n}\sum_i (\hat{y}_i - y_i)^2 with y^i=wxi+b\hat{y}_i = w x_i + b, the chain rule gives

∂L∂w=2n∑i(y^i−yi) xi∂L∂b=2n∑i(y^i−yi)\frac{\partial L}{\partial w} = \frac{2}{n}\sum_i (\hat{y}_i - y_i)\,x_i \qquad \frac{\partial L}{\partial b} = \frac{2}{n}\sum_i (\hat{y}_i - y_i)

In words: take each student’s miss, weight it by their hours for ww or leave it alone for bb, and average. Students the line overshoots push the parameters down; students it undershoots push them up.

Choosing the learning rate

The learning rate is the one thing gradient descent cannot work out for itself. You choose it, and the choice matters.

  • Too small, and every step is timid. The run heads the right way but needs a huge number of steps.
  • Too large, and each step jumps clean over the valley and lands higher up the other side. The error grows instead of shrinking, and the run is said to .
Predict firstCommit to a guess, then use the figure below to check it.

Gradient descent is working, but slowly. You make the learning rate much larger to speed it up. What is the worst that can happen?

Figure

Three learning rates

η = 0.005η = 0.08
  • Your learning rate
  • Small (0.005)
  • Well chosen (0.08)
Your η
0.050
Error after 40 steps
6.2
Verdict
Reaches the bottom
Breaks above
0.164
0.050
Each curve shows the error after every step, starting from the same flat line. Try it: slide the learning rate slowly upward from 0.005. Find roughly where the run is fastest, then keep going until it breaks.

For this dataset the run breaks just above η=0.164\eta = 0.164. That exact number belongs to this data and this model; a different problem has a different limit. In practice people try a few values spaced by factors of about three, such as 0.001, 0.003, 0.01, and keep the largest one that still goes down smoothly.

Checkpoint

You start training and the error goes 40, 95, 310, 1200. What is the most likely cause?

Cheaper steps

So far every step looked at all twelve students to compute the gradient. With twelve that is trivial. With twelve million it means reading the whole dataset just to move once.

The fix is to estimate the gradient from a small random handful of examples, called a . The estimate is noisy, so the path wobbles, but each step costs a tiny fraction of the full calculation and the wobbles mostly average out. This is , and it is what trains large models. One full pass through the data, in batches, is called an .

Figure

Fewer students per step

1, 481.5, 532, 503, 603.5, 574, 665, 685.5, 756, 717, 828, 839, 91
5.31, 67lowest
  • Current line / position
  • Best line
  • Equal error
Step
0
Slope w
0.00
Bias b
50.0
Error
466.8
0.030
Each step looks at

Before the first step you can drag the orange dot on the map to start somewhere else.

The same descent, but each step may use only some of the students to estimate the downhill direction. Try it: run it with all 12, then with 4, then with 1. Compare how straight the path is, and where it ends up.

With one student per step the path never quite settles. It reaches the neighbourhood of the lowest point and then jitters around it, because each single student pulls the line toward themselves. Smaller learning rates calm the jitter.

In code

The whole algorithm is a short loop. This version uses only NumPy, so nothing is hidden.

import numpy as np

hours = np.array([1, 1.5, 2, 3, 3.5, 4, 5, 5.5, 6, 7, 8, 9])
score = np.array([48, 53, 50, 60, 57, 66, 68, 75, 71, 82, 83, 91])
x = hours - hours.mean()            # measure hours from the average

w, b = 0.0, 50.0                    # starting line
eta = 0.05                          # learning rate

for step in range(200):
    miss = (w * x + b) - score      # prediction minus truth, per student
    grad_w = 2 * np.mean(miss * x)  # steepness in the w direction
    grad_b = 2 * np.mean(miss)      # steepness in the b direction
    w -= eta * grad_w               # step against the gradient
    b -= eta * grad_b

print(w, b)                         # 5.31  67.0

The slope matches the formula from the last chapter. The bias is 67 rather than 42.44 only because hours are now measured from the average: a student who studied the average amount is predicted to score 67.

Key Takeaways

  • When there is no formula for the best model, follow the slope of the loss downhill instead of guessing.
  • The update is always the same: parameter minus learning rate times the steepness of the loss.
  • The gradient is the list of steepnesses, one per parameter. All parameters step at once.
  • Too small a learning rate is slow. Too large and the run diverges.
  • Mini-batches make each step cheap by estimating the gradient from a few random examples.
You can now
  • Carry out a gradient descent update by hand.
  • Say what the gradient is and why the step goes against it.
  • Tell from a loss curve whether the learning rate is too small, too large or about right.
  • Explain what mini-batches save, and what they cost.

Exercises

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

Exerciseby hand

The loss is L(w)=(w−3)2L(w) = (w - 3)^2, whose steepness is 2(w−3)2(w - 3). Start at w=0w = 0 with a learning rate of 0.1 and take three steps. How does the distance from the best value change with each step?

Hint

Each step is: new ww = old ww minus 0.1 times 2(w−3)2(w - 3).

Solution

Each step is w←w−0.1×2(w−3)w \leftarrow w - 0.1 \times 2(w - 3).

  • Step 1: steepness −6-6, so w=0+0.6=0.6w = 0 + 0.6 = 0.6.
  • Step 2: steepness −4.8-4.8, so w=0.6+0.48=1.08w = 0.6 + 0.48 = 1.08.
  • Step 3: steepness −3.84-3.84, so w=1.08+0.384=1.464w = 1.08 + 0.384 = 1.464.

The distance from 3 goes 3, 2.4, 1.92, 1.536. Each step multiplies it by 0.8. The steps get smaller on their own as the slope flattens, which is why a fixed learning rate can still settle.

Exerciseby hand

Same loss, same start, but a learning rate of 1.1. Take three steps. Then say which learning rate would reach the lowest point in a single step.

Hint

Use the same rule with 1.1. For the last part, find the rate that makes the step land exactly on 3.

Solution
  • Step 1: w=0−1.1×(−6)=6.6w = 0 - 1.1 \times (-6) = 6.6.
  • Step 2: steepness 7.27.2, so w=6.6−7.92=−1.32w = 6.6 - 7.92 = -1.32.
  • Step 3: steepness −8.64-8.64, so w=−1.32+9.504=8.184w = -1.32 + 9.504 = 8.184.

The distance from 3 goes 3, 3.6, 4.32, 5.184. Each step jumps over the lowest point and lands further away on the other side. The run diverges.

In general each step multiplies the distance by 1−2η1 - 2\eta. A learning rate of 0.5 makes that zero, landing on w=3w = 3 at once. Any rate above 1 makes the multiplier larger than 1 in size, and the run diverges.

Exerciseby hand

A model y^=wx+b\hat{y} = wx + b starts at w=1w = 1, b=0b = 0. There is one example: x=2x = 2, y=10y = 10. The loss is (y^−y)2(\hat{y} - y)^2. Take one gradient step with a learning rate of 0.01, and check that the loss went down.

Hint

The steepness for ww is 2(y^−y)x2(\hat{y} - y)x and for bb it is 2(y^−y)2(\hat{y} - y). Update both from the old values.

Solution

The prediction is 1×2+0=21 \times 2 + 0 = 2, so y^−y=−8\hat{y} - y = -8 and the loss is 64.

The steepness with respect to ww is 2(y^−y)x=2×(−8)×2=−322(\hat{y} - y)x = 2 \times (-8) \times 2 = -32. With respect to bb it is 2(y^−y)=−162(\hat{y} - y) = -16.

Update both at once: w=1+0.01×32=1.32w = 1 + 0.01 \times 32 = 1.32 and b=0+0.01×16=0.16b = 0 + 0.01 \times 16 = 0.16.

The new prediction is 1.32×2+0.16=2.81.32 \times 2 + 0.16 = 2.8, and the new loss is (2.8−10)2=51.84(2.8 - 10)^2 = 51.84. It fell from 64.

Exercisein code

Write gradient descent for a line through the three points (0, 1), (2, 2) and (4, 6), starting from w=0w = 0, b=0b = 0 with a learning rate of 0.05. Check that it arrives at the best line, w=1.25w = 1.25 and b=0.5b = 0.5. Then change the learning rate to 0.2 and run it again.

Hint

Inside the loop: compute the misses, then both steepnesses as averages, then update ww and bb.

Solution
import numpy as np

x = np.array([0, 2, 4.0])
y = np.array([1, 2, 6.0])

w, b, eta = 0.0, 0.0, 0.05
for step in range(2000):
    miss = w * x + b - y
    w -= eta * 2 * np.mean(miss * x)   # steepness of the MSE with respect to w
    b -= eta * 2 * np.mean(miss)       # and with respect to b

print(round(w, 3), round(b, 3))        # 1.25 0.5

With a learning rate of 0.2 the numbers grow without limit and the program prints nan. For this data, anything above about 0.137 diverges.

Exercisewith the figure

In the figure “Three learning rates”, find the largest learning rate at which the run still settles. Then go a little higher. Describe what the error does in each case, and compare your limit with the 0.164 given in the chapter.

Hint

Just below the limit the error still falls, but not smoothly.

Solution

Just below 0.164 the error bounces: each step overshoots the valley and lands on the other side, a little lower than before, so it still gets there in the end. Just above, each bounce lands a little higher than the last, and the error grows without limit.

The fastest runs are at rates somewhat below the limit, where steps are large and overshoot only slightly. That is why the usual advice is to find the rate at which training breaks and then back off.

Going further

Why we measured hours from the average

With raw hours, the error bowl is a long, narrow valley: steep across, almost flat along. Gradient descent then zigzags across the steep walls and crawls along the floor, needing thousands of steps. Subtracting the average makes the bowl nearly round, and the same run takes about fifty. Rescaling features so that the loss is well shaped is one of the most useful habits in machine learning, and the chapter on preparing data returns to it.

Is the bottom always the true bottom?

For a line with squared error, yes. The loss is , a single bowl, so downhill always leads to the one lowest point. Neural networks have bumpy losses with many dips. Gradient descent then finds a low point rather than the lowest, which in practice turns out to be good enough.

Smarter steps

Plain gradient descent uses one fixed learning rate for every parameter. Methods such as momentum and Adam adapt the step as they go and are what most people use for neural networks. They have later in the book.

References and further reading

  • H. Kinsley and D. Kukieła, Neural Networks from Scratch in Python, chapters 6 to 10, nnfs.io. The random-search experiment follows their idea.
  • T. Ma and A. Ng, CS229 Lecture Notes, section 1.1, cs229.stanford.edu.
  • A. Karpathy and others, CS231n notes: Optimization, cs231n.github.io.

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 3.1Learning by luck
  3. 3.2Feeling the slope
  4. 3.3The update rule
  5. 3.4Two parameters, one map
  6. 3.5Choosing the learning rate
  7. 3.6Cheaper steps
  8. 3.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