# Chapter 3: Gradient Descent

> Finding the best fit by taking small steps downhill. Opening question: If there were no formula for the best line, how could a computer still find it?

From *The Book of Machine Learning*, a free interactive machine learning textbook. Interactive version, with figures to use: https://thebookofml.com/gradient-descent/

In [the last chapter](https://thebookofml.com/linear-regression/) 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.

> **Interactive figure: Guessing lines at random.** 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.
> (Use it at https://thebookofml.com/gradient-descent/)

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.

**Note:** One small change from the last chapter: here we measure hours from the class average, 4.6. The bias b then means "the score of a student who studied the average amount". The end of the chapter explains why this helps.

## 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 $w$. Every value of $w$ has an error, so we can draw the error as a curve over $w$. For squared error that curve is a bowl.

> **Interactive figure: The error as a bowl.** 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.
> (Use it at https://thebookofml.com/gradient-descent/)

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 $w$ lowers the error.
- **Positive** steepness: the curve rises to the right, so decreasing $w$ 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](/derivatives-and-gradients/) explains how the steepness is calculated.

## The update rule

That observation becomes a one-line rule. Take the current $w$, 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 \;\leftarrow\; w - \eta\,\frac{\partial L}{\partial w}
$$

The small number η is the learning rate. The fraction is the steepness of the loss L with respect to $w$. Repeating this update is gradient descent.

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.

**Example: One step, with numbers**

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

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

$$
w \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.

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

- Increases it by 0.8 — A positive steepness means the error rises as w grows, so w has to go down, not up.
- Decreases it by 0.8 **(correct)** — The update is w − 0.1 × 8, so w drops by 0.8. Positive steepness means downhill is to the left.
- Decreases it by 8 — That forgets the learning rate. The step is the steepness times η, which is 0.8.

## Two parameters, one map

A line has two parameters, so the error is really a surface over both $w$ and $b$: 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. 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 \leftarrow w - \eta\,\frac{\partial L}{\partial w}
\qquad\qquad
b \leftarrow b - \eta\,\frac{\partial L}{\partial b}
$$

> **Interactive figure: Gradient descent, seen two ways.** 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.
> (Use it at https://thebookofml.com/gradient-descent/)

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 converged.

**Derivation: The two steepnesses for a line**

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

$$
\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 $w$ or leave it alone for $b$, 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 diverge.

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

- It reaches the best line sooner, and nothing else changes — Up to a point, yes. But there is a limit, and past it something quite different happens.
- It stops just short of the best line — Stopping short is what a rate that is too small looks like when the run ends early. Too large fails in another way.
- The error grows with every step **(correct)** — Each step jumps over the bottom of the valley and lands higher up the other side. The figure shows the exact rate at which this starts.

> **Interactive figure: Three learning rates.** 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.
> (Use it at https://thebookofml.com/gradient-descent/)

For this dataset the run breaks just above $\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.

**Check your understanding:** You start training and the error goes 40, 95, 310, 1200. What is the most likely cause?

- The learning rate is too small — A small learning rate is slow, but the error would still creep downward.
- The learning rate is too large **(correct)** — Each step overshoots the valley by more than the last, so the error grows. Lower the learning rate.
- The model has converged — A converged run has an error that has stopped changing, not one that is growing.

## 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 mini-batch. 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 stochastic gradient descent, and it is what trains large models. One full pass through the data, in batches, is called an epoch.

> **Interactive figure: Fewer students per step.** 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.
> (Use it at https://thebookofml.com/gradient-descent/)

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.

**Common mistake: Training without watching the loss**

A run that has gone wrong rarely announces it. The code finishes, a model comes out, and it is bad. Always record the loss at every step and look at the curve. A loss that climbs or jumps about means the learning rate is too large. A loss that falls in a straight, shallow line and is still falling at the end means the learning rate is too small or the run too short. A loss that has gone flat has converged. The curve takes ten seconds to plot and answers most questions about a training run.

## In code

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

```python
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.

## What you should now be able to do

- 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

### Exercise (by hand)

The loss is $L(w) = (w - 3)^2$, whose steepness is $2(w - 3)$. Start at $w = 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 $w$ = old $w$ minus 0.1 times $2(w - 3)$.

**Solution:**

Each step is $w \leftarrow w - 0.1 \times 2(w - 3)$.

- Step 1: steepness $-6$, so $w = 0 + 0.6 = 0.6$.
- Step 2: steepness $-4.8$, so $w = 0.6 + 0.48 = 1.08$.
- Step 3: steepness $-3.84$, so $w = 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.

### Exercise (by 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 \times (-6) = 6.6$.
- Step 2: steepness $7.2$, so $w = 6.6 - 7.92 = -1.32$.
- Step 3: steepness $-8.64$, so $w = -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\eta$. A learning rate of 0.5 makes that zero, landing on $w = 3$ at once. Any rate above 1 makes the multiplier larger than 1 in size, and the run diverges.

### Exercise (by hand)

A model $\hat{y} = wx + b$ starts at $w = 1$, $b = 0$. There is one example: $x = 2$, $y = 10$. The loss is $(\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 $w$ is $2(\hat{y} - y)x$ and for $b$ it is $2(\hat{y} - y)$. Update both from the old values.

**Solution:**

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

The steepness with respect to $w$ is $2(\hat{y} - y)x = 2 \times (-8) \times 2 = -32$. With respect to $b$ it is $2(\hat{y} - y) = -16$.

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

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

### Exercise (in code)

Write gradient descent for a line through the three points (0, 1), (2, 2) and (4, 6), starting from $w = 0$, $b = 0$ with a learning rate of 0.05. Check that it arrives at the best line, $w = 1.25$ and $b = 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 $w$ and $b$.

**Solution:**

```python
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.

### Exercise (with 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 convex, 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 [their own chapter](https://thebookofml.com/optimizers/) later in the book.

## References

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

## Next

Gradient descent will fit whatever model you hand it as closely as it can. That raises a question that sounds too obvious to ask. Is the model that fits the data most closely the best one? The next chapter shows that it is not.
