The Normal Equation: Best Line in One Step

Classic MLMedium+15 XP+15

The Normal Equation: Best Line in One Step

Gradient descent finds the best-fitting line by walking downhill. For ordinary linear regression you don't have to walk at all — there's an exact formula that lands on the answer in one step.

It's called the normal equation:

β=(XTX)−1XTy\beta = (X^T X)^{-1} X^T yβ=(XTX)−1XTy

The only setup it needs is a column of 1s glued to the front of your features. That extra column is what lets the model have an intercept: its coefficient is the value the line predicts when every real feature is zero.

Task: write fit_linear(X, y) returning [intercept, coef_1, coef_2, ...], each rounded to 4 decimal places.

  • X is a list of rows, each row holding that example's features (without the column of ones — you add that yourself). y is the list of targets.
  • The returned list starts with the intercept, followed by one coefficient per feature, in the same order as the columns of X.
  • There are always more rows than features and no duplicate columns, so XTXX^T XXTX is always invertible.
  • NumPy is available. np.linalg.solve(A, b) solves Aβ=bA\beta = bAβ=b and is both faster and numerically steadier than building an explicit inverse with np.linalg.inv.

When the data lies exactly on a line, this returns that line's slope and intercept with no error at all — which makes it a very satisfying thing to test.

Fitting the Least-Squares Line

Slope (b₁):0.50
Intercept (b₀):2.00

Regression Line & Residuals (SSE = 3.250)

00224466

Fitting Verdict

Model: ŷ = 2.00 + 0.50x
Sum of Squared Errors: 3.250
Try to minimize the SSE by adjusting the sliders or click 'Show Best Fit'.

Examples

X = [[1], [2], [3]]
y = [3, 5, 7]
returns [1.0, 2.0]
X = [[0], [1], [2], [3]]
y = [1, 2, 3, 5]
returns [0.8, 1.3]

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