Skip to content
Course outline

Chapter 1: Supervised Learning

Linear Regression

Model, loss function, the normal equation and gradient descent — the foundation for every model that follows.

Linear regression predicts a continuous target yy from a feature vector x\mathbf{x}. It is simple, fast and easy to interpret, and almost every idea in this course (loss functions, optimisation, regularisation) appears here first.

The model

Given nn training examples {(x(i),y(i))}i=1n\{(\mathbf{x}^{(i)}, y^{(i)})\}_{i=1}^{n} with x(i)∈Rd\mathbf{x}^{(i)} \in \mathbb{R}^d, we assume

y^=hθ(x)=θ0+θ1x1+⋯+θdxd=θ⊤x,\hat{y} = h_{\boldsymbol\theta}(\mathbf{x}) = \theta_0 + \theta_1 x_1 + \dots + \theta_d x_d = \boldsymbol\theta^\top \mathbf{x},

where we prepend x0=1x_0 = 1 to every example so the intercept θ0\theta_0 fits into the dot product.

Stacking all examples as rows gives the design matrix X∈Rn×(d+1)X \in \mathbb{R}^{n \times (d+1)} and the prediction vector y^=Xθ\hat{\mathbf{y}} = X\boldsymbol\theta.

Loss function

We measure how wrong the model is with the mean squared error (MSE):

J(θ)=12n∑i=1n(θ⊤x(i)−y(i))2=12n∥Xθ−y∥22.J(\boldsymbol\theta) = \frac{1}{2n} \sum_{i=1}^{n} \left( \boldsymbol\theta^\top \mathbf{x}^{(i)} - y^{(i)} \right)^2 = \frac{1}{2n} \lVert X\boldsymbol\theta - \mathbf{y} \rVert_2^2 .

The factor 12\tfrac{1}{2} is only there to cancel the 2 that appears when we differentiate.

Solving for the parameters

The normal equation

JJ is a convex quadratic, so its minimum is where the gradient vanishes:

∇θJ=1nX⊤(Xθ−y)=0⟹θ⋆=(X⊤X)−1X⊤y.\nabla_{\boldsymbol\theta} J = \frac{1}{n} X^\top (X\boldsymbol\theta - \mathbf{y}) = \mathbf{0} \quad\Longrightarrow\quad \boldsymbol\theta^\star = (X^\top X)^{-1} X^\top \mathbf{y}.

This is exact but costs O(d3)O(d^3) to invert X⊤XX^\top X, which becomes slow when dd is large.

Gradient descent

Instead of solving in one step, we repeatedly move against the gradient with a learning rate α\alpha:

θ←θ−α⋅1nX⊤(Xθ−y).\boldsymbol\theta \leftarrow \boldsymbol\theta - \alpha \cdot \frac{1}{n} X^\top (X\boldsymbol\theta - \mathbf{y}).

Implementation in Python

import numpy as np


def fit_normal_equation(X: np.ndarray, y: np.ndarray) -> np.ndarray:
    """Closed-form solution. X must already include a column of ones."""
    return np.linalg.solve(X.T @ X, X.T @ y)


def fit_gradient_descent(
    X: np.ndarray, y: np.ndarray, lr: float = 0.1, epochs: int = 1_000
) -> np.ndarray:
    n, d = X.shape
    theta = np.zeros(d)
    for _ in range(epochs):
        grad = X.T @ (X @ theta - y) / n
        theta -= lr * grad
    return theta


rng = np.random.default_rng(0)
x = rng.uniform(-1, 1, size=200)
y = 3.0 + 2.0 * x + rng.normal(scale=0.1, size=200)
X = np.column_stack([np.ones_like(x), x])

print(fit_normal_equation(X, y))   # ≈ [3.0, 2.0]
print(fit_gradient_descent(X, y))  # ≈ [3.0, 2.0]

Notice that we use np.linalg.solve instead of computing an explicit inverse — it is faster and numerically more stable.

Evaluating the model

The coefficient of determination tells us what fraction of the variance in yy the model explains:

R2=1−∑i(y(i)−y^(i))2∑i(y(i)−yˉ)2.R^2 = 1 - \frac{\sum_i (y^{(i)} - \hat{y}^{(i)})^2}{\sum_i (y^{(i)} - \bar{y})^2}.
MetricFormulaInterpretation
MSE1n∑(y−y^)2\frac{1}{n}\sum (y - \hat y)^2Average squared error, in squared units of yy
RMSEMSE\sqrt{\text{MSE}}Same units as yy
R2R^2see above1 is perfect, 0 is no better than predicting yˉ\bar y

Summary

  • Linear regression models y^=θ⊤x\hat y = \boldsymbol\theta^\top\mathbf{x} and minimises the MSE.
  • The normal equation gives an exact solution; gradient descent scales to large dd.
  • Always scale features and evaluate on held-out data.

Exercise. Show that X⊤XX^\top X is invertible if and only if the columns of XX are linearly independent. What happens to the normal equation when two features are identical?