TExcelTAD
Home › Math for Machine Learning › Linear Regression and Least Squares

Linear Regression and Least Squares

Linear regression is where the whole toolbox meets: a linear model (linear algebra), Gaussian noise (probability), a likelihood to maximize (models meet data), and a gradient set to zero (vector calculus). This lesson derives the least-squares solution three ways and shows how to compute it robustly.

The model

y=θTx+ϵ,ϵ∼N(0,σ2)y = \boldsymbol{\theta}^T\mathbf{x} + \epsilon, \qquad \epsilon \sim \mathcal{N}(0, \sigma^2)

With the bias trick (x0=1x_0 = 1), the data matrix X∈RN×DX \in \mathbb{R}^{N \times D} and targets y\mathbf{y}, the likelihood is p(y∣X,θ)=N(y∣Xθ,σ2I)p(\mathbf{y} \mid X, \boldsymbol{\theta}) = \mathcal{N}(\mathbf{y} \mid X\boldsymbol{\theta}, \sigma^2I).

Derivation 1: maximum likelihood

The negative log-likelihood is 12σ2∥y−Xθ∥2+const\frac{1}{2\sigma^2}\lVert \mathbf{y} - X\boldsymbol{\theta} \rVert^2 + \text{const} (Maximum Likelihood). Its gradient is −1σ2(y−Xθ)TX-\frac{1}{\sigma^2}(\mathbf{y} - X\boldsymbol{\theta})^TX; setting it to zero:

XTXθ=XTy  ⟹  θML=(XTX)−1XTyX^TX\boldsymbol{\theta} = X^T\mathbf{y} \implies \boldsymbol{\theta}_{\text{ML}} = (X^TX)^{-1}X^T\mathbf{y}

(valid when XX has full column rank). The noise variance estimate is the mean squared residual.

Derivation 2: calculus of the squared error

The same equations come from minimizing the sum of squared residuals directly; the Hessian 2XTX2X^TX is positive semidefinite, so the problem is convex and the stationary point is the global minimum.

Derivation 3: projection

XθX\boldsymbol{\theta} ranges over the column space of XX. The closest point to y\mathbf{y} is its orthogonal projection, characterized by a residual orthogonal to every column: XT(y−Xθ)=0X^T(\mathbf{y} - X\boldsymbol{\theta}) = \mathbf{0}, the same normal equations (The Geometry of Least Squares).

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
N = 100
size = rng.uniform(40, 200, N); age = rng.uniform(0, 50, N)
price = 50 + 2.0 * size - 1.5 * age + rng.normal(0, 15, N)
X = np.column_stack([np.ones(N), size, age])
theta_normal = np.linalg.solve(X.T @ X, X.T @ price)
theta_lstsq = np.linalg.lstsq(X, price, rcond=None)[0]
Q, R = np.linalg.qr(X)
theta_qr = np.linalg.solve(R, Q.T @ price)
print("normal equations:", np.round(theta_normal, 4))
print("lstsq (SVD):     ", np.round(theta_lstsq, 4))
print("QR:              ", np.round(theta_qr, 4))
resid = price - X @ theta_normal
print("sigma_ML:", round(np.sqrt(np.mean(resid**2)), 3), "  R^2:", round(1 - resid @ resid / np.sum((price - price.mean())**2), 4))
normal equations: [50.0473  1.9802 -1.4866]
lstsq (SVD):      [50.0473  1.9802 -1.4866]
QR:               [50.0473  1.9802 -1.4866]
sigma_ML: 16.602   R^2: 0.9692

All three solvers agree here. They differ in robustness: the normal equations square the condition number of XX, QR does not, and the SVD-based lstsq also copes with rank-deficient XX.

Uncertainty of the estimate

Because θML=(XTX)−1XTy\boldsymbol{\theta}_{\text{ML}} = (X^TX)^{-1}X^T\mathbf{y} is linear in the Gaussian y\mathbf{y}, it is itself Gaussian with covariance σ2(XTX)−1\sigma^2(X^TX)^{-1}. Its diagonal gives the standard errors that statistics packages report.

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
N = 100
X = np.column_stack([np.ones(N), rng.uniform(0, 10, N)])
theta_true = np.array([1.0, 0.5])
estimates = []
for _ in range(3000):                                     # many datasets with the same X
    y = X @ theta_true + rng.normal(0, 2.0, N)
    estimates.append(np.linalg.solve(X.T @ X, X.T @ y))
