Skip to content

Gradient Steps

You'll fit the same line as before by walking downhill on the error one small step at a time, and watch what a bad step size does.

About

Gradient descent is how nearly every model bigger than a line gets trained, and it's just this: measure the error, work out which way is downhill, take a small step, repeat. Doing it on a line you've already solved exactly means you know the right answer and can watch the algorithm find it, or fail to. You need the pairs from Line of Best Fit (or any 20 pairs), a loop, and a chart of the loss. What counts is your own update rule written out, a loss curve that goes down, and one that explodes because you asked it to; a library's optimizer doesn't count here.

At a glance

Per requirement
15 XP
Completion bonus
75 XP
Requirements
5
Takes
One evening
Skill level
Intermediate (months of practice)
Cost
Free
Supplies
Nothing special
Where
At home
Other people
On your own

Requirements

  1. 1
    Write the loss and its two derivatives on paper before you write any code. For a line y = mx + b with mean squared error, the derivative with respect to m is minus two times the mean, over all rows, of x times the residual, and with respect to b it's minus two times the mean residual. Write both out, including the minus signs, because a dropped sign sends you uphill. Take a photo of the page. Photo
  2. 2
    Loop 1,000 steps with a small learning rate and log the loss every 50. Start m and b at zero. Each step, compute the two gradients and subtract the learning rate times each gradient from m and b. Try 0.01 first. Print the step, m, b and the loss. If your x values are in the hundreds or thousands, scale them to roughly minus one to one first, because otherwise the step that suits b is far too big for m and the loss blows up before it settles. Take a screenshot of the log. Photo
  3. 3
    Plot the loss against the step and confirm it flattens near the exact answer. The curve should drop fast and then level off, and the final m and b should match your least-squares answer to two decimal places. If they're close but not matching, you stopped early, so run longer or raise the rate a little. Take a screenshot of the plot with the final m and b written on it. Photo
  4. 4
    Raise the learning rate until it diverges, and keep that plot. Multiply the rate by ten and run again, then by ten again. At some point the loss bounces and then climbs to infinity or NaN. That's the step overshooting the bottom of the valley and landing higher up the other side. Take a screenshot of the diverging curve beside the good one. Photo
  5. 5
    Film the line moving as it trains. Redraw the scatter plot and the current line every 20 steps, with the step count in the title. Record 20 to 30 seconds of the line swinging in from flat to fitted. Say in one sentence, in the post, at what step you'd have been happy to stop. Video