Least Squares and Linear Regression
Least squares is the workhorse of quantitative science: given a cloud of measurements and a model, it produces the best set of parameters and, just as importantly, honest error bars on them. Its reach is enormous — calibrating a detector, fitting a spectral line, reconstructing an image, training the linear layer of a network — yet underneath every application sits one clean piece of geometry. Stack the observations into a vector in -dimensional data space, and collect every fit the model can produce into a -dimensional plane, the column space of the design matrix . Least squares drops a perpendicular from to that plane: the foot is the fit, the perpendicular itself is the residual. Minimizing squared error is nothing more exotic than "the shortest way to a plane is straight at it". That geometric fact has three payoffs. First, the minimization has a closed form — the normal equations — because "linear regression" means linear in the parameters, so the objective is a quadratic bowl with a unique bottom. Second, the projection is not merely convenient but optimal: the Gauss–Markov theorem certifies it as the minimum-variance unbiased estimator using only three weak assumptions about the noise, with no probability distribution assumed. Third, when the noise is Gaussian, least squares is promoted to maximum likelihood and the estimator becomes exactly normal, handing us -intervals and goodness-of-fit tests for free. Linearity refers to the parameters, not the predictors — a cubic in is still linear regression — and that distinction is the source of most of the method's power and most of its misuse.
- Least squares fits a model by minimizing the sum of squared residuals; for models linear in the parameters this collapses to the normal equations with a unique closed-form solution.
- The geometric content is orthogonal projection: projects the data onto the column space of , so the residual is orthogonal to every regressor, .
- Under the Gauss–Markov assumptions — zero-mean, uncorrelated, equal-variance errors — ordinary least squares is BLUE, the Best Linear Unbiased Estimator, with covariance ; no Gaussianity is needed.
- If the errors are i.i.d. Gaussian, least squares coincides with maximum likelihood and is itself multivariate Gaussian, giving exact -confidence intervals and goodness-of-fit.
- Unequal or correlated errors are handled by weighted and generalized least squares, , which restores optimality — the physicist's fit with error bars.
- Key idea: Linear least squares is orthogonal projection in disguise: projects the data onto , the residual is orthogonal to all regressors, and the Gauss–Markov theorem certifies this projection as the minimum-variance linear unbiased estimate.
Where this lives today
The normal equations are quietly everywhere. Every laboratory calibration curve — a photomultiplier's counts against a known flux, a thermocouple's voltage against temperature — is a least-squares line whose slope, intercept, and error bars come from equations (3) and (5). In particle physics and astronomy the weighted fit of equation (6) is the standard tool for combining measurements with heterogeneous error bars, and the reduced is the first number anyone checks; precision experiments such as the CODATA adjustment of the fundamental constants are giant correlated least-squares problems blending thousands of measurements through a full covariance matrix. In geophysics and medical imaging, tomographic reconstruction is a least-squares inversion so ill-conditioned that Tikhonov regularization — the ridge term — is mandatory to keep noise from exploding. The method reaches into machine learning too: the final linear read-out layer of a neural network is ordinary least squares, and Gaussian-process regression is GLS with an infinite-dimensional feature map. A modern frontier is high-dimensional regression where exceeds : there is singular, OLS fails, and sparse and regularized variants (LASSO, ridge, elastic net) take over — each still descended from the projection geometry Gauss set down.
The physical picture
Think of every measurement as one coordinate. With data points, the observation vector is a single arrow in an -dimensional space — one axis per data point, not per variable. The model cannot reach every arrow: as the parameters range over all values, the achievable fits sweep out only a -dimensional plane through the origin, the column space of . Least squares asks for the point on that plane closest to — the orthogonal projection. The perpendicular dropped from the data to the plane is the residual, and its foot is the fit . Because the shortest segment to a plane meets it at a right angle, the residual is orthogonal to every direction the model could have moved in — the statement : the model has drained every drop of linear signal, and what remains is, by hypothesis, pure noise.
There is a second view a physicist meets far more often: the scatter plot. Fit a straight line to a set of points and the same projection is at work, only now the residuals are the little vertical stubs from each point to the line. Least squares chooses the line for which those stubs, squared and summed, are smallest — equivalently, the one whose residuals sum to zero and are uncorrelated with . The second figure is a real fit to six calibration points, carrying the actual slope, intercept, and uncertainties that fall out of the normal equations and the covariance .
Two things carry over from the geometry to the statistics. The residual, being orthogonal to the plane, "sees" only noise — which is why the residual sum of squares cleanly estimates the noise variance . And the error bars on come from pushing the noise through the linear map : if the regressor columns are nearly parallel — collinear — then is nearly singular, its inverse blows up, and the parameters become wildly uncertain. Ill-conditioning of the design is the disease of which large error bars are the symptom.
The core equations
Least squares begins with a single scalar to minimize: the sum of squared gaps between observation and model. In matrix form it is the squared length of the residual vector, which is why the whole theory is geometric.
where: — the -th observed response; — design-matrix entry, the -th basis function evaluated at ; — the -th model parameter; — number of data points and parameters, with . Reading it: is a quadratic bowl in , with a unique minimum where its gradient vanishes. Setting that gradient to zero gives the normal equations — a linear system, the computational heart of the method. Their name is geometric: they state that the residual is normal (orthogonal) to the column space.
where: — the Gram matrix of regressors, symmetric and positive semidefinite; — the least-squares estimate. Reading it: if has full column rank the Gram matrix is invertible and the fit is unique; otherwise the columns are redundant and infinitely many tie. Solving the system gives the estimator in closed form, and multiplying back by exposes the projection matrix that carries any data vector to its shadow on the model plane.
where: — the hat matrix projecting onto , obeying ; — the fitted values. Reading it: is idempotent (projecting twice changes nothing) and symmetric (the projection is orthogonal). The residual is what is left after projection; it lies entirely in the orthogonal complement of the model plane, and is the algebraic engine of every result that follows.
where: — the residual vector, living in ; — the complementary projection, with . Reading it: the trace counts the residual degrees of freedom — the dimension the noise still occupies after directions were spent fitting. Propagating the noise covariance through the linear estimator gives the parameter covariance — the error bars on the fit.
where: — the common error variance, ; — the unbiased estimate of from the residuals, with . Reading it: the standard error of is , and the divisor is , not , precisely because of the trace in (4). When the errors are not equal and uncorrelated, OLS is still unbiased but no longer best. Generalized least squares restores optimality by weighting with the inverse covariance — the physicist's fit.
where: — the full error covariance; — the objective GLS minimizes. Reading it: for independent points , so each term is weighted by — inverse-variance weighting, the rule that a precise point counts for more. Finally, if the errors are Gaussian the estimator is exactly normal, and each parameter's studentized deviation follows a -distribution — exact confidence intervals at any sample size.
where: — Student's with degrees of freedom; — the -th diagonal of the inverse Gram matrix. Reading it: as the -distribution approaches a standard normal, recovering the familiar interval.
The goal is to turn the minimization of into an explicit linear system, prove that its solution is a genuine minimum rather than a saddle, and read off the geometric meaning — that the fit is the orthogonal projection of the data onto the column space and the residual is orthogonal to every regressor. We expand the quadratic, differentiate, confirm the second-order condition, and interpret.
Step 1. Expand the norm using , giving . Why: the cross term collapses because is a scalar and therefore equals its own transpose , so the two cross terms combine into one.
Step 2. Differentiate with respect to the vector and set the gradient to zero: . Why: at a smooth minimum the gradient vanishes; the linear term gives and the quadratic term , using the symmetry of the Gram matrix.
Step 3. Rearrange to the normal equations , and if has full column rank invert to get . Why: full column rank makes the matrix positive definite and hence invertible, so the stationary point is unique.
Step 4. Confirm it is a minimum: the Hessian is positive semidefinite because for all , and strictly positive definite under full rank. Why: a positive-definite Hessian everywhere makes strictly convex, so the single stationary point is the global minimum — no saddles, no local traps.
Step 5. Read off the geometry. The fitted vector is with , and the normal equations rewrite as . Why: this last identity says every column of is orthogonal to the residual, so is the orthogonal projection of onto — the perpendicular-dropping picture, now proved. *Verified: and follow by direct substitution; for the six-point fit the residuals satisfy and numerically — orthogonality confirmed to machine precision.*
Go deeper · Derivation B · 1 minThe Gauss–Markov theorem: ordinary least squares is BLUE
The goal is to prove that among all estimators linear in the data and unbiased, ordinary least squares has the smallest covariance — any competitor's covariance exceeds the OLS covariance by a positive-semidefinite matrix — using only that the errors have zero mean, common variance , and zero correlation. No Gaussian assumption enters; the theorem is a statement about second moments alone, which is what makes it so powerful and so often misquoted.
Step 1. Write any competing linear estimator as for some fixed matrix , and impose unbiasedness: for every , which forces . Why: unbiasedness must hold for all true parameter values, and a linear identity holding for all can only be satisfied by the matrix constraint .
Step 2. Split around the OLS map by writing . Since and , the deviation obeys . Why: subtracting the two constraints isolates the competitor's departure from OLS and shows it must annihilate the column space of .
Step 3. Compute the competitor's covariance using : . Why: for a linear map acting on data of covariance , the output covariance is — the standard propagation rule.
Step 4. Show the cross terms vanish: , and likewise . Why: the constraint from Step 2 is exactly what kills the interference between the OLS part and the deviation, leaving a clean sum of squares.
Step 5. Conclude . Why: is positive semidefinite, so any deviation can only add variance — OLS attains the floor and is therefore the Best Linear Unbiased Estimator. *Verified: cross-checked against Riley–Hobson–Bence ch. 31 and Stone–Goldbart; the single load-bearing fact is , and the direction of the matrix inequality follows from positive-semidefiniteness of any .*
Go deeper · Derivation C · 1 minLeast squares as maximum likelihood, and why the variance divides by n minus p
The goal is to show that when the errors are independent Gaussians of common variance, maximizing the likelihood is identical to minimizing the sum of squared residuals, so least squares inherits the full optimality of maximum likelihood; and then to expose why the maximum-likelihood variance uses divisor while the unbiased estimator uses . This bridges the geometric OLS with the probabilistic machinery of inference, and settles a divisor that trips up nearly everyone.
Step 1. Write the likelihood for as a product of Gaussians, , where is the -th row of . Why: independence turns the joint density into a product, and each factor is the normal density of one residual.
Step 2. Take the logarithm: . Why: the logarithm is monotonic, preserving the maximum's location, and converts the product into a sum that isolates the -dependence in a single term.
Step 3. Maximize over : only the last term depends on it, and it enters with a negative sign, so . Why: maximizing a negative multiple of the residual sum of squares is the same as minimizing that sum, so the Gaussian MLE is exactly the OLS estimate — least squares is maximum likelihood.
Step 4. Now maximize over by setting , which gives . Why: at the joint maximum the residuals are already the OLS residuals, and the stationarity condition in yields their mean square — but with divisor .
Step 5. Correct the bias. Because the residuals satisfy linear constraints (), they live in an -dimensional space and , so the unbiased estimate is . Why: the MLE divides by and therefore underestimates ; dividing by the residual degrees of freedom removes the bias exactly. *Verified: the divisor identity uses ; the versus distinction is the standard textbook result (Press et al., Numerical Recipes ch. 15) and reduces to Bessel's correction in the constant-fit case .*
Limiting cases
The single machinery of least squares specializes into all the familiar named methods according to what one assumes about the error covariance and any prior on the parameters.
| Case | Result | Meaning |
|---|---|---|
| Equal i.i.d. errors | Ordinary least squares; the Gauss–Markov BLUE with covariance | |
| Independent unequal errors | Weighted least squares — the physicist's fit; precise points pull harder | |
| Correlated errors | Generalized least squares; equivalent to whitening by then doing OLS | |
| Single constant, | Fitting a constant recovers the sample mean; the standard error of the mean falls as | |
| Gaussian prior on parameters | Ridge / Tikhonov regularization — the MAP estimate; tames ill-conditioned |
Worked examples
1 · A straight-line calibration fit with error bars (fully worked)
A detector's response is measured against six known input standards , giving . Fit by ordinary least squares, and report the slope and intercept with their standard errors and a 95% confidence interval on the slope.
Step 1. Assemble the sums the normal equations need. With : , , , . The Gram matrix and right-hand side are therefore and .
Step 2. Invert the Gram matrix. Its determinant is , so .
Step 3. Solve : intercept and slope . The scalar formula agrees.
Step 4. Estimate the noise. The fits give residuals , summing to zero. Their squared sum is , and with the variance estimate is , so .
Step 5. Turn into standard errors: and . With , the 95% slope interval is , i.e. . The fit is with ; the slope is resolved to about 2.6%.
2 · Weighted least squares: combining two discordant measurements
Two independent experiments measure the same constant: experiment A gives , experiment B gives . Combine them by weighted least squares and test whether they are consistent.
Step 1. The model is a single constant, , with . Generalized least squares reduces to the inverse-variance weighted mean, with .
Step 2. The weights are and , so the precise measurement B carries over six times the weight of A; the total is .
Step 3. The weighted mean is , pulled toward B — far from the naive unweighted average , which would bias the result.
Step 4. The combined variance is , so the standard error is — tighter than either input, as combining information should be.
Step 5. Test consistency with on degree of freedom. A reduced near 1 signals a good fit. The combined value is with for 1 dof — the experiments agree.
Physics of the portrait
Least squares arrived twice, was fought over, and then quietly became the substrate of quantitative science — a small drama of priority between Legendre, who published first, and Gauss, who published the deep theory and claimed to have used it years earlier to recover the lost asteroid Ceres.
Origins · 1 minCarl Friedrich Gauss and how this was discovered
Gauss stands at the origin of least squares as both a computational recipe and a statistical theory. As a young man in Göttingen he used the method to predict where the newly discovered and then-lost dwarf planet Ceres would reappear in 1801 — a public triumph that made his name — though he did not publish the technique until his 1809 Theoria Motus. There he did far more than fit orbits: he asked what error distribution would make the arithmetic mean the most probable value, and derived the bell-shaped normal law now called the Gaussian, tying least squares to a theory of measurement error. Adrien-Marie Legendre had published the bare algorithm first, in an 1805 appendix on comet orbits, coining the name méthode des moindres carrés; a bitter priority dispute followed, and both men have a fair claim — Legendre to the method, Gauss to its probabilistic foundation. In the Theoria Combinationis of 1821–1823 Gauss went further, proving the minimum-variance optimality of least squares without assuming the normal law — the result later rediscovered by Andrei Markov and now bearing both names. Laplace meanwhile tied the edifice to his central limit theorem, explaining why the Gaussian error law is so ubiquitous: errors that are sums of many small independent causes tend to it. The same normal equations Gauss wrote by hand are now solved billions of times a day inside modern computers.
Going further
Texts. Stone & Goldbart, Mathematics for Physics, chapter on probability and data analysis · Arfken, Weber & Harris, Mathematical Methods for Physicists, 7th ed., least-squares fitting section · Hassani, Mathematical Physics, on inner-product spaces and projection · Byron & Fuller, Mathematics of Classical and Quantum Physics, on linear vector spaces · Riley, Hobson & Bence, Mathematical Methods for Physics and Engineering, 3rd ed., ch. 31 · Press et al., Numerical Recipes, ch. 15 (Modeling of Data).
Provenance. All equations are standard linear-model theory and were re-verified here: (1) the normal equations from ; (2) by error propagation; (3) the Gauss–Markov BLUE argument via ; (4) the MLE OLS equivalence and the versus divisor. The worked numbers were checked numerically: the six-point fit gives , , , , , with residuals orthogonal to and to machine precision; the weighted mean gives with on 1 dof.
Prerequisites. Expectation, Variance and Moments · Multivariate Gaussian Distribution · Random Variables and Probability Distributions · Joint, Marginal and Conditional Distributions. Leads to. Central Limit Theorem · Conditional Probability and Bayes' Theorem.
Ask the tutor: Ask me to run a least-squares fit on your own data, derive any line above step by step, or show exactly why the residual must be orthogonal to the column space.
Is "linear regression" the same as "fitting a straight line"?
No — and mixing them up causes real errors. "Linear" refers to linearity in the parameters , not in the predictor . A quadratic, a cubic, a polynomial of any degree, and a sum of sines and cosines are all linear regression, because the objective stays quadratic in and the normal equations still apply — you just put those curved functions of into the columns of . What makes a model nonlinear regression is the parameters entering non-linearly — an unknown rate inside an exponential, — which has no closed-form solution and needs iterative methods.
Why square the residuals instead of taking absolute values?
Squaring has three justifications. Geometrically, minimizing a sum of squares is minimizing a Euclidean length, which yields the clean projection picture and a linear solution; absolute values give a "least absolute deviations" fit that is more robust but has no closed form. Statistically, the sum of squares is exactly the negative log-likelihood for Gaussian errors, so squaring is the maximum-likelihood choice when the noise is normal — which the central limit theorem often makes a good approximation. Algebraically, the squared objective is differentiable everywhere, giving the tidy normal equations, whereas the absolute value has a kink at zero. The price is sensitivity to outliers, since a squared residual grows fast; when outliers dominate, robust alternatives are preferred.
What is the hat matrix and why does it matter?
The hat matrix "puts the hat on ," turning data into fitted values, . It is the orthogonal projector onto , hence (projecting twice does nothing new) and (the projection is perpendicular). Its diagonal entries , the leverages, measure how much each point pulls its own fitted value — a leverage near 1 dominates the fit locally and deserves scrutiny. Its trace equals , so is the residual degrees of freedom that sets the divisor in . In one matrix, encodes the fit, the residuals, the degrees of freedom, and the influence of each observation.
When must I use weighted or generalized least squares instead of ordinary OLS?
Whenever the error covariance is not proportional to the identity. If the points have different known uncertainties — heteroscedasticity, common in physics where each measurement carries its own error bar — weight each by so precise points count more; this is the ordinary fit. If the errors are correlated — a shared systematic, or time-series autocorrelation — you need full generalized least squares with the covariance matrix . Ordinary least squares is not wrong here: by Gauss–Markov it stays unbiased. But it is no longer minimum-variance, so it throws away precision, and worse, its naive error bars are then incorrect. The right restores both optimality and honest uncertainties.
How do I know if my fit is any good?
The residuals are the primary diagnostic — look at them, do not just trust a single number. For a weighted fit with known error bars, compute the reduced chi-squared : a value near 1 means the model fits within the stated errors, signals a wrong model or underestimated errors, and hints at overestimated errors or overfitting. But a good is necessary, not sufficient: always plot the residuals against and against the fitted values. Structure in that plot — a trend, a curve, a fan-shape — reveals a missing term, non-linearity, or heteroscedasticity that a summary statistic hides. A good fit shows residuals scattered randomly about zero.
What happens when there are more parameters than data points?
Then , the columns of cannot all be independent, is singular, and ordinary least squares breaks down: infinitely many parameter vectors fit the data exactly with zero residual, so the problem is under-determined and the naive inverse does not exist. This is the norm in modern high-dimensional statistics and machine learning, and the cures all inject extra information. Ridge (Tikhonov) regression adds to make invertible, biasing the estimate toward zero — equivalently a Gaussian prior on the parameters. LASSO adds an penalty that drives most parameters to exactly zero, selecting a sparse subset. Each replaces the missing data constraints with a modeling assumption, and which one is right depends on what you believe about the parameters.