STATISTICS GRADUATE LEVEL • LINEAR MODELS AND GLMS

Linear Regression in Matrix Form

Expressing the general linear model in compact matrix notation enables elegant derivations, efficient computation, and a geometric understanding of least squares.

Historical Context & Motivation

The story of linear regression begins long before the matrix notation we use today, rooted in astronomers' and mathematicians' desire to fit curves to observational data. For most of the nineteenth century, practitioners solved normal equations by hand, manipulating individual sums and cross-products for each new predictor added to a model. As the number of predictors grew, this approach became not merely tedious but error-prone, motivating a search for a more systematic language. The adoption of matrix algebra in the twentieth century unified these disparate calculations into a single, compact framework that could be automated on digital computers. Today, every major statistical software package—R, Python's scikit-learn, SAS, Stata—solves regression problems using matrix operations at its core.

1805
Legendre's Method of Least Squares
Adrien-Marie Legendre publishes the first formal treatment of minimizing the sum of squared residuals, establishing the mathematical foundation that would later be expressed in matrix form.
1809
Gauss and the Normal Equations
Carl Friedrich Gauss derives the same least-squares principle independently and connects it to the normal distribution, providing probabilistic justification for the method. He also claims to have used the method since 1795.
1858
Cayley Formalizes Matrix Algebra
Arthur Cayley publishes "A Memoir on the Theory of Matrices," introducing the rules for matrix multiplication, inversion, and transposition that would eventually become the language of regression.
1922
Fisher's Framework for Statistical Estimation
Ronald A. Fisher establishes maximum likelihood and analysis of variance, cementing the need for a matrix-based treatment of linear models with multiple predictors and structured error terms.
1972
Computational Revolution
The widespread availability of LINPACK and similar numerical linear algebra libraries makes matrix-based regression practical for large datasets, and the QR decomposition replaces explicit normal-equation inversion for numerical stability.

The central question this lesson addresses is deceptively simple: given a response vector and a set of predictors, how can we express the entire regression problem—model, estimation, inference, and geometry—in a single, unified matrix equation? The payoff is enormous: derivations that span pages in scalar notation collapse to a few lines, properties like unbiasedness and efficiency emerge directly from matrix identities, and the geometric interpretation of projection provides an intuition that transcends any particular dataset.

Core Principles & Definitions

Before writing a single equation, it is essential to understand the conceptual pillars that support the matrix formulation of linear regression. Each principle below maps a familiar idea from introductory regression into the language of linear algebra, enabling us to handle models with an arbitrary number of predictors in a unified way. Mastery of these principles is prerequisite to the derivations and proofs that follow in subsequent sections.

1

The Design Matrix X

An n × p matrix whose rows represent observations and whose columns represent predictors (including a column of ones for the intercept). This matrix encodes all covariate information and defines the column space within which the fitted values must lie.
2

The Parameter Vector β

A p × 1 column vector of unknown regression coefficients. Estimation reduces to finding the particular linear combination of columns of X that best approximates the response vector y.
3

The Error Vector ε

A n × 1 random vector satisfying E(ε) = 0 and Var(ε) = σ²Iₙ under the Gauss–Markov assumptions. These conditions ensure that ordinary least squares is the best linear unbiased estimator.
4

Orthogonal Projection

The fitted values ŷ = Xβ̂ are the orthogonal projection of y onto the column space of X. The residual vector ê is perpendicular to every column of X, which is precisely the geometric content of the normal equations.
5

The Hat Matrix H

Defined as H = X(XᵀX)⁻¹Xᵀ, this idempotent, symmetric matrix projects y onto the column space of X. Its diagonal elements hᵢᵢ measure leverage, and its trace equals p, the number of estimated parameters.
KEY TAKEAWAY
Think of the column space of X as a flat screen (a subspace of ℝⁿ) and the response vector y as a flashlight shining from outside that screen. The OLS fitted values ŷ are the shadow that y casts perpendicularly onto the screen. No other point on the screen is closer to the flashlight—this is why the residual vector is orthogonal to every column of X. The hat matrix H is the mathematical machine that performs this projection, transforming y into its shadow ŷ = Hy.

