Linear Regression
- Galton (1886) coined regression studying hereditary height; Legendre formalized least squares in 1805
- Foundational supervised learning algorithm for continuous outputs
- The closed-form solution (normal equations) makes it unique among ML algorithms
Linear regression fits the line (or hyperplane) through data that minimizes the sum of squared vertical distances from each point to the line. It learns one weight per input feature plus a bias term.
- Foundation for logistic regression, regularized regression (ridge/lasso), and GLMs
- Normal equations are a special case of the projection theorem in linear algebra
- The bias-variance trade-off is most clearly illustrated here via ridge and lasso regularization
- Derive the OLS normal equations from the mean-squared-error objective.
- State the five classical assumptions and the Gauss-Markov theorem.
- Recognize OLS as MLE under Gaussian noise, and ridge as the MAP estimate under a Gaussian prior.
- Compare ridge, lasso, and elastic net by objective, closed form, sparsity, and behaviour under multicollinearity.
- Implement OLS and ridge from scratch in NumPy, with sklearn, and as a PyTorch autograd loop.
TL;DR
Linear regression fits the hyperplane that minimizes the squared residual norm. The closed-form OLS solution is the orthogonal projection of onto the column space of , and Gauss-Markov says it is the best linear unbiased estimator (BLUE) when errors are uncorrelated and homoskedastic [1]. Ridge [4], lasso [3], and elastic net [5] add penalties that trade a little bias for a lot of variance reduction, with ridge giving a closed form, lasso giving sparsity, and elastic net combining both.
Intuition
A line through a cloud of points is the simplest predictive model that is still useful. Linear regression chooses the line (or hyperplane in higher dimensions) that minimizes the sum of squared vertical residuals. Two equivalent stories explain why squared error is the right loss:
- Probabilistic. If we assume the noise is i.i.d. Gaussian, with , then maximum-likelihood estimation of is exactly minimization of the squared residual norm [2].
- Geometric. Squared error is the squared Euclidean distance, so OLS finds the orthogonal projection of onto the column space of . The residual vector is the component of that lies orthogonal to every feature column.
OLS is just orthogonal projection. The fitted vector lives in and the residual is perpendicular to every column of . That single fact gives you the normal equations, Gauss-Markov, the geometry of multicollinearity, and why ridge “shrinks” along the small-singular-value directions.
Figure 1. The OLS fit y_hat is the orthogonal projection of y onto col(X). The residual r is perpendicular to every column of X, which is exactly the normal equations X^T r = 0.
Math
Math: derivation of the normal equations and the OLS estimator
Setup
Stack observations in and . We fit with (an intercept is absorbed by adding a column of ones to ).
Squared-error objective
Define the residual sum of squares
Expanding,
Setting the gradient to zero
Differentiate with respect to :
The first-order condition gives the normal equations
If has full column rank, is invertible and
The Hessian is , so is convex and is a global minimum.
Geometric interpretation
The fitted vector , where is the orthogonal projection matrix onto . The residual
lies in , so . That is exactly the normal equations: residuals are orthogonal to every feature column.
Connection to MLE
If with i.i.d., the log-likelihood is
Maximizing in is identical to minimizing , so OLS is the MLE under Gaussian noise [2].
Gradient descent variant
When is too large to invert, run gradient descent with step size :
Convergence requires . Stochastic gradient descent uses a single example or mini-batch per step.
Gauss-Markov theorem: OLS is BLUE
Statement
Assume:
- Linearity: with non-random and full column rank.
- Zero-mean errors: .
- Spherical errors: (uncorrelated and homoskedastic).
Then among all linear unbiased estimators of , the OLS estimator has the smallest variance: it is the Best Linear Unbiased Estimator (BLUE).
Proof sketch
Any linear estimator can be written for some matrix . Write , where is the deviation from the OLS row-operator.
Unbiasedness requires , which forces .
Compute the covariance:
using to kill the cross terms. Since ,
so has the smallest variance among linear unbiased estimators. Equality requires , i.e. uniqueness up to multiplicity. Note that biased estimators (ridge!) can do strictly better in MSE; Gauss-Markov is a statement about the unbiased class only [1].
The classical assumptions
OLS is consistent and well-behaved when these five assumptions hold. Real data often violates one or more, and each violation has a textbook fix.
| Assumption | What it means | Common diagnostic | Standard fix |
|---|---|---|---|
| Linearity | E[y | x] is linear in beta. | Residuals-vs-fitted plot shows no curvature. | Add polynomial features, splines, or use a non-linear model. |
| Independence | Observations (or errors) are independent. | Durbin-Watson on residuals; check for time-series or cluster structure. | GLS, mixed-effects, or block-resampling. |
| Homoskedasticity | Var(epsilon | x) is constant. | Breusch-Pagan test; funnel-shaped residual plot. | Weighted least squares or robust (sandwich) standard errors. |
| Normality of residuals | epsilon is Gaussian. Needed for finite-sample inference, not consistency. | QQ-plot of residuals; Shapiro-Wilk on small n. | Bootstrap confidence intervals; do not bother for large n by CLT. |
| No multicollinearity | X has full column rank; columns are not near-collinear. | VIF (variance inflation factor) above 5-10; condition number of X above 30. | Drop a redundant feature, ridge regression, or PCA pre-processing. |
Strict normality matters for finite-sample t and F statistics. For prediction under a large , the central limit theorem rescues you and you can ignore non-Gaussian residuals. Always know which job your model is doing.
Regularization
Adding a penalty to the OLS objective trades a bit of bias for a lot of variance reduction, especially when features are correlated or when is close to .
Ridge regression: closed-form derivation
The ridge objective is
Setting ,
The penalty term makes strictly positive definite, so the inverse always exists, even when is singular (e.g. or perfectly collinear columns). This is exactly why ridge dominates OLS under multicollinearity [4].
MAP interpretation
Place a Gaussian prior . The posterior mode under the Gaussian likelihood is
with . Ridge is MAP under a Gaussian prior on the weights. Smaller pulls harder towards zero [2].
SVD view
Let be the thin SVD with singular values . Then
Ridge applies the multiplicative shrinkage to the OLS coefficients, with the heaviest shrinkage on directions with small singular values. Those are exactly the directions where OLS has highest variance, so ridge buys variance reduction precisely where OLS is least stable [1].
Lasso and elastic net
The lasso replaces the squared penalty with an absolute-value penalty:
There is no closed form, but the objective is still convex and is solved by coordinate descent or proximal gradient. Each coordinate update reduces to the soft-thresholding operator , which sets coefficients to zero exactly when their unpenalized residual signal is below . That is why lasso produces sparse solutions: it is the penalty geometry, not a heuristic [3].
The elastic net is the convex combination
with . It inherits lasso’s sparsity but, unlike lasso, can keep correlated groups of features together rather than arbitrarily picking one of them [5].
| Method | Objective | Closed form? | Sparsity | Multicollinearity | Hyperparameter |
|---|---|---|---|---|---|
| OLS | ||y - X beta||^2 | yes (X^T X must be invertible) | no | unstable, exploding variance | none |
| Ridge | ||y - X beta||^2 + lambda * ||beta||^2 | yes: (X^T X + lambda I)^(-1) X^T y | no (shrinks but does not zero) | stable, shrinks correlated features together | lambda |
| Lasso | ||y - X beta||^2 + lambda * ||beta||_1 | no (coordinate descent / proximal) | yes (sets coefficients to 0) | arbitrarily picks 1 of a correlated group | lambda |
| Elastic net | ||y - X beta||^2 + lambda * [(1 - alpha) * ||beta||^2 / 2 + alpha * ||beta||_1] | no (coordinate descent) | yes | keeps correlated groups together | lambda, alpha |
Bias-variance trade-off in regularization
OLS is unbiased; any non-zero introduces bias by pulling coefficients toward zero. The win is variance reduction: the shrinkage factor is strictly below 1 on every direction, and tiny on small-singular-value directions. The optimal is the one that balances the squared bias against the variance, and it is almost always strictly positive in finite samples [1].
Gauss-Markov says OLS is best among unbiased linear estimators. Ridge is biased, so the theorem does not apply, and ridge often has lower MSE precisely because the bias-variance trade-off pays off when has small eigenvalues. This is the cleanest example in classical statistics of “controlled bias is good”.
Algorithm
| Step | OLS via normal equations | OLS via gradient descent |
|---|---|---|
| 1 | Stack X (with intercept column) and y. | Stack X (with intercept column) and y. |
| 2 | Compute G = X^T X. | Initialise beta = 0. |
| 3 | Compute c = X^T y. | Choose step size eta below 2 / lambda_max(X^T X). |
| 4 | Solve G beta = c (e.g. Cholesky if G is PD). | Repeat: beta <- beta - eta * X^T (X beta - y) until ||grad|| is small. |
| 5 | Return beta_hat. | Return beta. |
| Cost | O(n d^2 + d^3) one-shot | O(n d) per step, no matrix inverse |
# OLS via normal equations (pseudocode)
G = X.T @ X
c = X.T @ y
beta = solve(G, c) # Cholesky / LU; do not call inv() in production
# OLS via gradient descent (pseudocode)
beta = zeros(d)
for step in range(max_steps):
grad = X.T @ (X @ beta - y)
beta = beta - eta * grad
if norm(grad) < tol:
breakImplementations
Three idiomatic implementations of the same model. The NumPy version solves the normal equations directly, the sklearn version is the production one-liner, and the PyTorch version uses autograd on the squared-error loss so the tensor view lines up with the math above.
import numpy as np
def ols_fit(X, y):
"""Closed-form OLS via the normal equations. Adds an intercept column."""
n = X.shape[0]
X1 = np.hstack([np.ones((n, 1)), X])
G = X1.T @ X1
c = X1.T @ y
beta = np.linalg.solve(G, c) # do not call inv() in production
return beta[0], beta[1:] # intercept, slopes
def ridge_fit(X, y, lam=1.0):
"""Closed-form ridge via (X^T X + lambda I)^{-1} X^T y. Penalty on slopes only."""
n, d = X.shape
X1 = np.hstack([np.ones((n, 1)), X])
A = X1.T @ X1
A[1:, 1:] += lam * np.eye(d) # do not regularize the intercept
beta = np.linalg.solve(A, X1.T @ y)
return beta[0], beta[1:]
def ols_gd_fit(X, y, eta=1e-3, steps=2000):
"""OLS via batch gradient descent (no closed form)."""
n, d = X.shape
X1 = np.hstack([np.ones((n, 1)), X])
beta = np.zeros(d + 1)
for _ in range(steps):
beta -= eta * (X1.T @ (X1 @ beta - y))
return beta[0], beta[1:]
# small synthetic example
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3))
beta_true = np.array([1.5, -2.0, 0.5])
y = 0.7 + X @ beta_true + 0.3 * rng.normal(size=200)
print("OLS :", ols_fit(X, y))
print("Ridge:", ridge_fit(X, y, lam=1.0))
print("GD :", ols_gd_fit(X, y))Run the from-scratch NumPy normal-equations solver live in the browser:
(no output yet)
Real-world uses
| Domain | System | Why linear regression |
|---|---|---|
| Real estate | Zillow Zestimate-style price models | Interpretable per-feature coefficients (sqft, beds, neighborhood) make legal and explainability requirements easier to meet. |
| Experimentation | A/B test impact estimation with covariates (CUPED-style) | Closed-form variance estimator and well-understood standard errors; covariate adjustment shrinks the variance of the treatment effect. |
| Finance | Fama-French and other factor models | Linear in factor exposures; OLS gives BLUE estimates of betas under the Gauss-Markov assumptions. |
| Pharma / clinical | Dose-response models | Regulatory pipelines require model forms whose assumptions can be checked, audited, and reproduced. |
| Causal inference | Difference-in-differences, instrumental variables, fixed effects | Most causal estimators are linear regressions in disguise, with closed-form standard errors. |
Pitfalls
If two columns of are nearly collinear, has a near-zero eigenvalue, and the OLS coefficient variance blows up along that direction. The point estimates are still unbiased but useless for inference. Diagnose with VIF; fix with ridge or by dropping a redundant feature.
OLS point estimates remain unbiased under heteroskedasticity, but the textbook standard errors are wrong, so confidence intervals and p-values lie. Use heteroskedasticity-robust (sandwich, HC1, HC3) standard errors, or weighted least squares if you can model the variance structure.
Squared error penalizes a residual of size by , so a single bad point can swing noticeably. Use Huber regression for moderate contamination, RANSAC for adversarial outliers, or an explicit robust loss.
Ridge, lasso, and elastic net are not scale-invariant: a feature in millimetres gets penalized far more than the same feature in kilometres. Always standardize features (zero mean, unit variance) before running a regularized model, and never regularize the intercept.
Interview Q&A
Derive the OLS normal equations from the squared-error objective.research
Stack examples in and , and define
Expanding,
Differentiate with respect to using and :
Set to obtain , and if has full column rank, . The Hessian is , so is convex and the stationary point is the global minimum. Geometrically, is the orthogonal projection of onto , and the residual satisfies - which is the normal equations [1].
State and prove the Gauss-Markov theorem.research
Statement. If with non-random and full column rank, , and , then among all linear unbiased estimators of , the OLS estimator has the smallest variance (it is BLUE).
Proof sketch. Any linear estimator can be written for a fixed . Decompose .
Unbiasedness. , so unbiasedness for all requires . Substituting, .
Covariance. Using ,
The cross terms vanish because , leaving . Since ,
so has the smallest variance in the Loewner order. Equality requires . ∎
The theorem says nothing about biased estimators, which is why ridge can have strictly lower MSE than OLS in finite samples [1].
Why is minimizing MSE equivalent to MLE under Gaussian noise?onsite
Assume with i.i.d. Then
The first term does not depend on , and the second is a strictly decreasing function of the squared residual norm. Therefore
OLS is the MLE. The same calculation explains why ridge corresponds to MAP estimation under a Gaussian prior on , and why Laplace priors give lasso [2].
Derive the ridge closed form and explain why it works when X is rank-deficient.research
The ridge objective is
Take the gradient and set to zero:
So .
Even if is singular (rank-deficient , or ), the matrix has all eigenvalues at least , so it is invertible and the solution is unique. This is why ridge is the standard fix for multicollinearity and high-dimensional underdetermined regression. The SVD view makes the shrinkage explicit: ridge replaces with , attenuating the small-singular-value directions where OLS variance is largest [4][1].
- 1. Which expression is the OLS estimator?
- 2. Under which assumption(s) is OLS the BLUE (Gauss-Markov)?
- 3. Why does ridge regression always have a unique closed-form solution?
- 4. Which property does lasso have that ridge does not?
- 5. What does it mean that OLS minimizing MSE equals MLE under Gaussian noise?
A short evening project:
- Generate synthetic data with a known and Gaussian noise.
- Fit OLS, ridge, lasso, and elastic net on the same training set across a grid of values.
- Plot validation MSE vs and report the optimum for each model.
- Add a few highly correlated features and re-run; watch ridge keep them all and lasso pick one.
- Stretch: add deliberate heteroskedasticity, then refit OLS with HC3 robust standard errors and confirm the confidence intervals widen on high-variance regions.
Interactive Demo
References
- Hastie, T., Tibshirani, R., and Friedman, J. (2009). The Elements of Statistical Learning, 2nd ed.. Springer. https://hastie.su.domains/ElemStatLearn/
- Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer. ISBN 978-0-387-31073-2
- Tibshirani, R. (1996). Regression Shrinkage and Selection via the Lasso. Journal of the Royal Statistical Society, Series B 58(1), 267-288. doi:10.1111/j.2517-6161.1996.tb02080.x
- Hoerl, A. E. and Kennard, R. W. (1970). Ridge Regression: Biased Estimation for Nonorthogonal Problems. Technometrics 12(1), 55-67. doi:10.1080/00401706.1970.10488634
- Zou, H. and Hastie, T. (2005). Regularization and variable selection via the elastic net. Journal of the Royal Statistical Society, Series B 67(2), 301-320. doi:10.1111/j.1467-9868.2005.00503.x