Downhill or Off a Cliff?

Machine Learning in CodeMedium+10 XP+10

Downhill or Off a Cliff?

A step size that is too big makes gradient descent leap past the bottom, and the error grows instead of shrinking. You want to watch that happen.

Write error_after_each_step(xs, ys, rate, steps). It fits the line y^=wx+b\hat y = w x + by^​=wx+b with the same loop as the lesson:

  • Start at w = 0 and b = 0.
  • Each step, compute the errors w * x + b - y, then grad_w (the mean of 2 * x * error) and grad_b (the mean of 2 * error) from those same errors, then update w = w - rate * grad_w and b = b - rate * grad_b.

After each step, measure the mean squared error of the new line: the mean of (w * x + b - y) ** 2.

Return a list with one number per step, in order, each rounded to 3 decimal places. Its length is steps. The starting error (before any step) is not included.

Examples

xs = [1, 2, 3, 4, 5]
ys = [2.0, 4.1, 5.9, 8.2, 9.8]
rate = 0.01
steps = 4
returns [25.534, 14.901, 8.704, 5.093]
xs = [1, 2, 3, 4, 5]
ys = [2.0, 4.1, 5.9, 8.2, 9.8]
rate = 0.1
steps = 4
returns [81.668, 152.387, 284.385, 530.758]

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