The Normal Equations and Closed-Form Solution

Imagine you have measured house prices against square footage for two hundred homes. You want the single straight line that best fits this cloud of points. There are infinitely many lines you could draw. Only one minimizes the total squared vertical distance to every data point. The question this article answers is deceptively simple. How do you find that exact line, in one shot? How do you do it without any trial and error? This matters because Linear Regression and the Least Squares Objective shows up everywhere. It appears in predicting prices, calibrating sensors, and fitting curves in physics experiments. It also helps initialize more complex models. Iterative methods can approximate the answer. But for well-behaved problems there is an exact formula. It is computable in a single pass of linear algebra. Engineers who understand this formula can reason about its behavior. They can tell when it is fast, when it breaks down numerically. They can also judge when an iterative alternative like Gradient Descent for Parameter Estimation is preferable. The big picture is geometric, not just algebraic. Least squares regression is really a projection problem. We are projecting the observed output vector onto a subspace. That subspace is spanned by the columns of our data matrix. The closed-form solution — the normal equations — falls directly out of one requirement. The residual (the error vector) must be orthogonal to that subspace. Once you see the picture, the formula stops looking like magic. It starts looking inevitable. This article derives the normal equations from that geometric picture. It walks through the algorithm step by step. It proves why the solution is the unique minimizer. It analyzes its computational cost. Finally, it traces a worked numerical example by hand. This lets you see every number appear.

Key takeaways
  • Least squares regression seeks the weight vector ww minimizing ∥y−Xw∥2\|y - Xw\|^2, the sum of squared residuals.
  • The optimal ww satisfies the normal equations: X⊤Xw=X⊤yX^\top X w = X^\top y.
  • Geometrically, XwXw is the orthogonal projection of yy onto the column space of XX; the residual is perpendicular to every column.
  • When X⊤XX^\top X is invertible, the unique closed-form solution is w=(X⊤X)−1X⊤yw = (X^\top X)^{-1} X^\top y.
  • Solving directly costs O(nd2+d3)O(nd^2 + d^3) for nn samples and dd features — fine for small-to-moderate dd, prohibitive for huge dd.
  • When X⊤XX^\top X is singular or ill-conditioned, the fix is Ridge Regression and L2 Regularization or an iterative solver.
The core insight

The least-squares weights are exactly the vector making the residual orthogonal to every column of the data matrix, which algebraically collapses to w=(X⊤X)−1X⊤yw = (X^\top X)^{-1}X^\top y.

The idea

Suppose we have nn training examples, each with dd features, stacked into a design matrix X∈Rn×dX \in \mathbb{R}^{n \times d}, and a target vector y∈Rny \in \mathbb{R}^n. We assume a linear model y^=Xw\hat{y} = Xw for weight vector w∈Rdw \in \mathbb{R}^d, and we measure error using the residual sum of squares:

J(w)=∥y−Xw∥22=(y−Xw)⊤(y−Xw).J(w) = \|y - Xw\|_2^2 = (y - Xw)^\top (y - Xw).

The least squares problem is to find w⋆=arg⁡min⁡wJ(w)w^\star = \arg\min_w J(w). This is a convex quadratic function of ww, so any point where its gradient vanishes is a global minimum (a fact we justify below). The key geometric insight is this: as ww ranges over all of Rd\mathbb{R}^d, the fitted vector XwXw ranges over the column space of XX, denoted col(X)\mathrm{col}(X) — the set of all linear combinations of the columns of XX. Minimizing ∥y−Xw∥\|y - Xw\| is therefore equivalent to finding the point in col(X)\mathrm{col}(X) closest to yy in Euclidean distance. Basic Euclidean geometry tells us that the closest point in a subspace to an external point is found by orthogonal projection: drop a perpendicular from yy onto the subspace. The foot of that perpendicular is y^=Xw⋆\hat{y} = Xw^\star, and the connecting vector y−y^y - \hat{y} is orthogonal to the entire subspace, not just to y^\hat{y}. "Orthogonal to the entire subspace" means orthogonal to every column of XX. Writing r=y−Xw⋆r = y - Xw^\star for the residual, this condition is

