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.
- Least squares regression seeks the weight vector minimizing , the sum of squared residuals.
- The optimal satisfies the normal equations: .
- Geometrically, is the orthogonal projection of onto the column space of ; the residual is perpendicular to every column.
- When is invertible, the unique closed-form solution is .
- Solving directly costs for samples and features — fine for small-to-moderate , prohibitive for huge .
- When is singular or ill-conditioned, the fix is Ridge Regression and L2 Regularization or an iterative solver.
The least-squares weights are exactly the vector making the residual orthogonal to every column of the data matrix, which algebraically collapses to .
The idea
Suppose we have training examples, each with features, stacked into a design matrix , and a target vector . We assume a linear model for weight vector , and we measure error using the residual sum of squares:
The least squares problem is to find . This is a convex quadratic function of , so any point where its gradient vanishes is a global minimum (a fact we justify below). The key geometric insight is this: as ranges over all of , the fitted vector ranges over the column space of , denoted — the set of all linear combinations of the columns of . Minimizing is therefore equivalent to finding the point in closest to 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 onto the subspace. The foot of that perpendicular is , and the connecting vector is orthogonal to the entire subspace, not just to . "Orthogonal to the entire subspace" means orthogonal to every column of . Writing for the residual, this condition is
This system of linear equations in unknowns is called the normal equations — "normal" in the old sense of "perpendicular." When is invertible (equivalently, when has full column rank, meaning no feature is an exact linear combination of the others), we can solve directly:
The matrix is called the Moore–Penrose pseudoinverse of in the full-rank case, and 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 as a matrix and then multiply it by . Explicit matrix inversion is numerically wasteful and less stable. Instead we factor — since is symmetric positive semi-definite, a Cholesky decomposition exists whenever is positive definite (full column rank), and solving reduces to two cheap triangular solves: then . Second, forming explicitly squares the condition number of the problem, which can amplify numerical error when features are nearly collinear. A more numerically robust alternative factors itself using QR decomposition, with orthogonal and upper triangular, and solves the equivalent triangular system directly, avoiding the squaring altogether. Both routes solve the same normal equations; QR is preferred in production numerical libraries, while the route is the one most often taught and hand-computed because is small in the pedagogical case.
Complexity & correctness
Correctness. We show two things: (1) the normal equations characterize every stationary point of , and (2) when has full column rank, that stationary point is the unique global minimizer. For (1), expand and differentiate:
Since is a quadratic form in , its gradient is
Setting the gradient to zero gives exactly , the normal equations. This confirms the calculus route agrees with the geometric orthogonality route derived above — both say the same thing, that . For (2), we check the Hessian: . A matrix of the form is always positive semi-definite, because for any vector ,
If has full column rank (its columns are linearly independent), then implies , so the inequality above is strict for : is positive definite. A positive definite Hessian means 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 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 , the one at minimum Euclidean distance from 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 does not have full column rank — for example, if two features are duplicates or one is a linear combination of others — then is only positive semi-definite, not invertible, and infinitely many achieve the same minimal loss (they differ by vectors in the null space of ). 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 invertible for any regardless of rank.
Time complexity. Forming costs multiply-adds (a matrix times an matrix). Forming costs . Solving the resulting system via Cholesky factorization costs . Total time is
When (many samples, modest feature count), the term dominates and the cost is roughly linear in — very efficient. When is large (thousands of features), the 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 .
Space complexity. Storing costs ; storing costs , independent of . This is a genuine advantage of the normal-equation approach for streaming or very large : once and 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 . But it does not scale gracefully to very high-dimensional feature spaces ( becomes intolerable past a few thousand features), it requires to be well-conditioned (near-collinear features cause numerical blowup even when technically invertible), and it has no natural mechanism to prevent overfitting when approaches or exceeds — all reasons the field also relies on regularized and iterative alternatives.
Worked example
Suppose we want to fit a line to four points relating hours studied () to exam score ():
| (hours) | (score) |
|---|---|
| 1 | 3 |
| 2 | 4 |
| 3 | 6 |
| 4 | 9 |
We prepend a column of ones to capture the intercept :
Step 1 — form .
The entry is (count of rows); the off-diagonal entries are ; the entry is .
Step 2 — form .
Here , and .
Step 3 — solve . The determinant is , so is invertible, confirming a unique solution exists. Its inverse is
Multiply:
So , : the fitted line is .
Verification via the orthogonality condition. Compute residuals :
| 1 | 3 | 2.5 | 0.5 |
| 2 | 4 | 4.5 | -0.5 |
| 3 | 6 | 6.5 | -0.5 |
| 4 | 9 | 8.5 | 0.5 |
Check : the sum of residuals is (orthogonal to the ones-column, confirming residuals average to zero), and (orthogonal to the -column). Both dot products vanish exactly as the theory demands — the residual really is perpendicular to the column space.
Common pitfalls & traps
| Pitfall | Why it happens | Consequence |
|---|---|---|
| Forgetting the intercept column | Treating as only the raw features | Forces the fitted line through the origin, systematically biased fit |
| Collinear or duplicate features | Two columns are (near) linearly dependent | is singular or near-singular; inversion blows up numerically |
| Explicitly inverting in code | Seems like the "obvious" translation of the formula | Numerically unstable and slower than Cholesky/QR-based solves |
| Using normal equations when is huge | Formula looks clean regardless of dimension | factorization becomes computationally infeasible |
| Assuming a unique solution always exists | Ignoring the full-rank requirement | Underdetermined systems (, 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
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 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 is normal (orthogonal) to the column space of . 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 , 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 has full column rank, equivalently when is invertible. If any feature is an exact linear combination of others (including a duplicated column, or more features than examples), 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, , 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 ; gradient descent gets there iteratively, with each step costing only but requiring many iterations and a tuned learning rate. For small-to-moderate feature counts ( 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 , 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 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?
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 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 , , , or — and stack them into ; the model is still linear in even though it is nonlinear in the original input . The normal equations apply completely unchanged in this "polynomial regression" or basis-expansion setting, since the entire derivation only relied on being some linear combination of the columns of , never on what those columns actually represent.
Why does the space complexity advantage of X⊤X matter in practice?
Because has size regardless of how many training examples you have, you can compute it incrementally: process training rows one at a time (or in batches), accumulate the running sums and , and discard each row after use. This means fitting via the normal equations can work in a streaming setting with bounded memory, even if the full dataset of rows would never fit in memory at once — a genuinely useful property distinct from the closed-form formula itself.