Geometric Interpretation of OLS

The most profound insight in the matrix treatment of regression is geometric: ordinary least squares finds the point in the column space of X that is closest to y in Euclidean distance. The diagram below illustrates this projection in a simplified three-dimensional setting where the column space of X is a two-dimensional plane. The response vector y sits outside this plane, the fitted value vector ŷ is its perpendicular projection onto the plane, and the residual vector ê = y − ŷ is perpendicular to the plane. This orthogonality condition, expressed algebraically as Xᵀê = 0, is the geometric heart of the normal equations.

The column space C(X), shown as the shaded plane, is spanned by column vectors x₁ (violet) and x₂ (cyan). The response vector y (pink) lies outside the plane. Its orthogonal projection ŷ (amber) is the closest point in C(X), and the residual ê (emerald, dashed) is perpendicular to the plane, satisfying the normal equations Xᵀê = 0.

This geometric picture clarifies many properties that would otherwise require separate algebraic proofs. For instance, the Pythagorean theorem applied to the right triangle formed by y, ŷ, and ê yields the ANOVA decomposition ‖y‖² = ‖ŷ‖² + ‖ê‖², which in scalar notation is SST = SSR + SSE. The coefficient of determination R² is simply the squared cosine of the angle between y and ŷ. Adding a new predictor extends the column space, so ŷ can only move closer to y, which explains why R² never decreases with additional predictors.

Mathematical Framework

We now formalize the algebraic structure. All derivations below assume the classical linear model y = Xβ + ε with rank(X) = p ≤ n, E(ε) = 0, and Var(ε) = σ²Iₙ. Under these conditions, we derive the OLS estimator, its distribution, and associated variance.

THE LINEAR MODEL
y = Xβ + ε
where y is the n × 1 response vector, X is the n × p design matrix, β is the p × 1 parameter vector, and ε is the n × 1 error vector with E(ε) = 0 and Var(ε) = σ²Iₙ.

Deriving the OLS Estimator

We seek β̂ that minimizes the sum of squared residuals S(β) = (y − Xβ)ᵀ(y − Xβ). Expanding, we have S(β) = yᵀy − 2βᵀXᵀy + βᵀXᵀXβ. Taking the gradient with respect to β and setting it to zero gives ∂S/∂β = −2Xᵀy + 2XᵀXβ = 0, which yields the normal equations.

NORMAL EQUATIONS
XᵀXβ̂ = Xᵀy
Pre-multiplying both sides by (XᵀX)⁻¹ yields the closed-form OLS estimator. The existence of this inverse requires X to have full column rank.
OLS ESTIMATOR
β̂ = (XᵀX)⁻¹Xᵀy
This is the fundamental equation of OLS. The matrix (XᵀX)⁻¹Xᵀ is sometimes called the Moore–Penrose left pseudo-inverse of X when X has full column rank.

Properties of the OLS Estimator

Because β̂ = (XᵀX)⁻¹Xᵀy = (XᵀX)⁻¹Xᵀ(Xβ + ε) = β + (XᵀX)⁻¹Xᵀε, we immediately see that E(β̂) = β, confirming unbiasedness. The variance-covariance matrix of β̂ follows from the linear transformation of ε.

VARIANCE-COVARIANCE OF β̂
Var(β̂) = σ²(XᵀX)⁻¹
This compact result encapsulates every standard error and every pairwise covariance among the estimated coefficients. The diagonal elements give Var(β̂ⱼ) = σ²[(XᵀX)⁻¹]ⱼⱼ, and the off-diagonal elements capture collinearity-induced correlations among the estimators.
📐 Gauss–Markov Theorem
Under the assumptions E(ε) = 0 and Var(ε) = σ²Iₙ (no normality required), the OLS estimator β̂ = (XᵀX)⁻¹Xᵀy is the Best Linear Unbiased Estimator (BLUE) of β. "Best" means it has the smallest variance (in the matrix sense: Var(β̃) − Var(β̂) is positive semidefinite) among all linear unbiased estimators β̃ = Cy for any fixed matrix C.

