How should we predict a student's exam score from hours studied? Or a house's price from its square footage? These questions share a common structure. A response variable, we believe, depends approximately linearly on one or more explanatory variables. This relationship is contaminated by noise we cannot control. Linear regression formalizes this idea. Least squares gives the canonical method for extracting the best-fitting line — or hyperplane — from noisy data. The method is over two centuries old. It traces to Legendre and Gauss's work on fitting orbits to astronomical observations. Yet it remains the single most used tool in applied statistics, machine learning, econometrics, and the sciences. The core insight is deceptively simple. Among all lines (or hyperplanes) we could draw through a scatter of points, choose one. Pick the line that minimizes the total squared vertical distance from the data to the line. This criterion is not arbitrary. It is the maximum-likelihood choice under Gaussian noise. It has an elegant closed-form solution via calculus or projections. It also decomposes cleanly into geometric pieces — fitted values and residuals — that are orthogonal to one another. That orthogonality is the structural fact underlying nearly every downstream computation. This includes variance decompositions, hypothesis tests, and confidence intervals. This article builds the linear model from its precise probabilistic definition. It derives the least-squares estimator via a normal-equations argument and a geometric projection argument. It also proves the key algebraic identities relating fitted values, residuals, and the design matrix. We keep the treatment general, allowing an arbitrary number of predictors. Every claim is grounded in explicit computation on worked numerical examples with real, unequal numbers. No step is left to intuition alone. The article closes by isolating exactly what least squares gives you for free. This includes unbiasedness and a specific closed-form variance. It also isolates exactly what least squares does not give you. This sets up the natural next question. Under what conditions is the least-squares estimator actually optimal among unbiased estimators? That question is answered by The Gauss-Markov Theorem, which we foreshadow but do not yet prove.
Key takeaways
The linear model assumes Yi=xi⊤β+εi with mean-zero, uncorrelated errors of common variance σ2.
The least-squares estimator β^ minimizes the sum of squared residuals ∑i(Yi−xi⊤β)2.
When X⊤X is invertible, the unique minimizer is β^=(X⊤X)−1X⊤Y, the normal equations.
Fitted values Y^=Xβ^ are the orthogonal projection of Y onto the column space of X; residuals ε^=Y−Y^ are orthogonal to that column space.
β^ is unbiased for β and has covariance matrix σ2(X⊤X)−1, under the stated model alone.
Key idea: least squares turns a statistical estimation problem into a geometric projection problem, and the resulting orthogonality of fitted values and residuals drives everything downstream.
Where this lives today
Least squares regression underlies econometric estimation of demand curves, wage equations, and macroeconomic relationships, where it remains the default first tool before more elaborate causal-inference methods. In physics and engineering, it is the workhorse of curve fitting and calibration — from fitting sensor drift models to processing GPS trilateration data, which still traces its ancestry to Gauss's orbit-fitting problem. In machine learning, ordinary least squares is the exact solution to training a linear model under squared-error loss, and it is the special case (ℓ2 penalty =0) of ridge regression, whose penalized normal equations (X⊤X+λI)β^=X⊤Y directly generalize the formula proved above. In signal processing, the same projection idea appears as the least-squares channel estimator and as the Kalman filter's update step. In statistics more broadly, the orthogonal decomposition ∥Y∥2=∥Y^∥2+∥ε^∥2 proved here is the seed of the ANOVA sum-of-squares decomposition and of the F-test for nested linear models, connecting directly to Standard Tests: t, Chi-Squared, and F. In computational science, the numerically stable way to solve the normal equations — via QR or singular value decomposition rather than explicit matrix inversion — is standard practice in every major statistical software package.
Ask the tutor: How does the Gauss–Markov theorem upgrade "unbiased with covariance σ2(X⊤X)−1" into "the best linear unbiased estimator" — and what exactly does "best" mean there?
DefinitionThe linear model, design matrix, and least-squares estimator
Let n≥p and suppose we observe a response Y1,…,Yn∈R together with, for each i, a vector of predictors xi=(xi1,…,xip)⊤∈Rp (one coordinate is typically the constant xi1≡1, for an intercept). The linear model postulates
Yi=xi⊤β+εi,i=1,…,n,
for an unknown parameter vector β=(β1,…,βp)⊤∈Rp and unobserved errors ε1,…,εn satisfying
E[εi]=0,Var(εi)=σ2<∞,Cov(εi,εj)=0(i=j).
In matrix form, with Y=(Y1,…,Yn)⊤, ε=(ε1,…,εn)⊤, and design matrixX the n×p matrix whose i-th row is xi⊤,
Y=Xβ+ε,E[ε]=0,Cov(ε)=σ2In.
We assume X has full column rank p (equivalently X⊤X is invertible), so no predictor is an exact linear combination of the others. The least-squares estimator of β is any minimizer of the residual sum of squares
S(b)=∥Y−Xb∥2=i=1∑n(Yi−xi⊤b)2,b∈Rp.
Given the estimator β^, the fitted values are Y^=Xβ^ and the residuals are ε^=Y−Y^.
Intuition
Picture data points scattered in a plane, one predictor and one response. Least squares asks: among all straight lines, which one makes the vertical gaps between the line and the points — the residuals — collectively as small as possible, in the sense of minimizing the sum of their squares? Squaring serves two purposes: it makes positive and negative deviations count equally (no cancellation), and it penalizes large deviations disproportionately, pulling the fit toward points that are far off much more strongly than toward points that are close. There is a second, more structural way to see the same object. Stack the n observations into the vector Y∈Rn. The set of all vectors of the form Xb, as b ranges over Rp, is a p-dimensional subspace C(X)⊂Rn — the column space of X. Minimizing ∥Y−Xb∥2 over b is exactly the problem of finding the point of C(X) closest to Y in ordinary Euclidean distance. Elementary geometry says the closest point is the orthogonal projection of Y onto C(X), and the connecting vector — the residual — is perpendicular to the entire subspace. This single geometric fact, proved rigorously below, is the source of every algebraic identity involving fitted values and residuals.
Figure
Least squares as orthogonal projection onto the column space
The central theorem
TheoremLeast-squares estimation and the normal equations
Under the linear model as defined above, with X an n×p matrix of full column rank p≤n, the residual sum of squares
S(b)=∥Y−Xb∥2
has a unique minimizer over b∈Rp, given by
β^=(X⊤X)−1X⊤Y.
Equivalently, β^ is the unique solution of the normal equationsX⊤Xb=X⊤Y. Writing H=X(X⊤X)−1X⊤ (the hat matrix), the fitted values and residuals satisfy: 1. Y^=HY, and H is symmetric idempotent (H⊤=H, H2=H) with rank(H)=p. 2. ε^=(I−H)Y, and X⊤ε^=0; in particular Y^⊤ε^=0 (fitted values and residuals are orthogonal). 3. (Pythagorean decomposition) ∥Y∥2=∥Y^∥2+∥ε^∥2. 4. E[β^]=β (unbiasedness), and Cov(β^)=σ2(X⊤X)−1.
Proof
We give two independent derivations of the minimizer — algebraic (via calculus/completing the square) and geometric (via orthogonal projection) — then establish the stated properties.
Step 1: existence and uniqueness of the minimizer, algebraically. Let β^=(X⊤X)−1X⊤Y; this is well defined since X has full column rank p, which forces X⊤X to be positive definite (for any v=0, v⊤X⊤Xv=∥Xv∥2>0 because Xv=0 only for v=0 by full rank), hence invertible. For an arbitrary b∈Rp, write b=β^+d for d=b−β^. Then
Y−Xb=(Y−Xβ^)−Xd=ε^−Xd,
where ε^:=Y−Xβ^. Expanding the squared norm,
S(b)=∥ε^∥2−2ε^⊤Xd+∥Xd∥2.
We check the cross term vanishes: by definition of β^,
X⊤ε^=X⊤(Y−X(X⊤X)−1X⊤Y)=X⊤Y−X⊤Y=0,
so ε^⊤Xd=(X⊤ε^)⊤d=0 for every d. Hence
S(b)=∥ε^∥2+∥Xd∥2=S(β^)+∥X(b−β^)∥2≥S(β^),
with equality if and only if ∥X(b−β^)∥2=0, i.e. X(b−β^)=0. Since X has full column rank, its columns are linearly independent, so Xv=0⟺v=0; hence equality holds iff b=β^. This proves β^ is the unique global minimizer of S.
Step 1′: the same minimizer via orthogonal projection (geometric verification). Let C(X)={Xb:b∈Rp}, a p-dimensional subspace of Rn (dimension p because X's columns are independent). The projection theorem for Hilbert/Euclidean spaces states that for any subspace C and any Y, there is a unique Y^∈C minimizing ∥Y−v∥ over v∈C, and it is characterized by Y−Y^⊥C. Writing Y^=Xβ^ for some β^ (possible since Y^∈C(X)), the orthogonality condition Y−Y^⊥C(X) means (Y−Xβ^)⊤Xc=0 for all c∈Rp, i.e. X⊤(Y−Xβ^)=0, i.e. X⊤Xβ^=X⊤Y — the normal equations, solved uniquely (by invertibility of X⊤X) by β^=(X⊤X)−1X⊤Y, matching Step 1. This confirms the two routes agree and explains geometrically whyX⊤ε^=0 held in Step 1: it is precisely the projection theorem's orthogonality condition.
Step 2: properties of the hat matrix H=X(X⊤X)−1X⊤. By definition Y^=Xβ^=X(X⊤X)−1X⊤Y=HY, proving the first claim of part 1. Symmetry: H⊤=X((X⊤X)−1)⊤X⊤=X(X⊤X)−1X⊤=H, using that X⊤X is symmetric so its inverse is too. Idempotence: H2=X(X⊤X)−1X⊤X(X⊤X)−1X⊤=X(X⊤X)−1X⊤=H, since the middle X⊤X(X⊤X)−1 cancels to Ip. Rank: since H is idempotent, its eigenvalues are all 0 or 1 (if Hv=λv with v=0 then λv=Hv=H2v=λHv=λ2v, so λ=λ2), and for a symmetric idempotent matrix, rank(H)=trace(H) (sum of eigenvalues counted with multiplicity, all 0 or 1). Compute
using the cyclic property of trace. Hence rank(H)=p, proving part 1 completely.
Step 3: residuals and orthogonality (part 2).ε^=Y−Y^=Y−HY=(I−H)Y. We showed in Step 1 that X⊤ε^=0 directly from the normal equations; this also follows from I−H: X⊤(I−H)=X⊤−X⊤X(X⊤X)−1X⊤=X⊤−X⊤=0. Consequently, since Y^=Xβ^∈C(X),
Y^⊤ε^=β^⊤X⊤ε^=β^⊤0=0.
This proves part 2.
Step 4: Pythagorean decomposition (part 3). Since Y=Y^+ε^ and Y^⊤ε^=0,
∥Y∥2=∥Y^+ε^∥2=∥Y^∥2+2Y^⊤ε^+∥ε^∥2=∥Y^∥2+∥ε^∥2.
Step 5: unbiasedness and covariance (part 4). Substitute the model Y=Xβ+ε into the estimator:
where we used ((X⊤X)−1)⊤=(X⊤X)−1 (symmetry of the inverse of a symmetric matrix). This proves part 4 and completes the proof. ■
∎
Worked examples
Example 1: simple linear regression with unequal, asymmetric data. Consider n=5 observations of a single predictor x (say, hours of machine operation) and response y (units produced, with measurement noise):
i
xi
yi
1
1
2.1
2
2
3.9
3
4
6.3
4
5
11.2
5
8
15.5
Here p=2 with design matrix rows xi⊤=(1,xi) (intercept plus slope). We need
X⊤X=(n∑xi∑xi∑xi2),X⊤Y=(∑yi∑xiyi).
Compute the sums: ∑xi=1+2+4+5+8=20, ∑xi2=1+4+16+25+64=110, ∑yi=2.1+3.9+6.3+11.2+15.5=39.0, and
Residuals: ε^1=2.1−1.89=0.21, ε^2=3.9−3.86=0.04, ε^3=6.3−7.80=−1.50, ε^4=11.2−9.77=1.43, ε^5=15.5−15.68=−0.18. Verify ∑ε^i≈0: 0.21+0.04−1.50+1.43−0.18=0.00 ✓ (this must hold exactly since the intercept column is 1's and X⊤ε^=0 forces ∑i1⋅ε^i=0). Verify ∑xiε^i≈0: 1(0.21)+2(0.04)+4(−1.50)+5(1.43)+8(−0.18)=0.21+0.08−6.00+7.15−1.44=0.00 ✓, confirming the second column of the orthogonality identity X⊤ε^=0.
Example 2: multiple regression with two predictors, illustrating the projection picture directly. Suppose we model a response Y (say, plant growth in cm) using two predictors: x1 = water (liters/week, no intercept term included in this design for simplicity) and x2 = sunlight (hours/day), with n=4 observations:
i
xi1 (water)
xi2 (sun)
yi (growth)
1
1
3
5.0
2
2
2
6.0
3
3
5
14.0
4
4
1
7.5
Model: Yi=β1xi1+β2xi2+εi (no intercept — the two-column design matrix directly).
X=12343251,Y=5.06.014.07.5.
Compute X⊤X: entry (1,1)=12+22+32+42=1+4+9+16=30; entry (1,2)=(2,1)=1(3)+2(2)+3(5)+4(1)=3+4+15+4=26; entry (2,2)=32+22+52+12=9+4+25+1=39. So
X⊤X=(30262639).
Compute X⊤Y: entry 1=1(5.0)+2(6.0)+3(14.0)+4(7.5)=5+12+42+30=89; entry 2=3(5.0)+2(6.0)+5(14.0)+1(7.5)=15+12+70+7.5=104.5. So
X⊤Y=(89104.5).
Determinant of X⊤X: 30(39)−26(26)=1170−676=494. Inverse:
So β^1=754/494≈1.5263 and β^2=821/494≈1.6620. Fitted values: y^1=1.5263(1)+1.6620(3)=1.5263+4.9859=6.5123; y^2=1.5263(2)+1.6620(2)=3.0526+3.3239=6.3765; y^3=1.5263(3)+1.6620(5)=4.5789+8.3097=12.8886; y^4=1.5263(4)+1.6620(1)=6.1053+1.6620=7.7673. Residuals: ε^1=5.0−6.5123=−1.5123, ε^2=6.0−6.3765=−0.3765, ε^3=14.0−12.8886=1.1114, ε^4=7.5−7.7673=−0.2673. Check x⋅1⊤ε^≈0: 1(−1.5123)+2(−0.3765)+3(1.1114)+4(−0.2673)=−1.5123−0.7530+3.3342−1.0692=−0.0003≈0 ✓ (rounding). Check x⋅2⊤ε^≈0: 3(−1.5123)+2(−0.3765)+5(1.1114)+1(−0.2673)=−4.5369−0.7530+5.5570−0.2673=−0.0002≈0 ✓. Both confirm X⊤ε^=0 to rounding precision, exactly as guaranteed by the theorem — note this design has no intercept column, so unlike Example 1 the raw residuals need not sum to zero on their own; only the orthogonality to each actual column of X is guaranteed, illustrating that "residuals sum to zero" is a special case of X⊤ε^=0 that requires a column of ones, not a universal law.
CounterexampleDropping full column rank: non-uniqueness of the minimizer
The theorem's uniqueness claim relies on X having full column rank p. Suppose instead we regress on two predictors that are perfectly collinear. Take n=3, p=2, with
X=123246,Y=134,
where the second column is exactly twice the first (xi2=2xi1 for every i), so X has rank 1<p=2. Then X⊤X=(14282856) has determinant 14(56)−28(28)=784−784=0, so it is singular and the formula β^=(X⊤X)−1X⊤Y is not defined. Worse, the minimizer of S(b) is no longer unique. Any b=(b1,b2) produces the same fitted value Xb=(b1+2b2)123, which depends on (b1,b2) only through the scalar c:=b1+2b2. Minimizing over c gives an ordinary one-variable least-squares problem with predictor column (1,2,3)⊤; one finds the optimal c∗ is unique, but every pair (b1,b2) with b1+2b2=c∗ achieves the same minimal sum of squares. For instance (b1,b2)=(c∗,0) and (b1,b2)=(0,c∗/2) both minimize S identically. There is an entire line of minimizers in R2, not a single point. This shows precisely what full column rank buys us: without it, X⊤X is not invertible, the normal equations have infinitely many solutions (a whole affine subspace), and "the" least-squares estimator is not well-defined as a single vector — one must either drop a collinear predictor or use a generalized (Moore–Penrose) inverse and select, by convention, the minimum-norm solution.
Scope, edge cases & common traps
Situation
What happens
Resolution
X⊤X singular (collinear predictors, or n<p)
Normal equations have infinitely many solutions
Drop redundant predictors, or use pseudoinverse for minimum-norm solution
No intercept column in X
∑iε^i need not be 0
Only X⊤ε^=0 is guaranteed in general
Errors correlated or heteroscedastic (Cov(ε)=σ2I)
β^ still unbiased, but the variance formula σ2(X⊤X)−1 is wrong
Origins · 1 minCarl Friedrich Gauss and how this was discovered
CF
Carl Friedrich Gauss
1777–1855 · Göttingen, German astronomy and mathematics
Gauss developed the method of least squares around 1795, motivated by the problem of combining redundant astronomical observations — most famously, predicting the orbit of the newly discovered dwarf planet Ceres in 1801 after it vanished behind the sun, using only a handful of noisy angular measurements. He justified the method by showing that, under a normal (Gaussian) error law, the least-squares estimate coincides with the maximum-likelihood estimate — a foundational link between geometry and probability that anticipates modern statistical inference. Adrien-Marie Legendre independently published the method first, in 1805, leading to a long priority dispute; Gauss maintained he had used the technique privately since the 1790s, and his 1809 book Theoria Motus Corporum Coelestium gives the probabilistic justification absent from Legendre's purely algebraic treatment.
History
- 1795 — Gauss privately develops the method of least squares for combining astronomical measurements.
- 1801 — Gauss successfully predicts the reappearance of Ceres, dramatically validating the method.
- 1805 — Legendre independently publishes the first formal description of least squares.
- 1809 — Gauss publishes Theoria Motus, linking least squares to maximum likelihood under Gaussian errors.
- 1821 — Gauss publishes the theorem now called Gauss–Markov, establishing an optimality property of the estimator.
Why minimize the sum of squares rather than, say, the sum of absolute residuals?
Squaring gives a smooth, differentiable objective with a unique closed-form global minimizer whenever X has full column rank, obtained by solving a linear system (the normal equations). Minimizing absolute deviations (least absolute deviations, or ℓ1 regression) is a valid alternative but leads to a piecewise-linear, non-differentiable objective solved by linear programming rather than linear algebra, and it targets the conditional median rather than the conditional mean. Historically, Gauss further justified the squared criterion by showing it coincides with maximum likelihood when errors are Gaussian — see the discussion in The Sample Mean and Sample Variance regarding why squared deviations arise naturally from Gaussian likelihoods. Both criteria are legitimate; least squares is simply the one with the richest closed-form theory.
Does the least-squares theorem require the errors to be normally distributed?
No. The theorem proved here — the formula for β^, its unbiasedness, and its covariance matrix σ2(X⊤X)−1 — uses only the assumptions that E[εi]=0, Var(εi)=σ2, and the εi are uncorrelated. Normality is a separate, additional assumption needed only when you want exact finite-sample distributions for β^, for confidence intervals, or for t- and F-tests on the coefficients, as covered under Standard Tests: t, Chi-Squared, and F. Without normality, one typically appeals instead to large-sample (central limit theorem) approximations for inference.
What exactly is the "hat matrix" and why is it useful?
The hat matrix H=X(X⊤X)−1X⊤ is the matrix that maps the observed response vector to the fitted values, Y^=HY — it "puts a hat on" Y. It is symmetric and idempotent, which encodes precisely the fact that it represents an orthogonal projection onto the column space of X. Its diagonal entries, called leverages, measure how much each observation's own response value influences its own fitted value, and they sum to p (the rank of H), which is useful for diagnosing influential data points in regression diagnostics.
Is the least-squares estimator the best possible unbiased estimator of β?
Not automatically, and this article deliberately does not claim it. What is proved here is only that β^ is unbiased with covariance σ2(X⊤X)−1, under the stated linear model with uncorrelated, equal-variance errors. Whether it has the smallest variance among all linear unbiased estimators is a distinct and stronger claim, established by The Gauss-Markov Theorem, which requires exactly the same error assumptions (mean zero, common variance, uncorrelated) but no normality. If those assumptions fail — for instance under heteroscedastic or correlated errors — least squares can be badly suboptimal, and generalized least squares should be used instead.
What happens numerically if X⊤X is invertible but nearly singular?
The formula β^=(X⊤X)−1X⊤Y remains mathematically valid, but it becomes numerically unstable: small perturbations in the data can produce large changes in β^, and the entries of (X⊤X)−1 can be enormous, inflating Cov(β^)=σ2(X⊤X)−1. This situation, called multicollinearity, does not violate any hypothesis of the theorem, but it is a serious practical warning sign; standard remedies include centering/scaling predictors, dropping redundant variables, or using ridge regression, which regularizes X⊤X by adding λI before inverting.
How does the fitted-values/residuals decomposition relate to hypothesis testing?
The Pythagorean identity ∥Y∥2=∥Y^∥2+∥ε^∥2 (or its mean-centered analogue, the total-sum-of-squares decomposition) is the algebraic seed of analysis of variance. Under the additional assumption εi∼N(0,σ2) i.i.d., ∥ε^∥2/σ2 has a chi-squared distribution with n−p degrees of freedom, and ratios of such sums of squares (for nested models) have F-distributions — the basis of the F-test for comparing regression models, and of individual coefficient t-tests, both covered under Standard Tests: t, Chi-Squared, and F.
Can least squares be used with more predictors than observations (p>n)?
Not in the form given here: if p>n, the design matrix cannot have full column rank p (its rank is at most n<p), so X⊤X is necessarily singular and the theorem's hypotheses fail outright. In that regime, ordinary least squares has no unique solution, and practitioners instead use regularized methods such as ridge regression or the lasso, which impose additional structure (a penalty term) to select a unique, well-behaved estimator despite p>n.