Fit linear regression in one line with the normal equation

Linear regression finds weights w and a bias b so that X @ w + b is as close as possible to y in squared error. For small problems you can solve it exactly instead of iterating.

Write fit_linear(X, y) that returns (w, b). Add a column of ones to X for the bias and solve (Xb.T Xb) theta = Xb.T y.

Use np.linalg.solve, not an explicit inverse.

Signaturedef fit_linear(X, y)

Understand the idea

Linear regression looks for the weights that make predictions as close as possible to the targets in squared error. For small problems you can solve for them exactly with one linear system, the normal equation, instead of training step by step. Add a column of ones so the model can learn an intercept; without it the line must pass through the origin. Worked example: x = [0, 1, 2], y = [1, 3, 5]. Xb has rows [0, 1], [1, 1], [2, 1]. Xb^T Xb = [[5, 3], [3, 3]] and Xb^T y = [13, 9]. Solve 5w + 3b = 13 and 3w + 3b = 9: subtracting gives 2w = 4, so w = 2 and b = 1. That fits y = 2x + 1 exactly. Rule: theta = solve(Xb^T Xb, Xb^T y); the last entry is b. Use a solver rather than an explicit inverse, which is less stable. Quick baselines and many statistics tools use this closed form.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: recovers weightsfit_linear(_X, _y)[0]
  • Sample 2: recovers biasfit_linear(_X, _y)[1]
  • Test 3: 1D linefit_linear([[0.0], [1.0], [2.0]], [1.0, 3.0, 5.0])