The Hat Matrix, Fitted Values, and Residual Structure

Substituting the OLS estimator back into the model gives ŷ = Xβ̂ = X(XᵀX)⁻¹Xᵀy = Hy, where H = X(XᵀX)⁻¹Xᵀ is the hat matrix (so named because it "puts the hat on y"). This matrix has remarkable algebraic properties that control the behavior of residuals, leverage, and influence in regression diagnostics.

Flowchart showing how the hat matrix H projects y onto ŷ (fitted values), while the complementary projector (I − H) produces the residual vector ê. Both matrices are symmetric and idempotent, and their traces sum to n. The orthogonality ŷᵀê = 0 follows directly from HᵀH(I − H) = H(I − H) = H − H² = 0.

Leverage and the Diagonal of H

The diagonal elements of H, denoted hᵢᵢ, satisfy 0 ≤ hᵢᵢ ≤ 1 and Σhᵢᵢ = p. The value hᵢᵢ measures how much observation i's predictor values differ from the centroid of the design; large hᵢᵢ (conventionally hᵢᵢ > 2p/n) flags that observation as a high-leverage point. Since Var(êᵢ) = σ²(1 − hᵢᵢ), high-leverage observations have small residual variance, making raw residuals unreliable for outlier detection. This motivates the use of studentized residuals rᵢ = êᵢ / (s√(1 − hᵢᵢ)), which have approximately unit variance under the model assumptions.

UNBIASED VARIANCE ESTIMATOR
s² = êᵀê / (n − p) = yᵀ(I − H)y / (n − p)
The denominator n − p arises because ê lies in an (n − p)-dimensional subspace (the orthogonal complement of C(X)), so the sum of squared residuals is a quadratic form with n − p degrees of freedom. Under normality, (n − p)s²/σ² ~ χ²(n − p).

Worked Example: Two-Predictor Regression

Consider a small dataset with n = 4 observations and p = 3 columns (intercept plus two predictors). We will compute β̂, the hat matrix H, fitted values, residuals, and the unbiased variance estimate entirely in matrix form.

Complete OLS Computation in Matrix Form
1
Step 1 — Define the Data MatricesSuppose we observe y = [6, 5, 10, 8]ᵀ with two predictors x₁ and x₂. Including an intercept column of ones, the design matrix is X = [[1, 1, 2], [1, 2, 1], [1, 3, 4], [1, 4, 3]]. Thus n = 4 and p = 3.
2
Step 2 — Compute XᵀXXᵀX = [[4, 10, 10], [10, 30, 28], [10, 28, 30]]. This 3 × 3 symmetric matrix captures the sums of squares and cross-products of all predictors. Notice the (1,1) entry equals n = 4, the (1,j) entries are column sums of xⱼ, and the other entries are inner products of the predictor columns.
3
Step 3 — Compute XᵀyXᵀy = [1×6 + 1×5 + 1×10 + 1×8, 1×6 + 2×5 + 3×10 + 4×8, 2×6 + 1×5 + 4×10 + 3×8]ᵀ = [29, 78, 81]ᵀ.
4
Step 4 — Solve the Normal Equations for β̂We need (XᵀX)⁻¹. Computing the inverse of the 3 × 3 matrix (via cofactors, Gauss-Jordan, or software), we obtain (XᵀX)⁻¹ ≈ [[2.75, −0.625, −0.375], [−0.625, 0.25, −0.0625], [−0.375, −0.0625, 0.1875]]. Then β̂ = (XᵀX)⁻¹Xᵀy ≈ [2.75×29 + (−0.625)×78 + (−0.375)×81, ...]ᵀ ≈ [1.4375, 0.6875, 1.3125]ᵀ.
β̂ ≈ [1.4375, 0.6875, 1.3125]ᵀ
5
Step 5 — Compute Fitted Values and Residualsŷ = Xβ̂ = [1.4375 + 0.6875(1) + 1.3125(2), 1.4375 + 0.6875(2) + 1.3125(1), 1.4375 + 0.6875(3) + 1.3125(4), 1.4375 + 0.6875(4) + 1.3125(3)]ᵀ ≈ [5.75, 6.125, 8.75, 8.375]ᵀ. The residual vector is ê = y − ŷ ≈ [0.25, −1.125, 1.25, −0.375]ᵀ. Verification: Xᵀê should equal the zero vector. Indeed 1ᵀê = 0.25 − 1.125 + 1.25 − 0.375 = 0, and the other two checks confirm orthogonality.
ŷ ≈ [5.75, 6.125, 8.75, 8.375]ᵀ, ê ≈ [0.25, −1.125, 1.25, −0.375]ᵀ
6
Step 6 — Estimate σ²s² = êᵀê / (n − p) = (0.25² + 1.125² + 1.25² + 0.375²) / (4 − 3) = (0.0625 + 1.265625 + 1.5625 + 0.140625) / 1 = 3.03125. With only 1 degree of freedom, this estimate is quite imprecise—a reflection of the small sample size. In practice, n >> p provides more stable variance estimation.
s² = 3.03125 with n − p = 1 degree of freedom