X⊤r=0⟺X⊤(y−Xw⋆)=0⟺X⊤Xw⋆=X⊤y.X^\top r = 0 \quad \Longleftrightarrow \quad X^\top (y - Xw^\star) = 0 \quad \Longleftrightarrow \quad X^\top X w^\star = X^\top y.

This system of dd linear equations in dd unknowns is called the normal equations — "normal" in the old sense of "perpendicular." When X⊤XX^\top X is invertible (equivalently, when XX has full column rank, meaning no feature is an exact linear combination of the others), we can solve directly:

w⋆=(X⊤X)−1X⊤y.w^\star = (X^\top X)^{-1} X^\top y.

The matrix X+=(X⊤X)−1X⊤X^+ = (X^\top X)^{-1}X^\top is called the Moore–Penrose pseudoinverse of XX in the full-rank case, and w⋆=X+yw^\star = X^+ y generalizes the notion of "inverting" a non-square matrix.

How it works

The algorithm is short precisely because the hard work is a linear algebra fact, not a search procedure. Given the data, we build two small matrices and solve one linear system. ``` ALGORITHM: NormalEquations(X, y) Input: X, an n×d matrix of features (one row per example), y, an n×1 vector of targets Output: w, the d×1 least-squares weight vector 1. # Optionally prepend a column of ones to X for an intercept term 2. A ← Xᵀ X # d×d matrix, the "Gram matrix" 3. b ← Xᵀ y # d×1 vector 4. if A is singular (or ill-conditioned): 5. report failure or switch to a regularized / pseudoinverse solve 6. else: 7. solve the linear system A w = b for w 8. # in practice: Cholesky factorization of A, then two triangular solves 9. return w ``` Two implementation details matter in practice. First, we never explicitly compute (X⊤X)−1(X^\top X)^{-1} as a matrix and then multiply it by X⊤yX^\top y. Explicit matrix inversion is numerically wasteful and less stable. Instead we factor A=X⊤XA = X^\top X — since AA is symmetric positive semi-definite, a Cholesky decomposition A=LL⊤A = LL^\top exists whenever AA is positive definite (full column rank), and solving Aw=bAw = b reduces to two cheap triangular solves: Lz=bLz = b then L⊤w=zL^\top w = z. Second, forming X⊤XX^\top X explicitly squares the condition number of the problem, which can amplify numerical error when features are nearly collinear. A more numerically robust alternative factors XX itself using QR decomposition, X=QRX = QR with QQ orthogonal and RR upper triangular, and solves the equivalent triangular system Rw=Q⊤yRw = Q^\top y directly, avoiding the squaring altogether. Both routes solve the same normal equations; QR is preferred in production numerical libraries, while the X⊤XX^\top X route is the one most often taught and hand-computed because dd is small in the pedagogical case.

Figure
Least squares as orthogonal projection onto the column space of X
column space of X (span of its columns) y ŷ = Xw* r = y − ŷ x₁ (column 1) x₂ (column 2) The residual r is perpendicular to every column of X — this is X⊤r = 0. Solving that orthogonality condition for w gives the normal equations X⊤Xw = X⊤y.

Complexity & correctness

Correctness. We show two things: (1) the normal equations characterize every stationary point of J(w)J(w), and (2) when XX has full column rank, that stationary point is the unique global minimizer. For (1), expand and differentiate:

J(w)=y⊤y−2w⊤X⊤y+w⊤X⊤Xw.J(w) = y^\top y - 2 w^\top X^\top y + w^\top X^\top X w.

Since JJ is a quadratic form in ww, its gradient is

∇wJ(w)=−2X⊤y+2X⊤Xw.\nabla_w J(w) = -2 X^\top y + 2 X^\top X w.

