Orthogonal projection can also be read as an optimization problem. Given a subspace \(U\subseteq \mathbb R^n\) and a vector \(\mathbf{x}_0\text{,}\) the projection \(\operatorname{proj}_U(\mathbf{x}_0)\) is the vector \(\mathbf{x}^*\in U\) that minimizes \(\|\mathbf{x}-\mathbf{x}_0\|\text{.}\)
This is the first version of a pattern that will recur in Units 5 and 7: choose a space of allowable approximations, choose a way to measure error, and find the point in the allowable space with smallest error.
The equation \(A\mathbf{x}=\mathbf{b}\) may have no solution because \(\mathbf{b}\notin\operatorname{col}(A)\text{.}\) The least-squares problem asks for \(\mathbf{x}\) so that \(A\mathbf{x}\) is as close as possible to \(\mathbf{b}\text{:}\)
Geometrically, \(A\mathbf{x}\) is a point in \(\operatorname{col}(A)\text{.}\) Thus the best possible \(A\hat{\mathbf{x}}\) is the projection of \(\mathbf{b}\) onto the column space:
The residual \(\mathbf{r}=\mathbf{b}-A\hat{\mathbf{x}}\) is orthogonal to every column of \(A\text{.}\) Equivalently, \(\mathbf{r}\in\operatorname{col}(A)^\perp=\operatorname{null}(A^T)\text{,}\) so
Theorem4.3.2.Normal equations from residual orthogonality.
If \(\hat{\mathbf{x}}\) minimizes \(\|A\mathbf{x}-\mathbf{b}\|\text{,}\) then the residual \(\mathbf{r}=\mathbf{b}-A\hat{\mathbf{x}}\) is orthogonal to \(\operatorname{col}(A)\text{.}\) Equivalently, \(\mathbf{r}\in\operatorname{col}(A)^\perp=\operatorname{null}(A^T)\text{,}\) so
The closest point \(A\hat{\mathbf{x}}\) in \(\operatorname{col}(A)\) is unique. The coefficient vector \(\hat{\mathbf{x}}\) is unique when the columns of \(A\) are linearly independent. If the columns are dependent, several different coefficient vectors may produce the same closest point.
Suppose that the columns of \(A\) are linearly independent. To show that \(A^T A\) is invertible, it is enough to show that \((A^T A)\mathbf{x}=\mathbf{0}\) has only the trivial solution. If \((A^T A)\mathbf{x}=\mathbf{0}\text{,}\) then
Therefore \(A\mathbf{x}=\mathbf{0}\text{.}\) Since the columns of \(A\) are linearly independent, \(\mathbf{x}=\mathbf{0}\text{.}\) Hence \(A^T A\) is invertible.
The first two coordinates of \(A\mathbf{x}=\mathbf{b}\) force \(x_1=1\) and \(x_2=2\text{,}\) but then the third coordinate would be \(3\text{,}\) not \(4\text{.}\) So the target is not reached exactly.
The residual is not zero, so the target is still not reached exactly. But the residual is orthogonal to the column space, so the fitted output is the closest reachable output.
xhat = np.linalg.lstsq(A, b, rcond=None)[0]
r = b - A @ xhat
A.T @ r
The vector \(\mathbf{r}\) is the residual. The output of A.T @ r should be close to zero because the least-squares residual is orthogonal to the columns of \(A\text{.}\)