Return to the current

Least Squares Regression - Examples

Linear least squares estimates the parameters of a linear model by minimizing the sum of squared residuals. This article derives the solution and implements it.

ENFR

The idea

Given observations (xi,yi)(x_i,y_i), simple linear regression looks for a line y=mx+by=mx+b. A residual is the vertical difference yi(mxi+b)y_i-(mx_i+b) between an observation and the prediction.

Points, residuals and their fitted line

Least squares chooses mm and bb by minimizing the sum of squared residuals:

E(m,b)=i=1n(yi(mxi+b))2.E(m,b)=\sum_{i=1}^{n}\left(y_i-(mx_i+b)\right)^2.

Squaring prevents positive and negative residuals from cancelling and penalizes large errors. For nonconstant input values, this objective is convex and has a unique minimum.

Contours of the squared-error objective around its minimum

One explanatory variable

For a simple regression, differentiating E(m,b)E(m,b) with respect to mm and bb gives

m^=i=1n(xixˉ)(yiyˉ)i=1n(xixˉ)2,b^=yˉm^xˉ.\hat m=\frac{\sum_{i=1}^n(x_i-\bar x)(y_i-\bar y)}{\sum_{i=1}^n(x_i-\bar x)^2},\qquad \hat b=\bar y-\hat m\bar x.

The denominator is nonzero when the observed xix_i are not all identical.

Several explanatory variables

For nn observations and pp explanatory variables, collect the observations in a design matrix XRn×(p+1)X\in\mathbb R^{n\times(p+1)}. Its first column contains ones for the intercept; each remaining column contains one feature. Put the unknown coefficients in βRp+1\beta\in\mathbb R^{p+1} and the observed targets in yRny\in\mathbb R^n:

y=Xβ+ε.y=X\beta+\varepsilon.

How observations, coefficients and predictions form the design matrix equation

The least-squares estimator is

β^=arg minβXβy22.\hat\beta=\operatorname*{arg\,min}_{\beta}\|X\beta-y\|_2^2.

The gradient is

βXβy22=2XT(Xβy).\nabla_{\beta}\|X\beta-y\|_2^2=2X^T(X\beta-y).

At a minimum it vanishes, which gives the normal equations

XTXβ^=XTy.X^TX\hat\beta=X^Ty.

If XX has full column rank, XTXX^TX is invertible and

β^=(XTX)1XTy.\hat\beta=(X^TX)^{-1}X^Ty.

Without full column rank, minimizers may not be unique. The minimum-norm solution is β^=X+y\hat\beta=X^+y, where X+X^+ is the Moore–Penrose pseudoinverse. Numerical software normally uses a QR or singular-value decomposition instead of explicitly computing (XTX)1(X^TX)^{-1}.

Python example

The following example generates noisy observations around y=2x+3y=2x+3 and solves the regression with numpy.linalg.lstsq:

import numpy as np

rng = np.random.default_rng(42)
x = np.linspace(0, 10, 100)
y = 2 * x + 3 + rng.normal(0, 1, len(x))

X = np.column_stack((x, np.ones(len(x))))
coefficients, residuals, rank, singular_values = np.linalg.lstsq(
    X, y, rcond=None
)

slope, intercept = coefficients
predictions = X @ coefficients
print(slope, intercept)

Noisy generated observations following a linear tendency

The same construction works with more features: add one column to XX for each feature. The fitted object then becomes a hyperplane in the feature space; it is not obtained by intersecting separate hyperplanes.

Residuals measured vertically between observations and predictions