Setting the gradient to zero gives exactly X⊤Xw=X⊤yX^\top X w = X^\top y, the normal equations. This confirms the calculus route agrees with the geometric orthogonality route derived above — both say the same thing, that X⊤(y−Xw)=0X^\top(y - Xw) = 0. For (2), we check the Hessian: ∇w2J(w)=2X⊤X\nabla^2_w J(w) = 2X^\top X. A matrix of the form X⊤XX^\top X is always positive semi-definite, because for any vector vv,

v⊤(X⊤X)v=(Xv)⊤(Xv)=∥Xv∥2≥0.v^\top (X^\top X) v = (Xv)^\top(Xv) = \|Xv\|^2 \geq 0.

If XX has full column rank (its columns are linearly independent), then Xv=0Xv = 0 implies v=0v = 0, so the inequality above is strict for v≠0v \neq 0: X⊤XX^\top X is positive definite. A positive definite Hessian means JJ is strictly convex, and a strictly convex function has at most one stationary point, which must be its unique global minimum. Combined with (1), this proves w⋆=(X⊤X)−1X⊤yw^\star = (X^\top X)^{-1}X^\top y is the unique minimizer of the least-squares objective. The projection argument gives the same conclusion more directly and more memorably: among all vectors in col(X)\mathrm{col}(X), the one at minimum Euclidean distance from yy is unique (Euclidean projection onto a subspace is always unique), and it is characterized exactly by the orthogonality of the residual — which is the normal equations.

When it fails. If XX does not have full column rank — for example, if two features are duplicates or one is a linear combination of others — then X⊤XX^\top X is only positive semi-definite, not invertible, and infinitely many ww achieve the same minimal loss (they differ by vectors in the null space of XX). In this regime, one instead uses the Moore–Penrose pseudoinverse (via the singular value decomposition) to select the minimum-norm solution, or adds an L2 penalty as in Ridge Regression and L2 Regularization, which makes X⊤X+λIX^\top X + \lambda I invertible for any λ>0\lambda > 0 regardless of rank.

Time complexity. Forming X⊤XX^\top X costs O(nd2)O(nd^2) multiply-adds (a d×nd \times n matrix times an n×dn \times d matrix). Forming X⊤yX^\top y costs O(nd)O(nd). Solving the resulting d×dd \times d system via Cholesky factorization costs O(d3)O(d^3). Total time is

O(nd2+d3).O(nd^2 + d^3).

When n≫dn \gg d (many samples, modest feature count), the nd2nd^2 term dominates and the cost is roughly linear in nn — very efficient. When dd is large (thousands of features), the d3d^3 factorization term dominates and becomes the bottleneck; this is precisely the regime where iterative methods like Gradient Descent for Parameter Estimation become attractive, since a single gradient step costs only O(nd)O(nd).

Space complexity. Storing XX costs O(nd)O(nd); storing X⊤XX^\top X costs O(d2)O(d^2), independent of nn. This is a genuine advantage of the normal-equation approach for streaming or very large nn: once X⊤XX^\top X and X⊤yX^\top y are accumulated (which can even be done incrementally, row by row, since both are sums over examples), the raw data need not be kept in memory.

Tradeoffs, honestly. The closed-form solution is exact and requires no learning rate, no convergence check, and no iteration count — real advantages for small-to-moderate dd. But it does not scale gracefully to very high-dimensional feature spaces (d3d^3 becomes intolerable past a few thousand features), it requires X⊤XX^\top X to be well-conditioned (near-collinear features cause numerical blowup even when technically invertible), and it has no natural mechanism to prevent overfitting when dd approaches or exceeds nn — all reasons the field also relies on regularized and iterative alternatives.

Worked example

Suppose we want to fit a line y^=w0+w1x\hat{y} = w_0 + w_1 x to four points relating hours studied (xx) to exam score (yy):