Assumptions, Diagnostics, and When OLS Fails

The elegance of the matrix framework comes with conditions that must be carefully verified in practice. Violations of these assumptions do not invalidate the algebra—the OLS formula still produces numbers—but the optimality properties (unbiasedness, efficiency, valid inference) may break down. The table below summarizes each assumption, its matrix expression, what happens when it fails, and the standard diagnostic tool.

Summary of OLS assumptions in matrix notation with diagnostics
AssumptionMatrix ExpressionConsequence of ViolationDiagnostic
LinearityE(y) = Xββ̂ is biased; predictions systematically wrongResidual vs. fitted plot; partial regression plots
Full rankrank(X) = p(XᵀX) is singular; β̂ not uniqueVIF > 10; condition number of XᵀX
Spherical errorsVar(ε) = σ²Iₙβ̂ still unbiased but no longer BLUE; SEs wrongBreusch–Pagan test; Durbin–Watson test
Normalityε ~ N(0, σ²Iₙ)t and F tests invalid in small samples (OK asymptotically)Q–Q plot of residuals; Shapiro–Wilk test
No influential outliershᵢᵢ bounded; Cook's D smallSingle observations dominate β̂Leverage hᵢᵢ; Cook's distance; DFFITS
KEY TAKEAWAY
Think of the Gauss–Markov conditions as the warranty terms for the OLS estimator. The matrix formula β̂ = (XᵀX)⁻¹Xᵀy always computes something, much like an appliance always turns on. But the guarantee that this something is unbiased and minimum-variance only holds when the warranty conditions are met. When they fail, you need a different estimator—GLS, robust regression, or ridge—much like needing a certified repair shop when the warranty is voided.

From OLS to GLS and Generalized Linear Models

The matrix formulation of OLS serves as the conceptual launching pad for virtually every advanced regression method. When the assumption Var(ε) = σ²Iₙ is replaced by Var(ε) = σ²Ω for a known positive-definite Ω, we arrive at Generalized Least Squares (GLS). When the response is non-Gaussian and the mean is linked to the linear predictor through a nonlinear function, we enter the domain of Generalized Linear Models (GLMs). The table below compares these frameworks.

Comparison of OLS, GLS, and GLM estimation in matrix notation
FeatureOLSGLSGLM (IRLS)
Modely = Xβ + εy = Xβ + ε, Var(ε) = σ²Ωg(μ) = Xβ, y ~ EDF
Estimator(XᵀX)⁻¹Xᵀy(XᵀΩ⁻¹X)⁻¹XᵀΩ⁻¹yIterative: (XᵀWX)⁻¹XᵀWz
Variance of β̂σ²(XᵀX)⁻¹σ²(XᵀΩ⁻¹X)⁻¹(XᵀWX)⁻¹ at convergence
Error structureHomoscedastic, uncorrelatedHeteroscedastic and/or correlatedVariance depends on mean via V(μ)
Key insightProjection onto C(X)Projection in Ω⁻¹-inner product spaceIteratively re-weighted projection

