When Ax = b has no solution, find the closest Ax: the orthogonal projection of b onto the column space. Derive projection matrices and normal equations geometrically and by calculus, connect the data-space and column-space views, and understand the numerical danger of AᵀA that motivates QR and SVD.
After this lesson you can
Derive projection onto a line and a subspace and prove it minimizes distance.
Characterize orthogonal projections by P² = P and Pᵀ = P and distinguish oblique projections.
Formulate a linear or polynomial fit as least squares and solve it using normal equations.
Interpret the same problem in data space and column space.
Explain why normal equations square the condition number.
Until now, a linear systemAx=b was a yes-or-no question: either b lies in the column space of A and there is a solution, or it does not and there is none. When data come from measuring the world, the answer is almost always “no”. Fitting a line y=C+Dt to m noisy points produces m equations C+Dti=yi with only two unknowns, and three noncollinear points suffice to make the system inconsistent. Yet the data carry plenty of information about C and D. The question, not the data, is at fault.
The same pattern—many more equations than unknowns and no exact solution—appears throughout practical work:
Regression and networks. A linear regression model trained with mean squared error solves exactly this lesson’s problem. So does a linear probe on frozen GPT activations: thousands of examples, hundreds of weights and a closed-form solution.
Robotics. To identify a linear model st+1≈Fst+Gut from a trajectory, each instant supplies linear equations in the entries of F and G; with hundreds of instants and dozens of unknowns the system is overdetermined. Camera calibration also uses dozens of correspondences between 3D points and pixels for about a dozen parameters.
Finance. With fixed decay parameter, the Nelson–Siegel model describes the interest-rate curve as a linear combination of three functions of maturity (level, slope and curvature). Fitting it to yields of dozens of bonds gives three unknowns and dozens of equations.
Change the question. If no x satisfies Ax=b, seek the x that leaves Axas close as possible to b. The key is a familiar observation: whichever x you choose, Ax is a combination of the columns, so it lies in col(A). The problem becomes geometric: which point in subspace col(A) is closest to b? The entire lesson follows from the answer: orthogonal projection.
We will use a small example throughout. Find the line that best fits points (1,1), (2,2) and (3,2). Requiring it to pass through all three gives
C+DC+2DC+3D=1=2=2
or, in matrix form,
A111123x[CD]=b122.
The first two equations give C=0 and D=1, whereupon the third says 3=2. There is no solution. By the end of the projection section we will have the best line, y=32+21t, and know in what sense it is best.
The closest shadow
Start with a case we can draw. Take A with two independent columns a1,a2∈R3, so col(A) is a plane through the origin, and an b outside that plane. Each x=(x1,x2) chooses a point Ax=x1a1+x2a2 on the plane. We seek the closest to b.
InteractiveThe closest shadow
b
a1
a2
plane col(A)
p, projection of b
error e=b−p
candidate Ax
Candidate
Radius ∥b−Ax∥2.086
Minimum ∥b−p∥1.537
∥p−Ax∥1.411
Pythagoras: 4.35=2.36+1.99
A⊤(b−Ax)=[−2.53−1.78]
x^ (the minimum)(0.22, 0.38)
The sphere intersects the plane in a circle through Ax: points inside are closer to b. The circle is always centered at p.
Drag Ax across the plane (or move x1 and x2). The blue sphere is centered at b with radius ∥b−Ax∥, so it always passes through Ax and intersects the plane in a circle. Press ‘Go to minimum’: the circle shrinks to a point, the sphere touches the plane only at p, and error e (red) is perpendicular to the plane. Try the two b buttons and drag the columns.
What you should have seen:
Points inside the circle are closer. The sphere consists of points at distance ∥b−Ax∥ from b; plane points inside it are better candidates. While the sphere intersects the plane in a circle of positive radius improvement is possible, and the optimum occurs when the circle degenerates to a point: the sphere is tangent to the plane.
The circle’s center does not move. However you move Ax, the intersection circle is always centered at p, the foot of the perpendicular from b. The readouts show why: ∥b−Ax∥2=∥b−p∥2+∥p−Ax∥2. This is Pythagoras for the right triangle with vertices b, p and Ax, and says the circle’s radius is ∥p−Ax∥.
Perpendicular to the plane means perpendicular to both columns. At the minimum, a1⊤(b−Ax^)=0 and a2⊤(b−Ax^)=0. Stacked together they give A⊤(b−Ax^)=0, the lesson’s central equation.
The two extremes. If b lies in the plane, p=b, error is zero and the system had an exact solution. If b is perpendicular to the plane, p=0 and x^=0: no column combination improves on doing nothing.
The rest turns these four observations into formulas and theorems, first for a line and then any subspace.
Projecting onto a line
The simplest case is a one-dimensional subspace: the line spanned by vector a=0 in Rm. Candidates are multiples xa, and the figure suggests the condition characterizing the best: error must be orthogonal to the line.
a⊤(b−x^a)=0⟺x^=a⊤aa⊤b,
and the projection of b onto the line is
projab=a⊤aa⊤ba.
That this condition gives the minimum takes one line to check. Write p=x^a and e=b−p. For any x, b−xa=e+(x^−x)a, and the two terms are orthogonal, so
∥b−xa∥2=∥e∥2+(x^−x)2∥a∥2,
which is never less than ∥e∥2 and equals it only at x=x^. Calculus gives the same: g(x)=∥b∥2−2xa⊤b+x2a⊤a is a parabola with minimum at x=a⊤b/a⊤a. Both paths agree, and will again in higher dimensions.
Rearranging factors, projection is a matrix applied to b:
p=aa⊤aa⊤b=Pa⊤aaa⊤b.
This P has rank one: all columns are multiples of a. It has two properties that will define orthogonal projection: P⊤=P, and P2=P, since projecting something already on the line does not move it.
Projection also proves the Cauchy–Schwarz inequality. Since p⊥e, Pythagoras gives ∥b∥2=∥p∥2+∥e∥2≥∥p∥2, and ∥p∥=a⊤b/∥a∥. Hence a⊤b≤∥a∥∥b∥, with equality if and only if e=0, that is, if b is a multiple of a. Orthogonal projection never lengthens.
Projecting onto a subspace
Now A∈Rm×n has n linearly independent columns a1,…,an (hence m≥n and rankA=n). Seek p=Ax^ in col(A) with error e=b−Ax^ perpendicular to all columns: aj⊤(b−Ax^)=0 for j=1,…,n. Stacked into a vector, those n conditions are
A⊤(b−Ax^)=0,
and rearranging gives a square system:
A⊤Ax^=A⊤b.
These n equations in n unknowns are the normal equations. “Normal” here means perpendicular: the error is normal to the subspace.
Condition A⊤e=0 has an interpretation in the map of the four fundamental subspaces: it says e∈null(A⊤). Since null(A⊤) is the orthogonal complement of col(A) and Rm=col(A)⊕null(A⊤), projection decomposes b into two components:
b=∈col(A)p+∈null(A⊤)e.
This decomposition is unique and independent of which columns describe the subspace. Hence the definition uses no matrices.
To solve for x^ invert A⊤A, a symmetric n×n matrix: the columns’ Gram matrix, with entries ai⊤aj. Its invertibility is exactly column independence. Prove it.
ProofWhen AᵀA is invertible
Prove: For A∈Rm×n, matrix A⊤A is invertible if and only if the columns of A are linearly independent.
0
A⊤A is square, so it is invertible if and only if its null space is {0}. The columns of A are independent if and only if null(A)={0}.
Step 1 of 4. What suffices to prove?
With independent columns solve for x^ to obtain projection as a matrix applied to b:
x^pP=(A⊤A)−1A⊤b,=Ax^=Pb,=A(A⊤A)−1A⊤.
P∈Rm×m is the projection matrix onto col(A). With n=1 and A=a it reduces to aa⊤/a⊤a. These formulas aid understanding, not computation: in practice solve the system and never form (A⊤A)−1 (see common mistakes).
We can now prove what the sphere showed: p is the unique point of col(A) closest to b.
ProofThe proof, using Pythagoras
Prove: For every x, ∥b−Ax∥≥∥b−p∥, with equality if and only if x=x^.
0
You know x^ satisfies the normal equations, A⊤(b−Ax^)=0. Fix any x.
Step 1 of 4. How do you start?
A special case shows why the general formula has (A⊤A)−1 in the middle. If the columns form an orthonormal basisq1,…,qn, matrix Q=[q1⋯qn] satisfies Q⊤Q=In and everything simplifies:
x^=Q⊤b,P=QQ⊤,
and projection becomes
p=QQ⊤b=j=1∑n(qj⊤b)qj.
The coefficients are dot products and projection is the sum of projections onto each line. For nonorthogonal columns that sum is wrong, and (A⊤A)−1 supplies the correction. For example, in R2 with a1=(1,0) and a2=(1,1) the column space is the entire plane, so the projection of b=(0,1) is b itself. But proja1b+proja2b=(0,0)+(21,21)=b. Finding an orthonormal basis of column space to stay in the easy case is the aim of QR factorization in the next lesson.
Projection matrices
Matrix P=A(A⊤A)−1A⊤ has a rigid structure. Each property has a one-line calculation and a geometric interpretation:
P2=P.P2=A(A⊤A)−1(A⊤A)(A⊤A)−1A⊤=P. Anything already in col(A) stays put when projected.
P⊤=P. The transpose of a symmetric matrix’s inverse is the inverse of its transpose, which is itself.
I−P is also an orthogonal projection, onto null(A⊤)=col(A)⊥: (I−P)b=e. Together they split b.
Its eigenvalues are 0 and 1. If Pv=λv with v=0, then λv=P2v=λ2v, hence λ∈{0,1}. Vectors in col(A) have eigenvalue 1 and those in null(A⊤) eigenvalue 0.
trP=n=rankP. By cyclicity of the trace, tr(A(A⊤A)−1A⊤)=tr((A⊤A)−1A⊤A)=trIn=n. Trace counts the dimensions projected onto.
Property 3 has a direct machine-learning use: to remove information carried by embeddings in unit direction u, apply I−uu⊤ to each vector. What remains is exactly the part orthogonal to u: the component in that direction becomes zero for all vectors. Note the limitation: if the same information is also distributed across other directions correlated with u, it remains.
The first two properties actually characterize orthogonal projections. To see why, separate two ideas that are often confused.
Proof
1. Every b can be written b=Pb+(I−P)b. The first term lies in col(P) and the second in null(P) because P(I−P)=P−P2=0. The sum is direct: if v=Pw and also Pv=0, then v=Pw=P2w=Pv=0.
2. If P⊤=P, for all y,b we have (Py)⊤(b−Pb)=y⊤P⊤(I−P)b=y⊤(P−P2)b=0, so the error is orthogonal to col(P). Conversely, if (Py)⊤(I−P)b=0 for all y,b, matrix P⊤(I−P) is zero, i.e. P⊤=P⊤P. The right side is symmetric, hence P⊤ is too, and P=P⊤.
3. For each b, both Pb and A(A⊤A)−1A⊤b are vectors p∈col(A) with b−p⊥col(A), and by definition that vector is unique. Two matrices that agree on every b are equal.
∎
Thus orthogonal projections are exactly symmetric idempotent matrices, and projection onto a subspace is a unique matrix regardless of which columns describe the subspace. Also, any projector’s trace is its rank: in a basis consisting of a basis of col(P) followed by one of null(P), the matrix of P is diag(1,…,1,0,…,0), and similar matrices have the same trace.
Oblique projectors exist and are useful, but do not give the closest point. The simplest is
P=[1010],P2=P,P⊤=P.
Its column space is the x axis and its null space the line x+y=0: it projects onto the horizontal axis along the diagonal, like a shadow with an angled sun. It maps b=(0,1) to (1,0), at distance 2 from b, whereas the nearest point on the axis is (0,0), at distance 1. Generally, if B∈Rm×n satisfies that B⊤A is invertible,
P=A(B⊤A)−1B⊤
is the projector onto col(A) along null(B⊤) (check P2=P). It is orthogonal exactly when null(B⊤)=col(A)⊥, meaning col(B)=col(A), and then one may equivalently take B=A.
InteractiveOblique versus orthogonal projection
b
shadow Pb
b−Pb
line col(P)
light direction null(P)
orthogonal projection p
P=[0.660.240.940.34]
P2−PF0.000
P−P⊤F0.990
Distance to shadow ∥b−Pb∥2.190
Minimum distance ∥b−p∥1.794
∥P∥2=1/cosφ1.221
P2=P, but P=P⊤: oblique projection. Points on the line inside the circle are closer to b than its shadow. Also ∥Pb∥>∥b∥: the shadow is longer than the vector.
Light falls at angle φ to the perpendicular to line col(P) and the shadow of b is Pb; the light's direction is null(P). For any φ, P2=P. But the circle centered at b through the shadow crosses the line again, and points in the blue band are closer to b than the shadow. Set φ to 0: simultaneously P becomes symmetric, the circle tangent, and ∥P∥2 falls to 1.
In the plane, with unit s along the line and unit w perpendicular to the light, the projector is P=sw⊤/(w⊤s), the n=1 case of the formula above, with spectral norm ∥P∥2=∥s∥∥w∥/w⊤s=1/cosφ. An oblique projection can lengthen vectors: you saw this when the shadow became longer than b. An orthogonal one never does, because ∥Pb∥2=∥b∥2−∥e∥2. Numerically this matters: transformations that do not lengthen also do not amplify rounding errors, so stable algorithms use orthogonal projections and reflections.
Least squares
We have the geometry. Now put it in optimization language, without assuming independent columns.
Before deriving anything, see what “squares” means. In fitting a line, each residual is a point’s vertical distance to the line, and its square is literally the area of a square.
InteractiveActual squares
data (ti,yi)
your line y=C+Dt
squares ri2
The data and the line: (t,y) plane
The parameters: (C,D) plane and area contours
Total area ∑iri23.350
Minimum possible?
∑iri−0.300
∑itiri5.310
Largest square30 % of the area
If the sums ∑iri and ∑itiri are not zero, the line can still be improved: apart from the factor −2, they are the two components of the area gradient.
Each residual ri=yi−(C+Dti) is drawn as a square of side ∣ri∣ (the plane has the same scale on both axes), and the goal is to minimize total red area. Adjust C and D with sliders or by dragging (C,D) in the right panel, where area is a quadratic function with elliptical contours. When ready, press ‘Go to optimum’ and inspect the two sums below. Finally create an outlier and enable the ℓ1 line.
Three things to notice:
Area is a quadratic in (C,D) with a unique minimum. Its contours are elongated tilted ellipses. The tilt means C and D compensate: increasing slope and decreasing intercept can cost little. This occurs because ti are not centered; with tˉ=0, matrix A⊤A would be diagonal and ellipse axes aligned.
At the optimum, both ∑iri=0 and ∑itiri=0 hold. These are the two rows of A⊤r=0 for A=[1t]: the residual is orthogonal to the column of ones and the column of ti. The first implies the optimal line passes through the data’s center of gravity (tˉ,yˉ).
An outlier pulls the line. A residual twice as large weighs four times as much, so the line bends to shrink the largest square even at the expense of all others. The ℓ1 line, minimizing ∑i∣ri∣, barely moves; the price is no closed formula, and it is computed as a linear program.
Why squares?
If squares are so sensitive to outliers, why are they the default? There are three reasons, each a different view of the same problem.
Geometry. Sum of squares is squared Euclidean distance in Rm, which comes from an inner product. This yields perpendicularity and Pythagoras, and the solution depends linearly on the data: p=Pb. With ∑i∣ri∣ or maxi∣ri∣, the ℓ1 and ℓ∞ norms, the unit ball has corners, there is no underlying inner product, and no linear formula.
Statistics. If bi=(Ax)i+εi with independent εi and N(0,σ2), log-likelihood is −2σ21∥b−Ax∥2 plus a constant: the maximum-likelihood estimator under Gaussian noise is least squares. With Laplace noise maximum likelihood leads to ℓ1. Without assuming normality, if noise has zero mean, constant variance and is uncorrelated, the Gauss–Markov theorem guarantees least squares is the best linear unbiased estimator.
Calculus. The objective is a differentiable convex quadratic with linear gradient. Its exact minimum comes from a linear system; when the system is too large, gradient descent, including stochastic descent, converges to the global minimum because there are no spurious local minima.
The price is the outlier sensitivity you just saw. Robust losses, such as ℓ1 or Huber loss, quadratic near zero and linear farther away, trade that sensitivity for the closed-form solution.
Two derivations of the same equation
By geometry. As x ranges over Rn, Ax ranges over col(A); distance ∥Ax−b∥ is minimal exactly when Ax is projection p of b, i.e. when A⊤(b−Ax)=0.
By calculus. Function f(x)=∥Ax−b∥2 is differentiable and its gradient is calculated by expanding the square. Try to predict each step before revealing it.
f(x)=(Ax−b)⊤(Ax−b)
The squared norm of Ax−b is its dot product with itself.
1/5
The first-order condition plus convexity suffice, but a more direct argument also works with dependent columns. If x^ satisfies the normal equations, for every x:
∥Ax−b∥2=∥Ax^−b∥2+∥A(x−x^)∥2.
Write Ax−b=(Ax^−b)+A(x−x^) and observe the cross term is 2(x−x^)⊤A⊤(Ax^−b)=0. This is Pythagoras written as “completing the square”. It solves the problem completely.
Proof
1. If x^ satisfies the normal equations, the identity above gives ∥Ax−b∥≥∥Ax^−b∥ for every x. Conversely, a minimizer makes the gradient zero, and that gradient is −2A⊤(b−Ax^).
2. The previous section’s exercise proved null(A⊤A)=null(A) (without using independence). By rank-nullity, rank(A⊤A)=n−dimnull(A)=rankA=rankA⊤. Since col(A⊤A)⊆col(A⊤) and dimensions coincide, col(A⊤A)=col(A⊤). The right side A⊤b lies in col(A⊤), so the system is consistent.
3. The solution set is x^+null(A⊤A)=x^+null(A), a single point if and only if null(A)={0}.
4. If x^1 and x^2 are solutions, apply the identity with x^=x^1 and x=x^2; since both minimize, this gives ∥A(x^2−x^1)∥2=0. Thus Ax^ is independent of the chosen solution, and residual b−Ax^ is orthogonal to col(A) by the normal equations: Ax^ is the projection.
∎
With dependent columns there are infinitely many x^ but only one p. Choosing the minimum-norm solution leads to the pseudoinverse in lesson 18.
For line y=C+Dt the normal equations can be solved by hand. With A=[1t] they are
[m∑iti∑iti∑iti2][CD]=[∑iyi∑itiyi].
Dividing the first by m gives C+Dtˉ=yˉ, the line through the center of gravity, and substituting into the second gives
D^=∑i(ti−tˉ)2∑i(ti−tˉ)(yi−yˉ),
and then C^=yˉ−D^tˉ.
Two views of the same problem
A line fit can be drawn in two different spaces; moving fluently between them distinguishes applying the formula from understanding it.
Data space, plane (t,y)
Observation space, Rm
m points (ti,yi)
one vector b=(y1,…,ym)
a line y=C+Dt
a point C1+Dt on plane col(A)
line heights at ti
coordinates of Ax
vertical residuals ei
components of vector e
sum of squares ∑iei2
∥e∥2, Pythagoras in Rm
optimal line
projection p=Pb
∑iei=0 and ∑itiei=0
e⊥1 and e⊥t
With three points, observation space is R3 and can be visualized.
Drag the points on the left. Each controls one coordinate of b (height yi) and one of t (abscissa ti), so on the right both b and the plane col(A) spanned by 1 and t move. The three red residuals on the left are the three components of red vector e on the right, perpendicular to the plane; readouts 1⊤e and t⊤e are always 0. The right scene is rotated so the initial plane is horizontal; labeled axes represent the three observations.
The right-hand picture scales. With a million data points and a thousand features the data plane cannot be drawn, but the picture in Rm stays the same: a vector b, a subspace col(A) of dimension n, and the perpendicular between them. The decomposition of p in the figure, first C^ times 1 then D^ times t, reminds us fitted coefficients are coordinates of p in the basis formed by the columns.
In this picture, the statistical analysis-of-variance table is Pythagoras. If the model has an intercept, yˉ1 lies in col(A), so p−yˉ1 does too, and is orthogonal to e:
variacioˊn total∥b−yˉ1∥2=explicada por el modelo∥p−yˉ1∥2+residual∥e∥2.
The coefficient of determinationR2 is the ratio of explained to total variation, i.e. cos2θ, with θ the angle between centered vectors b−yˉ1 and p−yˉ1. For a line, p−yˉ1=D^(t−tˉ1), so cosine between centered data b−yˉ1 and t−tˉ1, which is correlation coefficient ρ between t and y, equals ±cosθ with the sign of D^. Hence in simple regression R2=ρ2: squared correlation.
The picture in Rm also explains statistical “degrees of freedom”. The residual lives in null(A⊤), of dimension m−n. If data are b=Ax⋆+ε with zero-mean noise and covariance σ2I, then e=(I−P)ε because (I−P)A=0, and
E∥e∥2=E[ε⊤(I−P)ε]=σ2tr(I−P)=σ2(m−n).
That is why noise variance is estimated with ∥e∥2/(m−n) rather than ∥e∥2/m: the residual can move in only m−n directions. The sampling distribution of coefficients is studied in module 5.
Design matrix, polynomial fitting and leverage
Nothing above requires the model to be a line. It suffices to be linear in parameters: y≈x1ϕ1(t)+⋯+xnϕn(t) with fixed functions ϕj, called features in machine learning. Matrix A with entries aij=ϕj(ti) is the design matrix: one row per observation and one column per feature.
Polynomials. With ϕj(t)=tj−1, the design matrix is a Vandermonde matrix. Fitting a parabola is linear least squares although the curve is not a line: linear refers to coefficients. This is polynomial regression in module 11.
Other bases. Sines and cosines for periodic signals, splines, Nelson–Siegel’s three curves or frozen network activations: the design matrix changes, not the theory.
Multiple targets. If instead of one vector b there are k (the columns of B∈Rm×k), minimizing Frobenius norm∥AX−B∥F2 separately minimizes the sum of squares of each column, and X^=(A⊤A)−1A⊤B. The same P projects all k columns. This fits a linear probe with k outputs in closed form, or a linear layer mimicking another from its activations.
In statistics the projection matrix is called the hat matrix, written H because it “puts a hat” on the data: fitted values are y^=Hy, with y=b and y^=p. Its diagonal measures something specific. Since y^i=∑jhijyj, derivative ∂yi∂y^i is hii: leveragehii of observation i measures how much its own fitted value moves when it moves. Projection properties yield:
0≤hii≤1. Since H=H2=H⊤H, we have hii=∑jhij2=hii2+∑j=ihij2≥hii2.
∑ihii=trH=n. Mean leverage is n/m. A common rule marks points with hii>2n/m, twice the mean, as high leverage.
With an intercept, hii≥1/m and each row sums to 1. If 1∈col(A), then H1=1: each y^i is a weighted average of all yj, with weights hij summing to 1 that may be negative. Also H−m111⊤ is symmetric and idempotent (check using H1=1), so its diagonal hii−1/m is nonnegative.
For a line, leverage grows with distance from the center. Columns 1 and t−tˉ1 are orthogonal and span the same plane, so H is the sum of their projections:
hii=m1+∑j(tj−tˉ)2(ti−tˉ)2.
In the line example, P had diagonal (65,31,65): endpoints matter more than the center, as the formula confirms: 31+21=65.
InteractiveLeverage and the hat matrix
data
degree-1 fit
fit without point i
residuals
Leverage hjj of each point, below its tj; dashed: threshold 2n/m
Bars
Parameters n=k+12
trH=∑jhjj2.000
hii of point 90.721
Threshold 2n/m0.444
Residual ei−0.683
y^i with and without the point2.58 → 4.35
High-leverage point: h99=0.72>2n/m=0.44. Raising its y by one raises its fitted value by 0.72.
Nine points and a degree-k polynomial fit. The bars below, aligned with points, show leverage hjj of each or, in the other mode, row i of H: weights with which y^i averages all yj. Point 9, far from the rest, starts selected: its leverage exceeds threshold 2n/m and removing it completely changes the fit (dashed line). Increase the degree, drag points horizontally, and check the bars always sum to n=k+1.
A point with hii close to 1 nearly determines its own fitted value, so its residual is misleadingly small. Two formulas quantify this. If noise has covariance σ2I, the variance of residual i is σ2(1−hii): high-leverage points have small residuals by construction, so detect outliers using standardized residuals, as in regression diagnostics. If refitted without observation i, its prediction becomes y^(i), with
a consequence of the Sherman–Morrison formula (lesson 14). The first allows leave-one-out cross-validation error to be computed with one fit rather than repeating it m times.
When AᵀA is nearly singular
Normal equations are the shortest way to write the solution and often the worst way to compute it. The problem is the condition number. For A with independent columns, let
σmaxσmin=∥x∥=1max∥Ax∥,=∥x∥=1min∥Ax∥,
be the maximum and minimum stretch of a unit vector, and κ(A)=σmax/σmin their ratio. Since x⊤(A⊤A)x=∥Ax∥2, the quadratic form of A⊤A takes exactly the interval [σmin2,σmax2] on the unit sphere. For a symmetric positive semidefinite matrix these extremes are its largest and smallest eigenvalues (the Rayleigh quotient in lesson 12), and its condition number is their ratio. Therefore
κ(A⊤A)=κ(A)2.
In double precision the unit roundoff is u≈1.1×10−16, and a stable method solving a system with condition κ can lose on the order of log10κ digits. Normal equations lose 2log10κ(A): if κ(A)=108, then κ(A⊤A)=1016≈1/u and no digits are guaranteed.
There is a nuance: sensitivity of the least-squares problem itself to perturbations in A is of order κ(A)+κ(A)2tanθ, where θ is the angle between b and col(A). If the residual is small, θ≈0 and the problem is only as sensitive as κ(A): normal equations waste half the available digits. If the residual is large, term κ2 is already in the problem and normal equations lose little more. Detailed analysis appears in numerical least squares (module 9).
Normal equations have cost in their favor: forming A⊤A takes about mn2 operations exploiting symmetry, and Cholesky solution n3/3; QR with Householder reflections costs about 2mn2−32n3. With m≫n, normal equations are roughly twice as fast. The stable route, seen next lesson, factorizes A=QR with Q having orthonormal columns and R invertible upper triangular. Then A⊤A=R⊤R and normal equations reduce to
Rx^=Q⊤b,P=QQ⊤,
and since κ(R)=κ(A), nothing is squared. When columns are dependent or nearly so, use SVD, which gives the pseudoinverse and determines which directions are noise; when changing the problem is appropriate, ridge regression solves (A⊤A+λI)x=A⊤b, whose condition number (σmax2+λ)/(σmin2+λ) no longer explodes.
Implementation from scratch
First, projection onto a line and onto a subspace, with the lesson’s example. The normal equations are solved; no inverse is computed.
[ ]Projections from scratchBrowser
import numpy as np
np.set_printoptions(precision=4, suppress=True)
def proyectar_en_recta(a, b):
"""Proyección ortogonal de b sobre la recta de a (a no nulo)."""
return (a @ b) / (a @ a) * a
b = np.array([1.0, 2.0, 2.0])
uno = np.ones(3)
p = proyectar_en_recta(uno, b)
print("p =", p, " (la media de b, repetida)")
print("e =", b - p, " uno·e =", uno @ (b - p))
A = np.array([[1.0, 1.0],
[1.0, 2.0],
[1.0, 3.0]])
# ecuaciones normales: se resuelven, no se invierte AᵀA
x_hat = np.linalg.solve(A.T @ A, A.T @ b)
p = A @ x_hat
e = b - p
print("x̂ =", x_hat, " p =", p, " e =", e)
print("Aᵀe =", A.T @ e, " ‖e‖² =", e @ e)
If uno·e comes out on the order of 10−16 instead of 0, that is rounding: orthogonality holds to machine precision. Next examine projection-matrix properties on a random A of 8×3, and leverage computed two ways: as the diagonal of P and as squared row norms of an orthonormal basis Q of col(A), since P=QQ⊤ implies hii=∥fila i de Q∥2. The second method forms no m×m matrix.
[ ]Projectors and leverageBrowser
rng = np.random.default_rng(0)
m, n = 8, 3
A = rng.normal(size=(m, n))
# P = A (AᵀA)⁻¹ Aᵀ, sin formar ninguna inversa
P = A @ np.linalg.solve(A.T @ A, A.T)
print("‖P² − P‖ =", np.linalg.norm(P @ P - P))
print("‖P − Pᵀ‖ =", np.linalg.norm(P - P.T))
print("tr P =", round(np.trace(P), 12),
" rango de A =", np.linalg.matrix_rank(A))
autovalores = np.sort(np.linalg.eigvalsh(P))[::-1]
print("autovalores de P:", np.round(autovalores, 10))
# base ortonormal de col(A) (lección 9): P = QQᵀ
Q, R = np.linalg.qr(A)
print("‖P − QQᵀ‖ =", np.linalg.norm(P - Q @ Q.T))
# diag(QQᵀ) = normas al cuadrado de las filas de Q
h = np.sum(Q**2, axis=1)
print("apalancamientos:", h, " suma:", h.sum())
The eigenvalues are three ones and five zeros, and trace equals rank. Now consider data with a distant point: the closed leverage formula for a line agrees with QR, and the distant point alone exceeds threshold 2n/m.
[ ]The most influential pointBrowser
t = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 25.0])
A = np.column_stack([np.ones_like(t), t])
Q, _ = np.linalg.qr(A)
h = np.sum(Q**2, axis=1)
tc = t - t.mean()
formula = 1 / len(t) + tc**2 / np.sum(tc**2)
print("h :", h)
print("fórmula :", formula)
umbral = 2 * A.shape[1] / len(t)
print("umbral 2n/m =", round(umbral, 4),
" puntos por encima:", np.where(h > umbral)[0])
The main experiment solves normal equations using LU factorization with partial pivoting from lesson 4. This compact version stores L and U in one matrix and the permutation as an index vector.
[ ]Custom LU and normal equationsBrowser
def lu_factor(M):
"""PM = LU con pivoteo parcial.
Devuelve L (sin su diagonal de unos) y U en una sola matriz,
y la permutación P como vector de índices.
"""
U = np.array(M, dtype=float)
k_max = U.shape[0]
perm = np.arange(k_max)
for k in range(k_max - 1):
# pivote: el mayor en valor absoluto de la columna k
i = k + np.argmax(np.abs(U[k:, k]))
if i != k:
U[[k, i]] = U[[i, k]]
perm[[k, i]] = perm[[i, k]]
# multiplicadores (columna k de L) y actualización
U[k + 1:, k] /= U[k, k]
U[k + 1:, k + 1:] -= np.outer(U[k + 1:, k], U[k, k + 1:])
return U, perm
def lu_solve(LU, perm, rhs):
y = np.array(rhs, dtype=float)[perm]
k_max = len(y)
for i in range(k_max): # L y = P rhs
y[i] -= LU[i, :i] @ y[:i]
for i in reversed(range(k_max)): # U x = y
y[i] = (y[i] - LU[i, i + 1:] @ y[i + 1:]) / LU[i, i]
return y
def lstsq_normales(A, b):
"""Mínimos cuadrados por ecuaciones normales con la LU propia."""
LU, perm = lu_factor(A.T @ A)
return lu_solve(LU, perm, A.T @ b)
A = np.array([[1.0, 1.0], [1.0, 2.0], [1.0, 3.0]])
print(lstsq_normales(A, np.array([1.0, 2.0, 2.0])))
The experiment fits polynomials of degree d=1,…,15 to 50 points in [0,1] using monomial basis 1,t,…,td. Data are generated without noise from known coefficients (all equal to 1), so the exact solution has zero residual and all measured error is numerical. Compare normal equations with np.linalg.lstsq, which uses SVD.
[ ]The cost of squaring the condition numberBrowser
import matplotlib.pyplot as plt
m = 50
t = np.linspace(0, 1, m)
grados = np.arange(1, 16)
kA, kN, err_ne, err_ls = [], [], [], []
for d in grados:
# columnas 1, t, t², ..., t^d; coeficientes verdaderos, todos 1
A = np.vander(t, d + 1, increasing=True)
c = np.ones(d + 1)
b = A @ c # sin ruido: el residuo óptimo es 0
x_ne = lstsq_normales(A, b)
x_ls = np.linalg.lstsq(A, b, rcond=None)[0]
kA.append(np.linalg.cond(A))
kN.append(np.linalg.cond(A.T @ A))
err_ne.append(np.linalg.norm(x_ne - c) / np.linalg.norm(c))
err_ls.append(np.linalg.norm(x_ls - c) / np.linalg.norm(c))
kA = np.array(kA)
print(" d κ(A) κ(A)² κ(AᵀA) err normales err lstsq")
filas = zip(grados, kA, kN, err_ne, err_ls)
for d, a, nn, en, el in filas:
print(f"{d:2d} {a:7.1e} {a**2:7.1e} {nn:7.1e}"
f" {en:11.1e} {el:9.1e}")
u = np.finfo(float).eps / 2
plt.figure(figsize=(7, 4))
plt.semilogy(grados, err_ne, "o-", label="normales (LU propia)")
plt.semilogy(grados, err_ls, "s-", label="lstsq (SVD)")
plt.semilogy(grados, u * kA**2, "--", label="u·κ(A)²")
plt.semilogy(grados, u * kA, ":", label="u·κ(A)")
plt.xlabel("grado d del polinomio")
plt.ylabel("error relativo de los coeficientes")
plt.ylim(1e-17, 1e3)
plt.legend()
plt.title("Elevar al cuadrado el condicionamiento cuesta dígitos")
plt.show()
Three observations. Column κ(A)2 matches computed κ(A⊤A) while below 1/u≈1016; above that, the computed figure loses meaning because stored A⊤A is already numerically singular. Normal-equation error follows line uκ(A)2 and exceeds 100% around degree 11 or 12. Error from lstsq follows, and here even stays below, line uκ(A): around degree 15 it retains five or six correct digits. The monomial basis causes κ(A) to grow this way; orthogonal polynomial bases avoid it, hence numpy.polynomial.
Finally, the example where forming A⊤A destroys information:
[ ]Forming AᵀA can be irreversibleBrowser
eps = 1e-8
A = np.array([[1.0, 1.0],
[eps, 0.0],
[0.0, eps]])
# la solución exacta es x = (1, 1), con residuo 0
b = np.array([2.0, eps, eps])
N = A.T @ A
print("AᵀA calculada =\n", N)
print("¿1 + eps² == 1?", 1 + eps**2 == 1)
try:
print("normales:", np.linalg.solve(N, A.T @ b))
except np.linalg.LinAlgError as err:
print("normales: LinAlgError,", err)
Q, R = np.linalg.qr(A)
print("QR :", np.linalg.solve(R, Q.T @ b))
print("lstsq :", np.linalg.lstsq(A, b, rcond=None)[0])
Depending on the LAPACK library used to compile NumPy, solve on that singular matrix raises LinAlgError (on the laptop) or silently returns nan (in the browser); neither recovers anything. QR and lstsq, which never form A⊤A, recover x=(1,1).
The professional version
In practice normal equations are not written by hand. These are the usual tools and what they do internally.
[ ]Least squares with librariesBrowser
from scipy import linalg as sla
from numpy.polynomial import Polynomial
rng = np.random.default_rng(1)
t = np.sort(rng.uniform(0, 10, 40))
y = 1.5 + 0.8 * t + rng.normal(scale=1.0, size=t.size)
A = np.column_stack([np.ones_like(t), t])
x1, rss, rango, sv = np.linalg.lstsq(A, y, rcond=None)
x2 = sla.lstsq(A, y)[0] # LAPACK gelsd por defecto
print("numpy :", x1, " RSS =", rss, " rango =", rango)
print("scipy :", x2)
print("normales:", lstsq_normales(A, y))
# Polynomial.fit reescala t a [-1, 1] antes de ajustar
pf = Polynomial.fit(t, y, deg=3)
print("cúbica en la base 1, t, t², t³:", pf.convert().coef)
In scikit-learn, the same fit needs no column of ones (the first library import takes a few seconds in the browser):
[ ]The same fit with scikit-learnBrowser
from sklearn.linear_model import LinearRegression
# LinearRegression añade él solo el término independiente
modelo = LinearRegression().fit(t[:, None], y)
print("sklearn :", np.array([modelo.intercept_, modelo.coef_[0]]))
np.linalg.lstsq(A, b, rcond=None) uses SVD (LAPACK routine gelsd) and returns solution, residual sum of squares (an empty vector if rank is below n or if m≤n), numerical rank and singular values. Singular values below rcond times the largest are treated as zero, giving the minimum-norm solution.
scipy.linalg.lstsq selects the algorithm with lapack_driver: 'gelsd' (SVD, default), 'gelsy' (column-pivoted QR, faster) or 'gelss'.
sklearn.linear_model.LinearRegression adds the intercept by default without creating a ones column (fit_intercept=True), and with dense data solves using scipy.linalg.lstsq.
numpy.polynomial.Polynomial.fit rescales t to [−1,1] before building the design matrix, greatly improving conditioning; .convert() returns coefficients in the original monomial basis.
PyTorch: torch.linalg.lstsq(A, B) solves batches. On GPU only the QR-based 'gels' driver is supported, assuming A has full rank.
Leverage: with statsmodels, sm.OLS(y, A).fit().get_influence().hat_matrix_diag.
From scratch in this lesson
Professional equivalent
Method
lstsq_normales (Gram and custom LU)
scipy.linalg.cho_solve on A⊤A
normal equations
Rx^=Q⊤b
np.linalg.qr and scipy.linalg.solve_triangular
QR (lesson 9)
none yet
np.linalg.lstsq, scipy.linalg.lstsq
SVD (lessons 15 and 18)
np.sum(Q**2, axis=1)
statsmodels hat_matrix_diag
leverage
Common mistakes
Exercises
Quiz
Which matrices are orthogonal projections?
More than one answer may be correct.
Numeric
Fit line y=C+Dt by least squares to points (0,6), (1,0) and (2,0). What is C?
Numeric
What is the trace of the orthogonal projection matrix onto a three-dimensional subspace of R10?
Numeric
Let A have columns (1,1,0) and (0,1,1), and b=(1,0,0). How far is b from plane col(A)?
Quiz
You fit a line through the origin, y≈Dt, by least squares (the design matrix has only column t). What is guaranteed about residuals ri?
Quiz
You add a new column c to A (one feature) and solve again. What happens to minimum residual ∥b−Ax^∥?
Numeric
Fit a line y=C+Dt to five points with abscissas t=0,1,2,3,10. What is the leverage h55 of the point at t=10?
Quiz
A least-squares problem with small residual has κ(A)≈106 and uses double precision (u≈10−16). Approximately how many correct digits would you expect from normal equations and QR?
Quiz
If P is an orthogonal projection on Rm, what is R=I−2P?
Numeric
In a least-squares fit, observation i has leverage hii=0.9 and residual ei=0.2. When refitting without it, what is y^i−y^(i), the difference between its fitted value with it and prediction without it?
Code
Implement projection_matrix(A), returning the m×m matrix of orthogonal projection onto col(A), and lstsq_normal(A, b), returning tuple (x_hat, h): the normal-equation least-squares solution and leverages hii. Assume independent columns, do not compute explicit inverses (use np.linalg.solve), and obtain h without forming the m×m matrix.
import numpy as np
def projection_matrix(A):
"""Proyección ortogonal (m x m) sobre col(A)."""
# tu código
pass
def lstsq_normal(A, b):
"""Devuelve (x_hat, h) por ecuaciones normales."""
# tu código
pass
Shift+Enter to run
Summary
When Ax=b has no solution, find Ax closest to b. Since Ax ranges over col(A), the answer is the orthogonal projection p of b onto col(A), and its optimality is Pythagoras.
Error e=b−p is perpendicular to every column: A⊤(b−Ax^)=0. This gives normal equations A⊤Ax^=A⊤b, which calculus obtains by setting the gradient to zero and which always have a solution.
With independent columns, P=A(A⊤A)−1A⊤. Orthogonal projections are exactly matrices satisfying P2=P and P⊤=P; their eigenvalues are 0 and 1, and trace is subspace dimension. Nonsymmetric idempotents are oblique and do not give the closest point.
The same fit can be viewed as m points and a line in the data plane, or as vector b projected onto a subspace of Rm. Residuals are coordinates of e, and the diagonal of P, leverage, measures how much each observation determines its own fit.
κ(A⊤A)=κ(A)2: forming A⊤A can destroy half the digits or all information. Hence solve with QR or SVD.
Key idea
Solving Ax≈b by least squares means orthogonally projecting b onto the column space. Everything else—normal equations, projection matrix, regression line and leverage—follows from one condition: error is perpendicular to each column.