xx (hours)yy (score)
13
24
36
49

We prepend a column of ones to capture the intercept w0w_0:

X=[11121314],y=[3469].X = \begin{bmatrix} 1 & 1 \\ 1 & 2 \\ 1 & 3 \\ 1 & 4 \end{bmatrix}, \qquad y = \begin{bmatrix} 3 \\ 4 \\ 6 \\ 9 \end{bmatrix}.

Step 1 — form X⊤XX^\top X.

X⊤X=[11111234][11121314]=[4101030].X^\top X = \begin{bmatrix} 1&1&1&1 \\ 1&2&3&4 \end{bmatrix} \begin{bmatrix} 1 & 1 \\ 1 & 2 \\ 1 & 3 \\ 1 & 4 \end{bmatrix} = \begin{bmatrix} 4 & 10 \\ 10 & 30 \end{bmatrix}.

The (1,1)(1,1) entry is n=4n=4 (count of rows); the off-diagonal entries are ∑xi=10\sum x_i = 10; the (2,2)(2,2) entry is ∑xi2=1+4+9+16=30\sum x_i^2 = 1+4+9+16=30.

Step 2 — form X⊤yX^\top y.

X⊤y=[11111234][3469]=[2265].X^\top y = \begin{bmatrix} 1&1&1&1 \\ 1&2&3&4 \end{bmatrix} \begin{bmatrix} 3\\4\\6\\9 \end{bmatrix} = \begin{bmatrix} 22 \\ 65 \end{bmatrix}.

Here ∑yi=3+4+6+9=22\sum y_i = 3+4+6+9=22, and ∑xiyi=1(3)+2(4)+3(6)+4(9)=3+8+18+36=65\sum x_i y_i = 1(3)+2(4)+3(6)+4(9)=3+8+18+36=65.

Step 3 — solve [4101030]w=[2265]\begin{bmatrix} 4 & 10 \\ 10 & 30\end{bmatrix} w = \begin{bmatrix}22\\65\end{bmatrix}. The determinant is 4(30)−10(10)=120−100=20≠04(30) - 10(10) = 120 - 100 = 20 \neq 0, so X⊤XX^\top X is invertible, confirming a unique solution exists. Its inverse is

(X⊤X)−1=120[30−10−104].(X^\top X)^{-1} = \frac{1}{20}\begin{bmatrix} 30 & -10 \\ -10 & 4 \end{bmatrix}.

Multiply:

w=120[30−10−104][2265]=120[30(22)−10(65)−10(22)+4(65)]=120[660−650−220+260]=120[1040]=[0.52.0].w = \frac{1}{20}\begin{bmatrix} 30 & -10 \\ -10 & 4 \end{bmatrix}\begin{bmatrix}22\\65\end{bmatrix} = \frac{1}{20}\begin{bmatrix} 30(22) - 10(65) \\ -10(22) + 4(65) \end{bmatrix} = \frac{1}{20}\begin{bmatrix} 660 - 650 \\ -220+260 \end{bmatrix} = \frac{1}{20}\begin{bmatrix} 10 \\ 40 \end{bmatrix} = \begin{bmatrix} 0.5 \\ 2.0 \end{bmatrix}.

So w0=0.5w_0 = 0.5, w1=2.0w_1 = 2.0: the fitted line is y^=0.5+2x\hat{y} = 0.5 + 2x.

Verification via the orthogonality condition. Compute residuals ri=yi−y^ir_i = y_i - \hat y_i:

xxyyy^=0.5+2x\hat y = 0.5+2xr=y−y^r = y - \hat y
132.50.5
244.5-0.5
366.5-0.5
498.50.5

