Nudge the Line Into Place

Machine Learning in CodeEasy+10 XP+10

Nudge the Line Into Place

A bakery tracks how many trays of bread it bakes (xs) and how many loaves it sells (ys). You want the straight line y^=wx+b\hat y = w x + by^​=wx+b that fits them, and you will find it the way the lesson did: by walking downhill.

Write fit_line_by_descent(xs, ys, rate, steps).

  • Start at w = 0 and b = 0.
  • Each step, work out the errors w * x + b - y for every point, using the current w and b.
  • From those same errors, work out both gradients: grad_w is the mean of 2 * x * error, and grad_b is the mean of 2 * error.
  • Then move both knobs downhill: w = w - rate * grad_w and b = b - rate * grad_b.
  • Repeat this exactly steps times. If steps is 0, nothing moves.

Return [w, b], each rounded to 3 decimal places, as plain Python floats.

Examples

xs = [1, 2, 3, 4]
ys = [3, 5, 7, 9]
rate = 0.05
steps = 1000
returns [2.0, 1.0]
xs = [1, 2, 3, 4, 5]
ys = [2.0, 4.1, 5.9, 8.2, 9.8]
rate = 0.01
steps = 1
returns [0.439, 0.12]

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