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
With the bias trick (), the data matrix and targets , the likelihood is .
Derivation 1: maximum likelihood
The negative log-likelihood is (Maximum Likelihood). Its gradient is ; setting it to zero:
(valid when 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 is positive semidefinite, so the problem is convex and the stationary point is the global minimum.
Derivation 3: projection
ranges over the column space of . The closest point to is its orthogonal projection, characterized by a residual orthogonal to every column: , the same normal equations (The Geometry of Least Squares).
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 , QR does not, and the SVD-based lstsq also copes with rank-deficient .
Uncertainty of the estimate
Because is linear in the Gaussian , it is itself Gaussian with covariance . Its diagonal gives the standard errors that statistics packages report.
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'sLinearRegression(which calls an SVD/QR-based solver) (Linear Regression).statsmodels.OLSreports the standard errors computed from .- For huge , SGD on the squared loss reaches the same solution without forming .
Exercises
Exercise 1: Normal equations by hand
Fit to , , .
Answer
, .
Solution
Solving: and .
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 . The first column of is , so .
Exercise 3: Check Exercise 1 (code)
Solve Exercise 1 with np.linalg.lstsq and print the residuals.
Answer
with residuals summing to 0.
Solution
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…
- exactly
Why prefer QR or SVD solvers over forming ?
- They give a different model
- Forming squares the condition number and loses accuracy
- They are always slower
- Normal equations do not work for regression
Under Gaussian noise, the covariance of is…
- zero