Linear models · lesson 3 of 12
Parts in this lesson
Adw = 2 * np.mean(error * kg)the gradient for w
Bw = w - lr * dwone step downhill
Cfor step in range(1000): ...the training loop
Dax.set_yscale('log')a loss curve on a log scale

Gradient descent

Last updated

Searching a grid finds the bottom of the bowl for two numbers, but not for the millions in a neural network. Gradient descent does: stand anywhere, work out which way is downhill, take a small step, and repeat. This lesson derives the gradient of the squared-error loss, checks it, and trains linear regression with a loop you write yourself in NumPy. The same loop, with a different model inside, trains everything later in the course.

By the end of this lesson you can

  • Derive ∂ℒ/∂w and ∂ℒ/∂b for the squared-error loss, and check them numerically
  • Write the gradient descent update and a training loop in NumPy
  • Read a loss curve, and recognise a learning rate that’s too large

Derive the gradient

Lesson 1.8 showed that the gradient points uphill, the steepest way, and that its opposite points downhill. To walk down the loss bowl, you need the gradient of

ℒ(w,b)=1n∑i=1n(wxi+b−yi)2.

Call each error ei=wxi+b−yi. The loss is a mean of ei2, and by the chain rule (lesson 1.7), the derivative of ei2 is 2ei times the derivative of ei. That inner derivative is xi with respect to w, and 1 with respect to b. So

∂ℒ∂w=2n∑i=1neixi,∂ℒ∂b=2n∑i=1nei.

In words: for b, twice the mean error; for w, twice the mean of each error times its input. If the line is too low, the errors are negative, both derivatives are negative, and stepping against them raises w and b.

A derivation is easy to get wrong, so check it against lesson 1.8's numerical derivative, which nudges each number a tiny amount each way:

descent.ipynb

The formula and the nudges agree: −316.25 for w and −58.75 for b, at the line w=50, b=0. Always check a gradient like this the first time you write it.

The update rule

Gradient descent takes a step against the gradient:

w←w−η∂ℒ∂w,b←b−η∂ℒ∂b

The arrow means "becomes". η (the Greek letter eta) is the learning rate: how big a step to take, as a fraction of the gradient. In code it's lr. Where the bowl is steep the gradient is big and the steps are long; near the bottom the gradient shrinks towards zero, so the steps shrink too, and the walk settles.

Try it. Choose a start (click the map, or use the sliders) and take steps:

Gradient descent on the bowlthe ball, the line and the loss curve move together
×3040506070-4004080w (pesos per kg)b (pesos)pricekgloss (log scale) after 0 steps1010⁶
Learning rate:

w = 35, b = 70: price = 35 × kg + 70, with loss 3375. The bottom, marked ×, is 19.03.

With learning rate 0.02 the ball heads quickly into the valley, then slides along it to the bottom. With 0.03 it zig-zags across the valley but still gets there. With 0.05 it blows up; step 5 says why.

The training loop

Training is the update rule in a loop. Each time round, four things happen, and every model in this course is trained by some version of them:

  1. Predict with the current numbers.
  2. Measure the errors (and the loss).
  3. Work out the gradient of the loss.
  4. Step each number against its gradient.

Drawn as a UML activity diagram (the filled dot is the start, the ringed dot the end, and the diamonds are where the flow joins and where it decides, with the condition for each way out in brackets):

[yes][no]Start the weightsat 0Predictŷ = wx + bMeasure the errorsŷ − y, and the lossWork out thegradientStep against itw ← w − η ∂L/∂wStepsleft?

Press Walk through it to follow the work round the chart, one stop at a time.

  1. Start: set every weight and the bias to 0.
  2. Predict every example with the current weights.
  3. Measure the errors and the loss.
  4. Work out the gradient of the loss.
  5. Step each weight against its gradient, scaled by the learning rate.
  6. If there are steps left, go back to 2; otherwise stop.
The training loop as a UML activity diagram. In UML’s notation: the filled dot is where it starts and the ringed dot where it ends; rounded boxes are actions; a diamond with a question is a decision, with the condition for each way out in [brackets], and an empty diamond is a merge, where a way back joins the flow; Pink arrows go back to an earlier action.
descent.ipynb

Starting from w=0, b=0, 1,000 steps arrive at w=51.84, b=20.40, with loss 19.03: the same line as np.polyfit in lesson 3.1. The printout shows how it got there: the loss was 9,022 after the first step and 132 after the third, then crept the rest of the way. That's typical: big gains early, slow progress near the bottom, as the gradient gets smaller.

Plotting the loss curve

The loss curve, the loss after each step, is the first thing to look at whenever a model trains:

descent.ipynb

The loss falls over a range of several hundredfold, so the plot uses a log scale (lesson 1.1) to show the whole fall. A healthy curve drops quickly, then flattens. A curve still falling at the end says "train longer"; one that bounces or rises says the learning rate is too big.

Wrong way: a learning rate that’s too big

A bigger learning rate sounds faster. Here's 0.1 instead of 0.02:

descent.ipynb

After one step the loss is 2.9 million, much worse than at the start. By step 200 it's 2.6×10303, close to the largest number a float can hold; then it's inf, infinity, and then nan, "not a number", because the next step works out infinity minus infinity. Nothing raises an error. The training just quietly produces garbage.

What happened: the step was so big that it jumped right over the bottom of the valley to a point higher up the other side. There the gradient was bigger still, so the next jump was bigger again, and so on, further out each time. In the figure in step 2, it's the 0.05 button.

The fix is a smaller learning rate. There's no universal right value; it depends on how steep the bowl is (lesson 3.7 shows how to make that easier). The usual habit: try a few values, ten times apart (0.1, 0.01, 0.001), and watch the loss curve. And whenever you see nan in a loss, suspect the learning rate first.

Check what you learned

At the current line, ∂ℒ/∂w=−316. Which way does gradient descent move w?
Predict, then check with the figure: you start at the same point with learning rate 0.03 instead of 0.02. What does the ball do?
Your loss prints 412.7, 9,031.2, 2.1e+06, … then inf, then nan. What should you try first?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning