Linear Regression
Volume II, Chapter 4 — Part I. A complete theoretical treatment of linear regression: the probabilistic model, least-squares derivation, normal equations, geometric interpretation as orthogonal projection, regularization theory, and the bias–variance connection.
Table of Contents
- Learning Objectives
- Prerequisites
- Notation
- Core Intuition
- The Linear Model and Notation
- Least Squares from Maximum Likelihood
- The Normal Equations: Derivation
- Geometric Interpretation: Orthogonal Projection
- Existence, Uniqueness, and Rank Conditions
- Gradient Descent for Linear Regression
- Regularization: Ridge and Lasso
- The Bias–Variance Decomposition
- Statistical Properties of the OLS Estimator
- Worked Examples
- Connection to the Broader Curriculum
- Common Pitfalls and Misconceptions
- Research Perspective
- Summary of Takeaways
- Exercises
Learning Objectives
After reading this chapter, you should be able to:
- State the linear regression model in scalar, vector, and matrix form, and explain the role of the design matrix .
- Derive the least-squares objective from a Gaussian noise model via maximum likelihood.
- Prove the normal equations and solve for when the Gram matrix is invertible.
- Interpret ordinary least squares (OLS) as orthogonal projection of onto the column space of .
- Characterize when the OLS solution is unique in terms of rank and linear independence of features.
- Derive the gradient descent update for linear regression and connect it to the condition number of .
- Derive closed-form Ridge regression and explain why restores invertibility.
- State the bias–variance decomposition for squared error and identify the sources of each term.
Prerequisites
This chapter assumes familiarity with:
- Vectors, Spans & Linear Independence — span, rank, linear independence, inner products
- Matrix Operations & Linear Transformations — column space, rank-nullity, matrix multiplication
- Gradient Descent — first-order optimization, convexity, convergence
Optional but helpful: Positive Definite Matrices for regularization theory, and Maximum Likelihood Estimation for the probabilistic derivation.
Notation
- — Design matrix
- — Target vector
- — Parameter vector (including bias)
- — Augmented feature vector with leading 1
- — Ordinary least squares estimator
- — Regularization strength (Ridge/Lasso)
Core Intuition
Linear regression is the simplest supervised learning model — and the most important. Every neural network layer begins as a linear map; attention computes linear combinations; diffusion models predict noise through linear projections in latent space. Understanding linear regression deeply means understanding the template that all of supervised learning follows: specify a model, define a loss, optimize.
The question is deceptively simple. Given pairs for , find parameters such that predictions are close to observed targets . When is linear in , the problem admits:
- A closed-form solution (the normal equations)
- A geometric interpretation (projection onto a subspace)
- A probabilistic foundation (Gaussian noise least squares)
- A convex optimization landscape (single global minimum)
These properties make linear regression the canonical entry point to machine learning theory. Logistic regression replaces the Gaussian likelihood with Bernoulli; neural networks replace linear with compositions of linear maps and nonlinearities; but the loss–gradient–update pattern established here persists throughout.
Series context. This opens Chapter 4 (Supervised Learning) in Volume II: Classical Machine Learning. Subsequent articles cover Logistic Regression, Bayesian Linear Regression, and the Bias–Variance Tradeoff.
Linear Regression Fit
The Linear Model and Notation
Definition 1 (Linear Regression Model). Given feature vectors and scalar targets for , the linear regression model predicts
where is the augmented feature vector (bias absorbed via a leading coordinate of 1), and is the parameter vector.
Definition 2 (Design Matrix). Stack augmented features into the design matrix
Then predictions for all samples simultaneously are
Important equation. Equation (3) is the matrix form of every linear model in machine learning. The design matrix maps parameters to predictions; its column space is the set of all vectors reachable by some choice of .
Definition 3 (Hypothesis Class). The hypothesis class for linear regression is
This is the set of all affine functions on . It is a -dimensional vector space when features are non-degenerate.
Least Squares from Maximum Likelihood
We now derive why squared error is the natural loss function — not by fiat, but from a probabilistic model.
Assumption 1 (Gaussian Noise Model). Observations arise as
Equivalently, .
Proposition 1. Under Assumption 1, the maximum likelihood estimator of is identical to the minimizer of the sum of squared residuals:
Proof. The log-likelihood for independent Gaussian observations is
Since is constant with respect to , maximizing is equivalent to minimizing .
Definition 4 (Empirical Risk / MSE Loss). The mean squared error objective is
The factor is a convention: the cancels upon differentiation; the averages over samples. Minimizers are identical regardless of these constants.
Definition 5 (Ordinary Least Squares). The OLS estimator is
The Normal Equations: Derivation
We derive the closed-form solution step by step.
Theorem 1 (Normal Equations). A necessary condition for to minimize is
If is invertible, the unique minimizer is
Proof. Expand the objective:
Differentiating with respect to (using for symmetric ):
Setting yields (10). Since is convex (as is positive semidefinite), any critical point is a global minimum. If is positive definite (hence invertible), the solution is unique and given by (11).
Definition 6 (Moore–Penrose Solution). When is singular, (10) has infinitely many solutions. The minimum-norm least-squares solution is
where is the pseudoinverse. This is developed fully in Singular Value Decomposition.
Important equation. Equation (11) is the normal equation (or closed-form solution). It requires inverting a matrix — cost — making it impractical when is in the millions, even though forming costs only .
Geometric Interpretation: Orthogonal Projection
The least-squares problem has an elegant geometric interpretation that clarifies many properties of OLS.
Theorem 2 (Projection Characterization). Let be the OLS fitted values. Then is the orthogonal projection of onto , the column space of . The residual is orthogonal to every column of :
Proof. By definition, . The residual is . From the normal equations (10): , which is precisely (15). This is the orthogonality condition characterizing projection onto a subspace.
Corollary 1 (Pythagorean Decomposition). The total squared norm decomposes as
since .
Interpretation. OLS finds the point in the column space of closest to in Euclidean distance. When (overdetermined system), we cannot fit exactly; we find the best approximation. When (underdetermined), infinitely many yield zero training error; the pseudoinverse selects the minimum-norm parameter vector.
Existence, Uniqueness, and Rank Conditions
Theorem 3 (Uniqueness Condition). The OLS solution is unique if and only if has full column rank, i.e., .
Proof. is invertible if and only if has full column rank (see Positive Definite Matrices). Full column rank means the columns of are linearly independent — no feature (including the bias column) is a linear combination of the others.
Proposition 2 (Training Error and Rank). If (full row rank, requires ), there exists such that exactly — zero training error.
When features are collinear (multicollinearity), is near-singular: small perturbations in cause large changes in . The condition number quantifies this sensitivity via the eigenvalue spread of the Gram matrix.
Gradient Descent for Linear Regression
When is large, forming and inverting is prohibitive. Gradient descent provides an iterative alternative.
From (13), the gradient of the unscaled loss is
The update rule with learning rate :
Proposition 3 (Convergence in the Eigenbasis). Let be the eigendecomposition with eigenvalues . Gradient descent with step size converges to . The convergence rate per step in direction (eigenvector) is governed by .
When is large (ill-conditioned features), convergence is slow — a theme developed in Gradient Descent and addressed by preconditioning and adaptive methods (Adam, etc.).
Proposition 4 (Stochastic Gradient Descent). Replacing the full gradient (17) with an unbiased estimate based on a mini-batch :
yields an unbiased gradient estimator with reduced per-step cost instead of .
Regularization: Ridge and Lasso
When is singular or ill-conditioned, regularization stabilizes estimation.
Definition 7 (Ridge Regression / L2 Penalty). The Ridge objective adds an penalty:
where excludes the bias (typically not penalized).
Theorem 4 (Ridge Closed Form). The Ridge estimator is
where .
Proof. Setting the gradient of (20) to zero:
Rearranging: . For any , the matrix is positive definite and hence invertible.
Definition 8 (Lasso / L1 Penalty). The Lasso objective uses an penalty:
Unlike Ridge, Lasso has no closed-form solution. The penalty induces sparsity: many are driven exactly to zero, performing implicit feature selection. The geometry of the ball (corners on coordinate axes) explains this — the level sets of are non-smooth at axes, so optima often lie on sparse faces.
Proposition 5 (Bayesian Interpretation of Ridge). Ridge regression corresponds to MAP estimation under a Gaussian prior with the Gaussian noise model (5). See Bayesian Linear Regression.
The Bias–Variance Decomposition
Understanding generalization requires decomposing expected prediction error.
Theorem 5 (Bias–Variance Decomposition). Consider the model with , . Let be an estimator trained on a random dataset . For a fixed test point , the expected squared error decomposes as
Proof. Add and subtract and expand; cross terms vanish by independence of from . See Bias–Variance Tradeoff for the full derivation.
Interpretation for linear regression:
- Low complexity (few features, large ): high bias, low variance — underfitting
- High complexity (many features, with collinearity): low bias, high variance — overfitting
- Ridge increases bias slightly but reduces variance substantially when is ill-conditioned
The effective degrees of freedom of Ridge regression is , a smooth measure of model complexity.
Statistical Properties of the OLS Estimator
Under standard assumptions, OLS enjoys strong statistical guarantees.
Assumption 2 (Gauss–Markov Conditions). (i) Linearity: ; (ii) Homoscedasticity: ; (iii) Uncorrelated errors: for ; (iv) Full rank: .
Theorem 6 (Gauss–Markov). Under Assumption 2, the OLS estimator is the Best Linear Unbiased Estimator (BLUE): among all linear unbiased estimators, it has minimum variance.
Proposition 6 (Variance of OLS). Under homoscedastic Gaussian errors:
Large entries in — caused by collinear features — inflate the variance of individual coefficient estimates.
Worked Examples
Example 1: Simple Linear Regression
Given points with scalar feature: . Augmented design matrix and target:
Compute:
The fitted line is .
Example 2: Orthogonality of Residuals
For the solution above, and . Direct computation confirms — the residual is orthogonal to both the bias column and the feature column.
Example 3: Ridge Stabilization
Suppose two features are nearly collinear: . Then has a very small eigenvalue , and has a very large eigenvalue . Adding shifts all eigenvalues by , bounding and stabilizing .
Connection to the Broader Curriculum
Linear regression is the Rosetta Stone of machine learning:
- Linear model — Neural network layers
- Squared loss — Cross-entropy, Huber, contrastive losses
- Normal equations — No closed form; backpropagation instead
- Ridge/Lasso — Weight decay, dropout, all regularization
- Bias–variance — Universal generalization framework
- Design matrix rank — Representation rank, LoRA low-rank structure
Logistic Regression replaces the Gaussian likelihood with Bernoulli and the identity link with the logistic function. Backpropagation generalizes the gradient computation to arbitrary computation graphs. Self-Attention computes similarity-weighted linear combinations — regression over values indexed by queries.
Common Pitfalls and Misconceptions
Pitfall 1: Applying the normal equation when . When there are more parameters than samples, is singular. The normal equation as written in (11) does not apply; use the pseudoinverse or regularization.
Pitfall 2: Regularizing the bias term. Penalizing shifts predictions systematically and is usually undesirable. Always exclude the intercept from and penalties unless features are centered and targets are demeaned.
Pitfall 3: Confusing with model quality. High on training data does not imply good generalization. measures fit on the training set only.
Pitfall 4: Ignoring feature scaling before gradient descent. Features on different scales yield an ill-conditioned , slowing convergence. Standardization () improves conditioning without changing the OLS solution (if the bias is unpenalized).
Pitfall 5: Treating linear regression as "always the right first model." Linearity in parameters does not mean linearity in features. Polynomial, interaction, and basis-expansion features can capture nonlinearity while preserving the closed-form solution.
Pitfall 6: Assuming homoscedasticity. When depends on , OLS is still unbiased but no longer efficient. Weighted least squares or robust methods are appropriate.
Research Perspective
Linear regression dates to Gauss and Legendre's work on least squares in the early nineteenth century for astronomical orbit prediction. The probabilistic formulation through maximum likelihood connects to Fisher's foundations of statistical inference in the 1920s.
In modern machine learning, linear models remain indispensable:
- Generalized Linear Models (GLMs) extend the linear predictor to exponential-family distributions (Nelder & Wedderburn, 1972).
- Kernel Ridge Regression implicitly maps features to infinite-dimensional spaces while retaining a closed-form solution via the representer theorem.
- Random Features (Rahimi & Recht, 2007) approximate kernel methods with explicit finite-dimensional linear models.
- Scaling laws for language models show that linear trends in log-loss vs. compute persist across orders of magnitude — the simplest model class still governs the largest systems.
The resurgence of interest in interpretability has renewed focus on linear probes and linear concept directions in embedding spaces, demonstrating that linear algebra remains central even in the era of billion-parameter models.
Summary of Takeaways
- Linear model — — Simplest supervised hypothesis class
- MSE loss — — MLE under Gaussian noise
- Normal equations — — Closed-form OLS
- Projection — — Geometric interpretation
- Uniqueness — — Full column rank required
- Ridge — — Stabilizes ill-conditioned problems
- Bias–variance — Error = Bias + Variance + — Generalization decomposition
Next article: Logistic Regression → — where the linear predictor is composed with the logistic function and Bernoulli likelihood replaces the Gaussian.
Exercises
Exercise 1 (Derivation). Starting from the Gaussian log-likelihood (7), verify that after substituting the MLE for .
Exercise 2 (Projection). Prove that among all , the vector uniquely minimizes . Use the Pythagorean theorem with the orthogonal decomposition .
Exercise 3 (Rank). Construct a design matrix with rank 2. Show that the normal equations have infinitely many solutions and characterize the solution set as an affine subspace of .
Exercise 4 (Ridge). Prove that the eigenvalues of are where are eigenvalues of . Conclude that Ridge always produces a unique solution for .
Exercise 5 (Bias–variance). For the simple model with a single observation and known , compute and where . Verify the bias–variance decomposition at a test point .
Exercise 6 (Condition number). Let have columns with and . Compute and its condition number as a function of . What happens as ?
Exercise 7 (Conceptual). Explain why centering features () does not change the fitted values , but does change the interpretation of . How does centering affect the Ridge penalty if the bias is not excluded?
Exercise 8 (Connection). Show that the gradient descent update (18) can be written as . Analyze convergence via the spectral radius of .