Skip to content
AI.info

Mathematical foundations

Orthogonality, Projections, and Least Squares

Use orthogonality and projection geometry to derive least squares, understand non-unique parameters, and choose numerically reliable solvers.

By the end you can

Projection turns approximation into geometry

Many machine-learning problems ask for the best approximation inside a restricted family. Linear regression is one. The prediction vector has to lie in the column space of the design matrix. Orthogonality supplies the certificate. At the least-squares solution the residual is perpendicular to every direction the model can produce, so the model cannot cut squared error by moving inside its own subspace. That single fact explains the normal equations, the role of rank, and why good software never forms an inverse explicitly.

The geometry is old. The arithmetic is not settled. Legendre put the normal equations in print in 1805, in an appendix to his book on the orbits of comets. Two centuries later the National Institute of Standards and Technology still publishes least-squares datasets with answers certified to 16 significant digits, because widely used software gets them wrong.

Least squares is a projection problem before it is a formula.

Case

Legendre published least squares first; Gauss claimed it anyway

Least squares arrived with a priority fight attached. The method reached print in 1805, in an appendix to Adrien-Marie Legendre's book on determining the orbits of comets. That appendix carries the derivation of the normal equations.

Four years later Gauss printed his own version, in Theoria Motus Corporum Coelestium in 1809. The claim is one quotable sentence: “Our principle, which we have made use of since the year 1795, has lately been published by Legendre in the work Nouvelles methodes pour la determination des orbites des cometes, Paris, 1806, where several other properties of this principle have been explained, which, for the sake of brevity, we here omit.” Two things happen in that sentence. The priority is dated to 1795, eleven years before anything Gauss had published on it. And Legendre's book, cited by title, is misdated to 1806.

The evidence was weighed a century and a half later. Stigler reviewed the documentary and statistical record in 1981, in The Annals of Statistics. His own summary of the verdict is careful rather than triumphant: “It is argued (though not conclusively) that Gauss probably possessed the method well before Legendre, but that he was unsuccessful in communicating it to his contemporaries.” Magnus, writing in 2021, dates the publications the same way: Legendre in 1805, four years before Gauss's 1809 monograph. Priority in mathematics is decided by the printed record. The printed record has a date on it.

Comparison

Four ways to solve a least-squares problem

One mathematical objective, four methods, four different numerical behaviours. The difference is measured, not argued. The National Institute of Standards and Technology publishes Statistical Reference Datasets whose least-squares answers are certified to 16 significant digits. Filip is one of them: 82 observations fitted by a tenth-degree polynomial, 11 parameters, classified “Higher Level of Difficulty.” Its certified values include β0 = −1467.48961422980 (SD 298.084530995537), a residual standard deviation of 0.334801051324544E-02 and R² = 0.996727416185620.

Someone checked. A 2009 audit ran four freely used packages against those certified digits. On Filip, R's lm() returned no usable answer at all, and neither did Ox. Octave's regress scored a log-relative-error of 7 digits on its least accurate coefficient and 1 digit on the residual standard deviation. NIST states plainly why the datasets exist: “Even with the availability of reliable code for linear least squares fitting, problems persist. Failure to use the best algorithms and to implement them most effectively is often the cause.” The card that calls normal equations reasonable only in well-behaved small problems is describing that table.

The iterative column is not generic either. It has a name and a date: LSQR, published by Paige and Saunders in 1982. It is built on the Golub–Kahan bidiagonalization, the same reduction that sits under the dense SVD driver in the third column. It touches A only through the products Ax and Aᵀx, which is what lets it run on matrices too large to factor. Its authors' claim for it is precise: “It is analytically equivalent to the standard method of conjugate gradients, but possesses more favorable numerical properties.” They report it as the most reliable of the conjugate-gradient-type methods they tested when A is ill-conditioned. scipy.sparse.linalg.lsqr implements it, and accepts A as a linear operator producing Ax and Aᵀx.

FigureComparison · 4 columns

Normal equations

Solve XᵀXβ = Xᵀy.

  • Simple derivation
  • Squares the condition number
  • Avoid explicit matrix inversion
  • Reasonable only in well-behaved small problems

QR factorization

Represent X as an orthonormal basis times a triangular matrix.

  • Good numerical stability
  • Exposes rank information
  • Useful for dense least squares
  • Costs more than normal equations

SVD

Resolve every singular direction explicitly.

  • Most informative about rank
  • Supports pseudoinverse and truncation
  • Handles near singularity
  • Often the most expensive dense method

Iterative solver

Use matrix-vector products without a full factorization.

  • Scales to large sparse systems
  • Needs stopping criteria
  • Conditioning controls speed
  • May use preconditioning

Where the normal equations come from

Minimizing ‖Xβ − y‖² gives the gradient 2Xᵀ(Xβ − y). Setting it to zero yields XᵀXβ = Xᵀy. If X has full column rank, XᵀX is invertible and the solution is unique. When columns are dependent, several parameter vectors produce the same projection.

Production software does not leave that ambiguity open. It settles it by a documented rule. LAPACK describes its driver in one line: “DGELSD computes the minimum-norm solution to a real linear least squares problem: minimize 2-norm(| b - A*x |) using the singular value decomposition (SVD) of A. A is an M-by-N matrix which may be rank-deficient.” Among the many minimisers it returns the one of smallest 2-norm. It also reports an integer effective rank, because “The effective rank of A is determined by treating as zero those singular values which are less than RCOND times the largest singular value.” That is why numpy.linalg.lstsq documents that “If there are multiple minimizing solutions, the one with the smallest 2-norm ||x|| is returned”. It is also why scipy.linalg.lstsq defaults to lapack_driver='gelsd' and hands back the effective rank of a alongside the coefficients. The alternatives are 'gelsy' and 'gelss'.

