Skip to content

2.2 Linear regression

ready≈ 8.5 hoursNeeds: 2.1, 1.3, 1.1Unlocks: 2.3, 2.5
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (Regression fitter)
  4. 4 Do
  5. 5 Check

Linear regression predicts y^=w⊤x\hat y = \mathbf{w}^\top\mathbf{x}, with a constant 1 prepended to every input so that w0w_0 is the intercept. Stack the inputs as rows of X\mathbf{X} and the loss L(θ)L(\boldsymbol{\theta})lossThe scalar we minimise; lower is better. Often an average over training examples.Introduced in 1.6 Optimization. is 1n∥Xw−y∥2\frac1n\lVert\mathbf{X}\mathbf{w}-\mathbf{y}\rVert^2 (CS229 notes §1.2; MML §9.2).

Geometry first. Xw\mathbf{X}\mathbf{w} ranges over the column space of X\mathbf{X}. The closest such vector to y\mathbf{y} is its orthogonal projection, so the residual y−Xw\mathbf{y}-\mathbf{X}\mathbf{w} must be perpendicular to every column. That is the projection condition from module 1.1, and it gives the normal equations X⊤Xw=X⊤y\mathbf{X}^\top\mathbf{X}\mathbf{w}=\mathbf{X}^\top\mathbf{y} (MML §9.2.1, eq. 9.12, and §9.4). The derivation below reaches them by calculus instead, and both routes agree.

Solve, don’t invert. Computing (X⊤X)−1(\mathbf{X}^\top\mathbf{X})^{-1} explicitly is slower and less accurate than solving the system. Forming X⊤X\mathbf{X}^\top\mathbf{X} squares the condition number, so when columns are nearly dependent the answer loses digits. Production code uses QR or the SVD, which is what np.linalg.lstsq does (NumPy, lstsq). If two features are exact copies, X⊤X\mathbf{X}^\top\mathbf{X} is singular and there is no unique answer at all.

The same problem by gradient descent. The loss is a quadratic bowl with Hessian 2nX⊤X\frac2n\mathbf{X}^\top\mathbf{X}. Module 1.6 then says exactly when gradient descent converges: η<1/λmax⁡(X⊤X/n)\eta < 1/\lambda_{\max}(\mathbf{X}^\top\mathbf{X}/n), and elongated bowls (very different eigenvalues) converge slowly (UDL §6.1). In the regression fitter, watch the contours on the right and the path that follows them. Neural networks have no closed form, so this route is the one that scales.

Why squared error? If y=w⊤xy = \mathbf{w}^\top\mathbf{x} plus Gaussian noise, then maximising the likelihood of the data is the same as minimising squared error (CS229 notes §1.3). Module 2.4 makes that recipe general.

The normal equations from ∇L = 0step 1 of 5
  1. L(w)=1n(Xw−y)⊤(Xw−y)=1n(w⊤X⊤Xw−2y⊤Xw+y⊤y)L(\mathbf{w}) = \tfrac1n(\mathbf{X}\mathbf{w}-\mathbf{y})^\top(\mathbf{X}\mathbf{w}-\mathbf{y}) = \tfrac1n\left(\mathbf{w}^\top\mathbf{X}^\top\mathbf{X}\mathbf{w} - 2\mathbf{y}^\top\mathbf{X}\mathbf{w} + \mathbf{y}^\top\mathbf{y}\right)

Regression fitter

Least squares, with the loss surface beside the fit

Static view on small screens. Open this page on a laptop to interact.

drag the points · red: residuals loss surface: w₀ (intercept) → , w₁ (slope) ↑
fit: y = 0.047 + 0.621 x MSE 0.1591 (minimum 0.1591)

The closed form jumps straight to the bottom of the bowl (the dot on the right). Drag a point far away: squared error lets one outlier pull the whole line.

Left: draggable data points, the fitted line and the residuals. Right: contours of the mean squared error over the intercept and slope, with the least-squares minimum marked. In gradient descent mode the right panel shows the path of the weights for a chosen learning rate and number of steps, and the readout gives the largest stable learning rate. Keyboard: Tab to a data point and move it with the arrow keys (Shift for bigger steps); Tab through the buttons and sliders.

Fit linear regression both ways: by the normal equations, and by gradient descent with your own hand-derived gradient. Then measure the fit with R². The tests compare you against numpy.linalg.lstsq and find the exact learning rate at which your gradient descent starts to diverge.

Linear regression stubs/m2_2_linear_regression.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m2_2_linear_regression.py and run mlc check 2.2. The tests are identical; import the results on the progress page.

Hints · loss_and_grad 0/3 revealed
Hints · fit_gd 0/3 revealed

Locally: mlc check 2.2.

1. At the least-squares solution, the residual vector y − Xw is…
2. Two of your features are identical copies. What happens to XᵀX?
3. Why prefer np.linalg.solve or lstsq over np.linalg.inv(X.T @ X) @ X.T @ y?
4. For the MSE loss, λ_max(XᵀX/n) = 4. Which learning rate diverges?
5. R² = 0 means your model…
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.