SafeZone AI Learn
Learn/ Machine Learning/ Supervised Learning · lesson 1 of 8

Linear regression

Least squares from three angles — optimization, geometry, statistics — because each angle answers a question the others cannot: how to compute it, why the residuals behave as they do, and when to trust it.

Linear regression is where supervised learning’s whole conceptual toolkit appears for the first time: a model class, a loss, an estimator, and three different lenses that each make something visible the others hide. Most treatments pick one lens. A practitioner needs all three, because debugging a regression means knowing which lens the symptom belongs to.

The model and the loss

Data: nn pairs (xi,yi)(x_i, y_i) with xiRdx_i \in \mathbb{R}^d. Model: predictions linear in the parameters,

y^=Xβ,XRn×d\hat{y} = X\beta, \qquad X \in \mathbb{R}^{n \times d}

(XX‘s first column is all-ones for the intercept). “Linear” constrains the parameters, not the inputs — replace the columns of XX with polynomials, splines or interactions and everything in this lesson survives untouched; that flexibility is exactly what the widget below exploits. The estimator is ordinary least squares (OLS):

β^=argminβ  12yXβ2.\hat{\beta} = \arg\min_\beta \; \tfrac{1}{2}\lVert y - X\beta \rVert^2 .

Lens 1 — optimization: the normal equations

The objective is a convex quadratic (its Hessian is XX0X^\top X \succeq 0 — the convexity lesson of the Optimization module), so setting the gradient to zero is sufficient:

β12yXβ2=XXβXy=0XXβ^=Xy\nabla_\beta \tfrac{1}{2}\lVert y - X\beta \rVert^2 = X^\top X \beta - X^\top y = 0 \quad\Longrightarrow\quad \boxed{\,X^\top X\, \hat\beta = X^\top y\,}

— the normal equations. If XX has full column rank, β^=(XX)1Xy\hat\beta = (X^\top X)^{-1} X^\top y exists and is unique. Two computational regimes follow:

RegimeMethodCost
dd small–moderate (≲ 10⁴)solve the normal equations (Cholesky) or, better, QR on XXO(nd2)O(nd^2)
dd huge or nn streaminggradient descent / SGD on the same objectiveO(nd)O(nd) per pass

The Optimization module is not a separate subject here: the GD route’s iteration count scales with κ(XX)\kappa(X^\top X), and κ(XX)=κ(X)2\kappa(X^\top X) = \kappa(X)^2 — conditioning is squared by forming the normal equations, which is why numerical libraries prefer QR and why unstandardized features (one in [0,1][0,1], one in [0,104][0, 10^4]) can make gradient-based fitting absurdly slow. If you did exercise 5 of the gradient-descent lesson, this is the payoff.

Lens 2 — geometry: prediction is projection

XβX\beta ranges over the column space of XX — a dd-dimensional plane inside Rn\mathbb{R}^n. Minimizing yXβ\lVert y - X\beta \rVert means finding the point of that plane closest to yy: orthogonal projection. The fitted values are

y^=X(XX)1Xy  =  Hy,\hat{y} = X(X^\top X)^{-1}X^\top y \;=\; H y,

with HH the hat matrix (it puts the hat on yy): symmetric, idempotent (H2=HH^2 = H), a projection. The residual e=yy^=(IH)ye = y - \hat y = (I - H)y is the perpendicular component, which forces

Xe=0:X^\top e = 0 :

residuals are exactly orthogonal to every column of X — mean-zero (the intercept column), and uncorrelated with every feature, by construction. This is why “I see structure in my residuals” is such a powerful diagnostic: any pattern the residuals show against a variable is structure the model could not represent, since anything representable was projected out. And tr(H)=d\operatorname{tr}(H) = d counts the model’s degrees of freedom — a number that returns, fractionally, when ridge regression bends this projection in the next lesson.

The dashed green curve is the true function that generated the data; the blue curve is the least-squares fit. At degree 1–2 the model underfits (residual sticks stay long and patterned — the projection lens says the pattern is unrepresentable structure). Around degree 3–5 it tracks the truth. Push the degree toward 10–12 and watch train MSE fall while test MSE explodes — the fit contorts through the training points. You are watching the capacity axis of the bias–variance trade-off; the next lesson measures it properly. (Leave the penalty on “none” here — ridge and lasso get their own lesson.)

Lens 3 — statistics: when is OLS the right estimator?

Assume the data really are y=Xβ+εy = X\beta^\ast + \varepsilon with E[ε]=0\mathbb{E}[\varepsilon] = 0, Cov(ε)=σ2I\operatorname{Cov}(\varepsilon) = \sigma^2 I. Then:

  • Unbiasedness: E[β^]=β\mathbb{E}[\hat\beta] = \beta^\ast — substitute and use (XX)1XX=I(X^\top X)^{-1}X^\top X = I.
  • Covariance: Cov(β^)=σ2(XX)1\operatorname{Cov}(\hat\beta) = \sigma^2 (X^\top X)^{-1}. Read this matrix: nearly-collinear columns make XXX^\top X nearly singular, so coefficient variances blow up along the associated directions — the statistical face of the same ill-conditioning that slowed gradient descent. One pathology, three lenses.
  • Gauss–Markov: among all linear unbiased estimators, OLS has minimal variance — it is BLUE. Note what is not assumed: normality. Gaussian errors add only the exact finite-sample distributions (tt-tests on coefficients) and make OLS equal to maximum likelihood, since minimizing squared error is maximizing a Gaussian log-likelihood.

The fine print is where real datasets live: heteroscedastic errors break the covariance formula (weighted least squares or robust/sandwich errors), correlated errors break it worse (time series — its own track), and squared loss’s sensitivity to outliers is a choice, inherited from the Gaussian assumption, swappable for Huber or absolute loss at the price of closed forms. And Gauss–Markov’s “best” is conditional on unbiased — the next lesson exists precisely because a little bias, bought wisely, can be a bargain.

import numpy as np

# The three computational routes to the same estimator
beta_ne, *_ = np.linalg.lstsq(X, y, rcond=None)        # QR/SVD route — use this
beta_ch = np.linalg.solve(X.T @ X, X.T @ y)            # normal equations (κ²!)

beta_gd = np.zeros(X.shape[1])                          # the optimization route
for _ in range(2000):
    beta_gd -= 1e-2 * X.T @ (X @ beta_gd - y) / len(y)

Exercises

Work these before the next lesson

  1. Derive the normal equations by expanding yXβ2\lVert y - X\beta\rVert^2 and differentiating. Where exactly does convexity enter to make the stationary point a global minimum?
    Solution

    Worked solutions are part of Premiumunlock all of them for £5/month →

  2. 4 more exercises — each with a worked solution — are part of Premium. Unlock everything for £5/month →

References

  • T. Hastie, R. Tibshirani, J. Friedman, The Elements of Statistical Learning, 2nd ed., ch. 3 — the canonical treatment of all three lenses (free PDF from the authors).
  • G. James et al., An Introduction to Statistical Learning, ch. 3 — the gentler companion, with labs.
  • G. Strang, Linear Algebra and Learning from Data, 2019 — the projection picture, done properly.