In
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.
Guessing lines at random
- Best guess so far
- Latest guess
- Earlier guesses
- Guesses made
- 0
- Best error so far
- –
- Guesses since it improved
- –
- Lowest possible
- 6.1
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 . Every value of has an error, so we can draw the error as a curve over . For squared error that curve is a bowl.
The error as a bowl
- Slope w
- 1.00
- Steepness of the curve
- -52.5
- So to go downhill
- move right (w up)
- Error
- 119.3
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 lowers the error.
- Positive steepness: the curve rises to the right, so decreasing 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 , 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.
new value = old value − learning rate × steepness of the error
The small number
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.
Start with a flat line: , . Its error on the twelve students is 467.
The steepness of the error is in the direction and in the direction. Both are negative, so both numbers should go up. With a learning rate of :
The new line has an error of 199. One step removed more than half the error, without a single guess.
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 and : 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
Gradient descent, seen two ways
- Current line / position
- Best line
- Equal error
- Step
- 0
- Slope w
- 0.00
- Bias b
- 50.0
- Error
- 466.8
Before the first step you can drag the orange dot on the map to start somewhere else.
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 with , the chain rule gives
In words: take each student’s miss, weight it by their hours for or leave it alone for , 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
.
Gradient descent is working, but slowly. You make the learning rate much larger to speed it up. What is the worst that can happen?
Three learning rates
- 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
For this dataset the run breaks just above . 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.
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
Fewer students per step
- Current line / position
- Best line
- Equal error
- Step
- 0
- Slope w
- 0.00
- Bias b
- 50.0
- Error
- 466.8
Before the first step you can drag the orange dot on the map to start somewhere else.
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.
- 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.
The loss is , whose steepness is . Start at 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 = old minus 0.1 times .
Solution
Each step is .
- Step 1: steepness , so .
- Step 2: steepness , so .
- Step 3: steepness , so .
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.
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: .
- Step 2: steepness , so .
- Step 3: steepness , so .
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 . A learning rate of 0.5 makes that zero, landing on at once. Any rate above 1 makes the multiplier larger than 1 in size, and the run diverges.
A model starts at , . There is one example: , . The loss is . Take one gradient step with a learning rate of 0.01, and check that the loss went down.
Hint
The steepness for is and for it is . Update both from the old values.
Solution
The prediction is , so and the loss is 64.
The steepness with respect to is . With respect to it is .
Update both at once: and .
The new prediction is , and the new loss is . It fell from 64.
Write gradient descent for a line through the three points (0, 1), (2, 2) and (4, 6), starting from , with a learning rate of 0.05. Check that it arrives at the best line, and . 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 and .
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.5With 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.
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
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
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.