Check X⊤r=0X^\top r = 0: the sum of residuals is 0.5−0.5−0.5+0.5=00.5 - 0.5 - 0.5 + 0.5 = 0 (orthogonal to the ones-column, confirming residuals average to zero), and ∑xiri=1(0.5)+2(−0.5)+3(−0.5)+4(0.5)=0.5−1−1.5+2=0\sum x_i r_i = 1(0.5)+2(-0.5)+3(-0.5)+4(0.5) = 0.5-1-1.5+2 = 0 (orthogonal to the xx-column). Both dot products vanish exactly as the theory demands — the residual really is perpendicular to the column space.

Common pitfalls & traps

PitfallWhy it happensConsequence
Forgetting the intercept columnTreating XX as only the raw featuresForces the fitted line through the origin, systematically biased fit
Collinear or duplicate featuresTwo columns are (near) linearly dependentX⊤XX^\top X is singular or near-singular; inversion blows up numerically
Explicitly inverting X⊤XX^\top X in codeSeems like the "obvious" translation of the formulaNumerically unstable and slower than Cholesky/QR-based solves
Using normal equations when dd is hugeFormula looks clean regardless of dimensionO(d3)O(d^3) factorization becomes computationally infeasible
Assuming a unique solution always existsIgnoring the full-rank requirementUnderdetermined systems (d>nd > n, or dependent columns) have infinitely many minimizers

Pioneers & history

The method of least squares predates modern machine learning by two centuries. Its discovery is credited to Legendre, who published the method first, and to Gauss, who claimed prior use and gave the deeper probabilistic justification connecting it to the normal (Gaussian) distribution of errors — the historical root of the word "normal" in "normal equations."

Origins · 1 minCarl Friedrich Gauss and how this was discovered
CF
Carl Friedrich Gauss
1777–1855 · Predicted the orbit of the asteroid Ceres using least squares, and later published the connection between least squares estimation and the Gaussian error distribution, giving the method its statistical foundation

History
1805
— Adrien-Marie Legendre publishes the method of least squares as a technique for fitting astronomical and geodesic data.
1809
— Carl Friedrich Gauss publishes his own account, claiming earlier private use, and links least squares to the normal distribution of measurement errors.
1821
— Gauss formalizes the Gauss–Markov theorem, showing least squares gives the best linear unbiased estimator under standard assumptions.
1900
s — Matrix notation and linear algebra (Cayley, later refined by numerical analysts) recast the normal equations in the compact vector form used today.
1965
— Golub and Kahan popularize the singular value decomposition and QR-based least squares algorithms, replacing naive normal-equation solves in numerical software for stability.

Where this matters

The normal equations are the backbone of ordinary least squares regression, still the default first model fit in statistics, econometrics, and applied science whenever a linear relationship is plausible and the feature count is modest. Scientific computing libraries — the linear algebra routines behind `numpy.linalg.lstsq`, R's `lm()`, and the normal-equation solvers inside statistical packages — implement exactly this method, usually via QR or SVD factorizations for numerical stability rather than the raw (X⊤X)−1(X^\top X)^{-1} formula. Beyond direct regression, the same projection idea recurs throughout machine learning: it is the basis for understanding why Linear Regression and the Least Squares Objective has a unique optimum, it motivates the regularized variants in Ridge Regression and L2 Regularization used whenever features are correlated or numerous, and it provides the exact baseline against which iterative solvers like Gradient Descent for Parameter Estimation are checked for correctness on small problems. Calibration steps in sensor fusion, camera geometry (fitting lines and planes to noisy point measurements), signal processing (least-squares filter design), and the final linear layer of many machine learning pipelines all reduce, at some point, to solving a system that looks exactly like the normal equations.

Ask the tutor: How does adding an L2 penalty term change the normal equations, and why does it always restore invertibility?

Why is the solution called the "normal" equations rather than just "the least-squares equations"?

