When the Nudges Stop Mattering

Machine Learning in CodeMedium+20 XP+20

When the Nudges Stop Mattering

In Gradient Descent by Hand the loop ran exactly 500 times. Nobody knows in advance how many steps a line will need, so real training loops decide for themselves when to stop. They stop when the nudges stop mattering.

Fit the line y^=wx+b\hat y = w x + by^​=wx+b to nnn points by gradient descent on the mean squared error. This is the same loop as in the lesson:

errori=wxi+b−yi\text{error}_i = w x_i + b - y_ierrori​=wxi​+b−yi​ gradw=1n∑i=1n2 xi errori,gradb=1n∑i=1n2 errori\text{grad}_w = \frac{1}{n}\sum_{i=1}^{n} 2\, x_i\, \text{error}_i, \qquad \text{grad}_b = \frac{1}{n}\sum_{i=1}^{n} 2\, \text{error}_igradw​=n1​i=1∑n​2xi​errori​,gradb​=n1​i=1∑n​2errori​

A nudge is how far a knob moves in one step: Δw=rate×gradw\Delta w = \text{rate} \times \text{grad}_wΔw=rate×gradw​ and Δb=rate×gradb\Delta b = \text{rate} \times \text{grad}_bΔb=rate×gradb​. The step itself is w←w−Δww \leftarrow w - \Delta ww←w−Δw and b←b−Δbb \leftarrow b - \Delta bb←b−Δb.

Task: write fit_until_settled(xs, ys, rate, tol, max_steps).

  • Start at w=0w = 0w=0 and b=0b = 0b=0.
  • In every step, compute all the errors with the current www and bbb, then work out both nudges from those errors, and only then move both knobs.
  • After a step, if both nudges were smaller than tol in size (ignore their sign), stop. That step counts.
  • Never take more than max_steps steps, even if the nudges have not settled.

Return a tuple (w, b, steps). w and b are the final values, each rounded to 4 decimal places, and steps is the number of steps taken, as an integer. Return plain Python numbers.

A cap on the number of steps is not optional in real code. With a learning rate that is far too large, the nudges grow instead of shrinking, and without a cap the loop would never end.

Walking Downhill, One Step at a Time

Step size stays fixed at α = 0.30 here.
-8-4048
new x = old x − α × slope
5.950 = 7.000 − 0.30 × 3.500
Steps taken: 0 · Loss now: 14.250

The slope tells you which way is uphill, so you subtract it to head downhill. Near the edge the ground is steep and the steps are long. As the ground flattens the slope shrinks, so the steps shrink with it, and the walk eases into the bottom instead of shooting past it.

Examples

xs = [0, 1, 2, 3]
ys = [1, 3, 5, 7]
rate = 0.1
tol = 0.001
max_steps = 1000
returns (2.0071, 0.9848, 20)
xs = [1, 2, 3, 4, 5]
ys = [3.1, 4.9, 7.2, 8.8, 11.1]
rate = 0.04
tol = 0.0005
max_steps = 5000
returns (2.0001, 1.0137, 187)

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run