Equations · Standard statistics; least squares goes back to Legendre (1805) and Gauss (1809)

The normal equation for linear regression, explained

The closed-form answer to linear regression: the coefficients that minimize the sum of squared errors ∥y−Xβ∥2\|\mathbf{y} - X\boldsymbol{\beta}\|^2. It comes from setting that loss's gradient to zero, which gives the "normal equations" X⊤Xβ=X⊤yX^\top X \boldsymbol{\beta} = X^\top \mathbf{y}.

β^=(X⊤X)−1X⊤y\hat{\boldsymbol{\beta}} = \left(X^\top X\right)^{-1} X^\top \mathbf{y}

Open in the decoder →

Term by term

  1. XX

    The design matrix: one row per example, one column per feature. A column of ones is usually included so the first coefficient is the intercept.

  2. y\mathbf{y}

    The targets, one per example.

  3. X⊤XX^\top X

    A small square matrix (d×dd \times d) of feature inner products. It is invertible when the columns of XX are linearly independent.

  4. (…)−1(\ldots)^{-1}

    The matrix inverse. In code, solve the linear system rather than forming the inverse: it is faster and more accurate.

  5. β^\hat{\boldsymbol{\beta}}

    The estimated coefficients; the hat marks an estimate. ML papers often call them w\mathbf{w} or θ\boldsymbol{\theta}.

Shapes

A small worked example

Fit a line to (0,1),(1,3),(2,5)(0, 1), (1, 3), (2, 5). With an intercept column, X=(101112)X = \begin{pmatrix} 1 & 0 \\ 1 & 1 \\ 1 & 2 \end{pmatrix}, X⊤X=(3335)X^\top X = \begin{pmatrix} 3 & 3 \\ 3 & 5 \end{pmatrix}, X⊤y=(9,13)X^\top \mathbf{y} = (9, 13). Solving gives β^=(1,2)\hat{\boldsymbol{\beta}} = (1, 2): the line y=1+2xy = 1 + 2x, which fits these points exactly.

In code

import numpy as np

X = np.array([[1, 0], [1, 1], [1, 2]], dtype=float)
y = np.array([1, 3, 5], dtype=float)
beta = np.linalg.solve(X.T @ X, X.T @ y)      # [1. 2.]
beta, *_ = np.linalg.lstsq(X, y, rcond=None)  # more stable: avoids forming X^T X

Every symbol in it

W∈Rm×n\mathbf{W} \in \mathbb{R}^{m \times n}Bold uppercase (matrix)x∈Rd\mathbf{x} \in \mathbb{R}^{d}Bold lowercase (vector)x⊤y\mathbf{x}^\top \mathbf{y}TransposeA−1A^{-1}Inversey^\hat{y}Hat (estimate)β1,β2\beta_1, \beta_2Beta

Other equations