So the fitted values can be unique when the coefficients are not. And the coefficient vector you receive is a choice, made by a cutoff you are allowed to set. Telling those two apart matters whenever parameters are interpreted rather than used only for prediction.

Example

A two-feature projection by hand

A small calculation makes the orthogonality condition visible. The device that makes it work — centring the feature — is not a classroom convenience. It is the remedy a standards body prescribes when a real fit falls apart.

NIST's other “Higher Level of Difficulty” real-world least-squares case is Longley: 16 observations, 7 parameters, certified at β0 = −3482258.63459582 with a residual standard deviation of 304.854073561965. The data comes from a 1967 paper by J. W. Longley appraising least squares programs for the electronic computer from the point of view of the user. R's datasets manual describes it as “A macroeconomic data set which provides a well-known example for a highly collinear regression” — 7 variables, 1947–1962, n=16. Measured against the certified digits, Octave's regress scored a log-relative-error of 0 on that residual standard deviation. No correct digits at all. R's lm scored 14.

  • Design: Let X have one column of ones and one centered feature, so the two columns are orthogonal. NIST gives the same instruction for its hardest datasets: “If your code fails to produce correct results for a dataset of higher level of difficulty, one possible remedy is to center the data and rerun the code. Centering the data, i.e., subtracting the mean for each predictor variable, reduces the degree of multicollinearity.”
  • Coefficients: Project y onto each column and divide by that column’s squared norm. The cross terms that would couple the two estimates vanish, precisely because the columns are orthogonal.
  • Prediction: The fitted vector is the sum of the two projected components.
  • Residual: Subtracting the fitted vector from y leaves a residual with zero dot product against both columns.
  • Interpretation: Orthogonality proves local optimality for squared error inside the chosen linear subspace. Longley shows what losing it costs: 7 near-dependent predictors over 1947–1962 were enough to leave one widely used implementation with 0 correct digits in the residual standard deviation.

Key idea

Changing the metric changes the projection

Ordinary least squares measures residual length with the Euclidean norm. Weighted least squares minimizes rᵀWr instead, so the geometry is defined by W.

A direction can be orthogonal under one inner product and not under another. The phrase “closest point” is therefore incomplete until the metric is named. Weighting can encode unequal noise or unequal decision importance. It can also magnify a mislabeled or badly measured example.

Projection is always relative to a chosen geometry.

Analogy

A shadow keeps everything about an object except its depth

Shadows lose exactly one dimension. The shadow of a three-dimensional object on a flat wall is the closest representation that can live on that wall, and the missing depth points away from the surface. A least-squares model behaves the same way. The fitted vector lies in the model subspace; the residual points in an orthogonal direction. Rotate the wall and a different shadow becomes the closest one.

Statistical residuals also carry noise, misspecification, and the way the data were collected. Geometry says how far the target sits from the subspace. It never says why it sits there. It also never says whether the number your solver printed for that distance has any correct digits in it.

The best approximation depends on both the subspace and the metric.

Steps

Audit a least-squares claim

Use these checks before interpreting a fitted linear model. Several of them have documented answers rather than judgement calls.

Step 2 has a prescribed first move. Near-dependence among columns is exactly what makes Longley hard, and NIST's advice is to centre the predictors — subtract each predictor's mean — and rerun before concluding anything else. Step 5 has a return value: scipy.linalg.lstsq reports the effective rank that GELSD derived from its RCOND cutoff on the singular values, so a rank below the column count is a fact the library will state if you read it. Steps 4 and 6 have Filip and Longley standing behind them. On those two certified datasets Octave's regress returned a residual standard deviation with 1 correct digit and 0 correct digits. R's lm() returned nothing usable on Filip at all. Every one of those runs still produced output shaped like a fitted model, with coefficients and a residual line and no warning that the digits were gone.

FigureProcess · 6 steps
  1. 1. Name the subspace

    State which columns and transformations define the reachable predictions.

  2. 2. Check rank

    Identify exact and near dependencies among columns.

  3. 3. Name the metric

    Distinguish ordinary, weighted, and regularized objectives.

  4. 4. Inspect residual structure

    Look for patterns that violate the approximation model.

  5. 5. Choose a solver

    Match QR, SVD, or iterative methods to scale and conditioning.

  6. 6. Separate fit from meaning

    Do not infer causality or stable coefficients from projection geometry alone.

Visual

The geometry of an orthogonal projection

A vector splits into a component inside a subspace and a residual orthogonal to it. The target y sits outside col(X). The projection ŷ is the closest reachable point under Euclidean distance. The residual r = y − ŷ carries what the subspace cannot reach. And Xᵀr = 0 is the certificate that no move inside the subspace improves the fit.

Rank is where the picture meets the software. When col(X) is spanned by fewer directions than X has columns, many β land on the same ŷ. DGELSD picks among them by an explicit rule: the minimum 2-norm solution, with singular values below RCOND times the largest treated as zero.

FigureProcess · 5 steps
  1. 1

    Target vector y

    The observation we want to approximate.

  2. 2

    Model subspace col(X)

    All predictions reachable as Xβ.

  3. 3

    Projection ŷ

    The closest reachable point under Euclidean distance.

  4. 4

    Residual r = y − ŷ

    The part left outside the model subspace.

  5. 5

    Orthogonality Xᵀr = 0

    The residual has zero inner product with every model direction.

Key takeaways