Skip to content

Least squares, explained

6 min read

Short answer

When Ax=bA\mathbf x=\mathbf b has no exact solution, the least-squares solution x^\hat{\mathbf x} makes ∣Ax−b∣|A\mathbf x-\mathbf b| as small as possible. It solves the normal equations ATA x^=ATbA^TA\,\hat{\mathbf x}=A^T\mathbf b. Geometrically, Ax^A\hat{\mathbf x} is the projection of b\mathbf b onto the column space of AA, so the error is perpendicular to every column.

Diagram(0,1)(1,2)(2,2)
No line passes through all three points. The least-squares line y = 7/6 + x/2 minimizes the sum of the squared vertical gaps.

Why the normal equations

The closest point in the column space is the one whose error b−Ax^\mathbf b-A\hat{\mathbf x} is perpendicular to the column space, meaning AT(b−Ax^)=0A^T(\mathbf b-A\hat{\mathbf x})=\mathbf 0. Rearranging gives ATAx^=ATbA^TA\hat{\mathbf x}=A^T\mathbf b. If the columns of AA are independent, ATAA^TA is invertible and the solution is unique.

Fitting a line

To fit y=a+bxy=a+bx to data points, each point gives one equation a+bxi=yia+bx_i=y_i. Stack them into A(ab)=yA\begin{pmatrix}a\\b\end{pmatrix}=\mathbf y with a column of ones and a column of xx values, then solve the normal equations.

Worked example

Fit y=a+bxy=a+bx to the points (0,1),(1,2),(2,2)(0,1),(1,2),(2,2).

A=(101112)A=\begin{pmatrix}1&0\\1&1\\1&2\end{pmatrix} and y=(1,2,2)\mathbf y=(1,2,2). Then ATA=(3335)A^TA=\begin{pmatrix}3&3\\3&5\end{pmatrix} and ATy=(5,6)A^T\mathbf y=(5,6).

Solve 3a+3b=53a+3b=5 and 3a+5b=63a+5b=6: subtract to get 2b=12b=1, so b=12b=\tfrac12 and a=53−12=76a=\tfrac53-\tfrac12=\tfrac76.

Check: the residuals are −16,13,−16-\tfrac16,\tfrac13,-\tfrac16, which add to 0 and satisfy 0⋅(−16)+1⋅13+2⋅(−16)=00\cdot(-\tfrac16)+1\cdot\tfrac13+2\cdot(-\tfrac16)=0, so the error is perpendicular to both columns. ✓

Try it yourself

Fit y=a+bxy=a+bx to (0,0),(1,1),(2,1)(0,0),(1,1),(2,1).

Show the answer

ATA=(3335)A^TA=\begin{pmatrix}3&3\\3&5\end{pmatrix} and ATy=(2,3)A^T\mathbf y=(2,3). Solving 3a+3b=23a+3b=2, 3a+5b=33a+5b=3 gives b=12b=\tfrac12 and a=23−12=16a=\tfrac23-\tfrac12=\tfrac16, so y=16+x2y=\tfrac16+\tfrac x2.

Keep going with practice

Least squares ties together projections and matrices in Vidi's Linear Algebra & Probability course.