The name predates modern statistical vocabulary. "Normal" here is used in its geometric sense of "perpendicular" — the defining property of the solution is that the residual vector y−Xw⋆y - Xw^\star is normal (orthogonal) to the column space of XX. Gauss additionally connected the method to the normal distribution of errors, which reinforced the name historically, but the algebraic origin of the term is the perpendicularity condition X⊤(y−Xw)=0X^\top(y-Xw)=0, not the probability distribution. Both meanings of "normal" happen to converge on the same equations, which is a pleasant historical coincidence rather than a logical necessity.

Does the closed-form solution always exist?

No. It exists and is unique only when XX has full column rank, equivalently when X⊤XX^\top X is invertible. If any feature is an exact linear combination of others (including a duplicated column, or more features than examples), X⊤XX^\top X is singular and the normal equations have infinitely many solutions, all achieving the same minimal loss. In that case one typically uses the Moore–Penrose pseudoinverse via singular value decomposition to select the minimum-norm solution, or adds an L2 penalty as in ridge regression, which restores invertibility for any positive regularization strength.

How does this relate to gradient descent, and when should I use one over the other?

Both methods minimize the exact same objective, ∥y−Xw∥2\|y-Xw\|^2, and both are guaranteed to find the same unique minimizer when it exists, because the objective is strictly convex. The normal equations get there in one direct linear-algebra computation costing O(nd2+d3)O(nd^2+d^3); gradient descent gets there iteratively, with each step costing only O(nd)O(nd) but requiring many iterations and a tuned learning rate. For small-to-moderate feature counts (dd in the hundreds or low thousands), the closed-form solve is simpler and exact. For very high-dimensional or very large-scale problems, the per-iteration cost advantage of gradient-based methods dominates.

What does it mean for the residual sum of squares function to be "convex", and why does that guarantee correctness?

Convexity means the function's graph never dips below any chord connecting two points on it — equivalently, its Hessian matrix is positive semi-definite everywhere. For the least-squares objective, the Hessian is the constant matrix 2X⊤X2X^\top X, which is always positive semi-definite regardless of the data. This guarantees any stationary point (where the gradient vanishes) is a global minimum, never a saddle point or local minimum that isn't global. When XX has full column rank, the Hessian is strictly positive definite, upgrading "a global minimum" to "the unique global minimum" — precisely the fact that licenses solving the normal equations with confidence.

What happens numerically if two features are highly correlated but not identical?

X⊤XX^\top X remains technically invertible, so the formula produces an answer, but the matrix becomes ill-conditioned: its condition number (ratio of largest to smallest eigenvalue) becomes very large. Small perturbations in the data or floating-point rounding errors get amplified into large, unstable swings in the estimated coefficients. The fitted line may still predict reasonably on the training data, but the individual weights become unreliable and hard to interpret. This is the classic symptom of multicollinearity, and it is precisely the failure mode that ridge regression's added diagonal term λI\lambda I is designed to stabilize.

Can the normal equations be used for nonlinear relationships?

Yes, as long as the model stays linear in its parameters. You can engineer nonlinear features — for example columns for xx, x2x^2, x3x^3, or sin⁡(x)\sin(x) — and stack them into XX; the model y^=Xw\hat y = Xw is still linear in ww even though it is nonlinear in the original input xx. The normal equations apply completely unchanged in this "polynomial regression" or basis-expansion setting, since the entire derivation only relied on y^\hat y being some linear combination of the columns of XX, never on what those columns actually represent.

Why does the space complexity advantage of X⊤X matter in practice?

Because X⊤XX^\top X has size d×dd \times d regardless of how many training examples nn you have, you can compute it incrementally: process training rows one at a time (or in batches), accumulate the running sums X⊤X=∑ixixi⊤X^\top X = \sum_i x_i x_i^\top and X⊤y=∑ixiyiX^\top y = \sum_i x_i y_i, and discard each row after use. This means fitting via the normal equations can work in a streaming setting with bounded O(d2)O(d^2) memory, even if the full dataset of nn rows would never fit in memory at once — a genuinely useful property distinct from the closed-form formula itself.

Before this

Where this leads