estimates = np.array(estimates)
print("empirical std of estimates:", np.round(estimates.std(axis=0), 4))
print("theory sigma*sqrt(diag((X^T X)^-1)):", np.round(2.0 * np.sqrt(np.diag(np.linalg.inv(X.T @ X))), 4))
empirical std of estimates: [0.4123 0.0697]
theory sigma*sqrt(diag((X^T X)^-1)): [0.4096 0.0697]

In software

  • np.linalg.lstsq, scipy.linalg.lstsq, scikit-learn's LinearRegression (which calls an SVD/QR-based solver) (Linear Regression).
  • statsmodels.OLS reports the standard errors computed from σ2(XTX)−1\sigma^2(X^TX)^{-1}.
  • For huge NN, SGD on the squared loss reaches the same solution without forming XTXX^TX.

Exercises

Exercise 1: Normal equations by hand

Fit y=θ0+θ1xy = \theta_0 + \theta_1x to (0,1)(0, 1), (1,3)(1, 3), (2,4)(2, 4).

Answer

θ0=76\theta_0 = \frac{7}{6}, θ1=32\theta_1 = \frac{3}{2}.

Solution
XTX=[3335],XTy=[811]X^TX = \begin{bmatrix} 3 & 3 \\ 3 & 5 \end{bmatrix}, \quad X^T\mathbf{y} = \begin{bmatrix} 8 \\ 11 \end{bmatrix}

Solving: θ1=3⋅11−3⋅83⋅5−9=96=32\theta_1 = \frac{3 \cdot 11 - 3 \cdot 8}{3 \cdot 5 - 9} = \frac{9}{6} = \frac{3}{2} and θ0=8−3⋅323=76\theta_0 = \frac{8 - 3 \cdot \frac{3}{2}}{3} = \frac{7}{6}.

Exercise 2: Residuals sum to zero

Why do the residuals of a least-squares fit with an intercept always sum to 0?

Answer

Because the residual is orthogonal to the column of ones.

Solution

The normal equations say XTr=0X^T\mathbf{r} = \mathbf{0}. The first column of XX is 1\mathbf{1}, so 1Tr=∑nrn=0\mathbf{1}^T\mathbf{r} = \sum_n r_n = 0.

Exercise 3: Check Exercise 1 (code)

Solve Exercise 1 with np.linalg.lstsq and print the residuals.

Answer

(1.1667,1.5)(1.1667, 1.5) with residuals summing to 0.

Solution
python · try it yourself
import numpy as np
X = np.array([[1.0, 0], [1, 1], [1, 2]]); y = np.array([1.0, 3, 4])
theta = np.linalg.lstsq(X, y, rcond=None)[0]
r = y - X @ theta
print(np.round(theta, 4), np.round(r, 4), round(r.sum(), 10) + 0)
[1.1667 1.5   ] [-0.1667  0.3333 -0.1667] 0.0

Test yourself

The least-squares solution satisfies…

  1. Xθ=yX\boldsymbol{\theta} = \mathbf{y} exactly
  2. XTXθ=XTyX^TX\boldsymbol{\theta} = X^T\mathbf{y}
  3. θ=XTy\boldsymbol{\theta} = X^T\mathbf{y}
  4. XTθ=yX^T\boldsymbol{\theta} = \mathbf{y}

Why prefer QR or SVD solvers over forming (XTX)−1(X^TX)^{-1}?

  1. They give a different model
  2. Forming XTXX^TX squares the condition number and loses accuracy
  3. They are always slower
  4. Normal equations do not work for regression

Under Gaussian noise, the covariance of θML\boldsymbol{\theta}_{\text{ML}} is…

  1. σ2I\sigma^2 I
  2. σ2(XTX)−1\sigma^2(X^TX)^{-1}
  3. XTXX^TX
  4. zero