Two Routes, One Line

Machine Learning in CodeHard+10 XP+10

Two Routes, One Line

LinearRegression finds the best line in one call. Gradient descent walks there one step at a time. With more than one feature, both should land in the same place, given enough steps.

Write two_routes(rows, answers, rate, steps). Each row has the same number of features.

Route 1: gradient descent. Keep one weight per feature in an array w (all zeros at the start) and one intercept b = 0. Each step:

  • error = X @ w + b - y, for every row at once.
  • grad_w = 2 * X.T @ error / n and grad_b = 2 * error.mean(), where n is the number of rows.
  • w = w - rate * grad_w and b = b - rate * grad_b.

Repeat exactly steps times.

Route 2: the library. Fit a LinearRegression model on the same rows.

Return a dict:

  • "descent": the weights from route 1 followed by its intercept, as one list.
  • "library": coef_ followed by intercept_, as one list.

Round every number to 2 decimal places and use plain Python floats.

Examples

rows = [[1, 2], [2, 1], [3, 4], [4, 3], [5, 5]]
answers = [1.1, 7.0, 6.9, 12.1, 12.0]
rate = 0.02
steps = 5000
returns {'descent': [3.96, -1.59, 0.7], 'library': [3.96, -1.59, 0.7]}
rows = [[1, 2], [2, 1], [3, 4], [4, 3], [5, 5]]
answers = [1.1, 7.0, 6.9, 12.1, 12.0]
rate = 0.02
steps = 10
returns {'descent': [1.65, 0.82, 0.37], 'library': [3.96, -1.59, 0.7]}

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