The progression from OLS to GLS to GLMs illustrates a recurring theme in statistics: each generalization relaxes one assumption while preserving the same matrix-algebraic skeleton. GLS replaces Iₙ with Ω⁻¹ inside the quadratic form, effectively "whitening" the errors before applying OLS. GLMs go further by iterating the GLS step with updated weights W that depend on the current estimate of the mean, converging to the maximum likelihood estimate for exponential-family responses. In each case, the hat matrix, leverage, and residual diagnostics have direct analogs expressed in the weighted inner product, so the geometric intuition of OLS carries forward intact.

🔭 Looking Ahead
In subsequent coursework, you will encounter models where X is not full rank (requiring generalized inverses or penalization), where Ω is unknown and must be estimated (feasible GLS), and where the response belongs to distributions like Poisson, Binomial, or Gamma. The matrix framework you have learned here provides the common algebraic and geometric language for all of these extensions.

Practice Problems

PROBLEM 1CONCEPTUAL
Explain in geometric terms why adding a new predictor column to X can never decrease R² in ordinary least squares. Your answer should reference the column space of X, the projection of y, and the relationship between ‖ŷ‖² and ‖y‖².
PROBLEM 2BASIC CALCULATION
Given X = [[1, 2], [1, 3], [1, 5]] and y = [3, 5, 6]ᵀ, compute XᵀX, Xᵀy, and the OLS estimate β̂ = (XᵀX)⁻¹Xᵀy.
PROBLEM 3INTERMEDIATE
Using the data from Problem 2, compute the hat matrix H = X(XᵀX)⁻¹Xᵀ. Verify that H is idempotent (H² = H) and that its trace equals p = 2. Also compute the leverage value h₃₃ and comment on whether the third observation is high-leverage.
PROBLEM 4APPLIED
A researcher fits a linear model with p = 6 predictors (including intercept) on n = 50 observations and finds êᵀê = 220. She then notices one observation with leverage h₁₁ = 0.38 and raw residual ê₁ = −4.2. (a) Compute the unbiased variance estimate s². (b) Compute the internally studentized residual r₁. (c) Should this observation be investigated further? Justify your reasoning using both leverage and residual size.
PROBLEM 5CRITICAL THINKING
Prove that the OLS residual vector ê has variance-covariance matrix Var(ê) = σ²(I − H). From this result, explain why the raw residuals are not identically distributed even when the errors εᵢ are i.i.d. N(0, σ²), and discuss implications for residual diagnostics.

Summary

The classical linear model y = Xβ + ε compactly encodes a system of n equations with p unknowns. By minimizing the squared Euclidean norm ‖y − Xβ‖², we derive the OLS estimator β̂ = (XᵀX)⁻¹Xᵀy from the normal equations XᵀXβ̂ = Xᵀy. The hat matrix H = X(XᵀX)⁻¹Xᵀ projects y onto the column space of X, producing the fitted values ŷ = Hy, while the residuals ê = (I − H)y are orthogonal to every column of X.

Under the Gauss–Markov assumptions (E(ε) = 0, Var(ε) = σ²Iₙ), OLS is BLUE with Var(β̂) = σ²(XᵀX)⁻¹ and σ² is estimated unbiasedly by s² = êᵀê/(n − p). The diagonal elements hᵢᵢ of H measure leverage, and the heterogeneous residual variances Var(êᵢ) = σ²(1 − hᵢᵢ) motivate studentized residuals for diagnostic use. This matrix framework extends naturally to GLS (when errors are heteroscedastic or correlated) and to GLMs (when the response is non-Gaussian), preserving the geometric projection interpretation throughout.

Varsity Tutors • Statistics Graduate Level • Linear Regression in Matrix Form