Lab 4.4

Least Squares as Orthogonal Projection

Focus
minimize error → project b → check the residual
Notebook
Ch4-4 Least Squares.ipynb

Lab goal

Find the closest reachable output to b, explain why the residual is perpendicular to Col(A), and distinguish unique fitted values from possibly non-unique coefficients.

Lecture-note concepts
  • Euclidean squared error
  • Normal equations
  • Orthogonal projection
  • Reduced QR
  • Rank and uniqueness

Code extensionCompare the lecture’s normal equations with reduced QR and NumPy lstsq; then duplicate a column to see which quantities stay unique.

Lecture 4 · Reading guide

Read the symbols first

Wooseok Ha, MAS110 Lecture 4: Orthogonality and Projections (Fall 2026), lec04.pdf. Least squares: printed slides 61–68 / PDF pages 71–78. Projection: slides 29–33 and 39 / PDF pages 33–37 and 44. QR example: slides 49–51 / PDF pages 57–59.

Chapter 3 asked whether Aθ=bA\theta = b has an exact solution. Here b may lie outside Col(A), so we choose coefficients whose output is as close to b as possible. Throughout this lab, vectors and matrices are real and distance means the standard Euclidean distance. The running example is exactly the lecture’s 3 × 2 matrix, not a square system with an inverse.

φ;θ;qj;wj;G\varphi;\quad\theta;\quad q_j;\quad w_j;\quad G
Across Chapter 4, φ\varphi denotes angles and θ\theta denotes model coefficients. In 4.3, qjq_{j} names a normalized column while wjw_{j} is a remainder; the lecture previously labels normalized Gram–Schmidt vectors wiw_{i}. G always denotes a Gram matrix: here ATAA^{\mathsf T}A, and in 4.2 the polynomial integral metric. The inner product being used determines which Gram matrix applies.
A∈Rm×n;here m=3, n=2A\in\mathbb R^{m\times n};\quad\text{here }m=3,\ n=2
A is the design matrix: m measurements (rows) and n coefficients (columns). θ∈Rn\theta \in \mathbb R^{n} is an input; AθA\theta and b∈Rmb \in \mathbb R^{m} are outputs in measurement space. More rows than columns does not itself prove inconsistency; b∉Col⁡(A)b \notin \operatorname{Col}(A) does.
ai∈Rn;row i is aiTa_i\in\mathbb R^n;\quad\text{row }i\text{ is }a_i^{\mathsf T}
In the lecture’s data model, aia_{i} is the feature vector for measurement i, so (Aθ)i=aiTθ=θTai(A\theta )_{i} = a_{i}^{\mathsf T}\theta = \theta ^{\mathsf T}a_{i}. This notation names rows via their transposes. A[:, j] in Python instead selects a column of A, a vector in Rm\mathbb R^{m}.
θ;θ^;b^=Aθ^\theta;\quad\hat\theta;\quad\hat b=A\hat\theta
θ\theta is any candidate coefficient vector; the hat marks a minimizing choice θ^\hat{\theta}. b^\hat{b} is the fitted output, not another name for the coefficients. Here θ^\hat{\theta} has 2 coordinates and b^\hat{b} has 3. The lecture writes the fitted vector as Aθ^;b^A\hat{\theta}; \hat{b} is an added shorthand on this page.
e=b−b^;f(θ)=∥Aθ−b∥22e=b-\hat b;\quad f(\theta)=\lVert A\theta-b\rVert_2^2
e is the observed-minus-fitted residual vector. At θ^,Aθ^−b=−e\hat{\theta}, A\hat{\theta} - b = -e; both signs have the same squared length. The lecture uses |v| for Euclidean vector length; this page writes ∥v∥2\Vert v\Vert _{2}. The actual measurement noise εi\varepsilon _{i} in the model need not equal the fitted residual eie_{i}.
⟨u,v⟩=uTv;e⊥Col⁡(A)\langle u,v\rangle=u^{\mathsf T}v;\quad e\perp\operatorname{Col}(A)
T\mathsf T means transpose; ⊥\perp means orthogonal. The condition means e has zero inner product with every column combination of A. It is equivalent to ATe=0A^{\mathsf T}e=0, not to e=0e=0.
G=ATA;h=ATb;Gθ^=hG=A^{\mathsf T}A;\quad h=A^{\mathsf T}b;\quad G\hat\theta=h
G is an n × n Gram matrix and h has n entries. These names abbreviate the normal equations; G is not the original design matrix A. “Normal” refers to a perpendicular residual, not a normal probability distribution.
P=A(ATA)−1AT;b^=PbP=A(A^{\mathsf T}A)^{-1}A^{\mathsf T};\quad\hat b=Pb
This formula requires independent columns: rank⁡(A)=n\operatorname{rank}(A) = n. P has shape m × m, acts on outputs, and satisfies PT=PP^{\mathsf T} = P and P2=PP^{2} = P. The map (ATA)−1AT(A^{\mathsf T}A)^{-1}A^{\mathsf T} has shape n × m and computes coefficients; it is not the projection matrix.
A=QR;QTQ=In;P=QQTA=QR;\quad Q^{\mathsf T}Q=I_n;\quad P=QQ^{\mathsf T}
For a full-column-rank A, reduced Q has shape m × n and orthonormal columns; R is an invertible n × n upper triangular matrix. For m > n, Q is not a square orthogonal matrix: QTQ=InQ^{\mathsf T}Q = I_{n} but QQT=PQQ^{\mathsf T} = P generally differs from ImI_{m}.
arg min⁡;rank⁡(A);Null⁡(A)\operatorname*{arg\,min};\quad\operatorname{rank}(A);\quad\operatorname{Null}(A)
arg min names the coefficient vectors attaining the smallest objective, not the objective value itself. They form θ^+Null⁡(A)\hat{\theta} + \operatorname{Null}(A). Rank counts independent columns. If rank⁡(A)=n\operatorname{rank}(A) = n the coefficient is unique; otherwise the fitted output stays unique while coefficients may differ.
NumPy: (3, 2), (2,), .T, @, **2
A.shape is (3, 2); a 1D θ\theta array has shape (2,), not (2, 1). .T transposes a matrix, but does not turn a 1D array into a column array. @ is matrix multiplication; * is elementwise multiplication or scalar scaling; **2 squares entries. Python indices start at 0.
lstsq: theta_hat, sums_squared, rank_A, singular_values
np.linalg.lstsq returns four results. sums_squared contains sums of squared residuals, not the residual vector e. It is empty when rank(A) < n or m≤nm \le n; empty does not mean zero error. Compute e=b−A@theta_hate = b - A \mathbin{\mathtt{@}} \mathtt{theta\_hat} and e @ e directly.

Key ideas

Terms you will use

Objective and minimizerf(θ)=∥Aθ−b∥22;θ^∈arg min⁡θf(θ)f(\theta)=\lVert A\theta-b\rVert_2^2;\quad\hat\theta\in\operatorname*{arg\,min}_{\theta}f(\theta)

AθA\theta is the prediction for candidate coefficients θ\theta. Choose θ^\hat{\theta} to minimize the sum of squared differences between predictions and observations.

Keep in mind The coefficient θ^\hat{\theta} is a vector; the minimum squared error f(θ^)f(\hat{\theta}) is a scalar.
Normal equationsATAθ^=ATb ⟺ ATe=0A^{\mathsf T}A\hat\theta=A^{\mathsf T}b\ \Longleftrightarrow\ A^{\mathsf T}e=0

At a minimum, the residual has zero inner product with every column of A. This gives a smaller system in coefficient space.

Keep in mind These equations hold for every least-squares minimizer. Their inverse formula requires full column rank.
Fitted values and residualb=b^+e;b^∈Col⁡(A),e∈Null⁡(AT)b=\hat b+e;\quad\hat b\in\operatorname{Col}(A),\quad e\in\operatorname{Null}(A^{\mathsf T})

The fitted vector b^\hat{b} belongs to the reachable subspace; the remaining part e belongs to its orthogonal complement.

Keep in mind Orthogonality does not mean the residual is zero. Here b^\hat{b} and e live in R3\mathbb R^{3}, while θ^\hat{\theta} lives in R2\mathbb R^{2}.
Uniquenessall minimizers=θ^+Null⁡(A)\text{all minimizers}=\hat\theta+\operatorname{Null}(A)

The nearest reachable output is always unique. Different coefficients can produce that same output if the null space is nontrivial.

Keep in mind Independent columns give one coefficient vector; dependent columns give a family with the same fitted values.

Change the input

See the geometry respond

Keep A fixed and vary only b2b_{2} in b=(1,b2,1)Tb = (1,b_{2},1)^{\mathsf T}. The graph is a 2D orthonormal slice through the fitted vector and the residual in R3\mathbb R^{3}. The vertical coordinate is along ℓ/3\ell /\sqrt{3}, where ℓ=(1,−1,1)T\ell = (1,-1,1)^{\mathsf T}; it can be negative.

Minimum squared error
0.33333
Original coefficient θ^\hat\theta
(0.66667, 1.33333)
ATeA^{\mathsf T}e
(0, 0)
Best fitted output and perpendicular residualb^ · fitted output; b · observation; e · perpendicular residual. Both axes use the same scale.00.81.6-0.20.30.7along b̂ · reachablealong ℓ/√3
  • b^\hat b · fitted output
  • b · observation
  • e · perpendicular residual

b^=\hat{b} = (0.66667, 1.33333, 0.66667); e=e = (0.33333, -0.33333, 0.33333). The residual is perpendicular even though it is nonzero.

With column 2 duplicated, θ(t)=(0.66667,0.66667,0.66667)=θmin⁡+t(0,1,−1)T\theta(t)=(0.66667, 0.66667, 0.66667)=\theta_{\min}+t(0,1,-1)^{\mathsf T}. Changing t preserves the fitted output and squared error; t=0t=0 selects the smallest coefficient norm.

Lab 4.4 · Lecture example

From an impossible exact fit to the nearest output

Use the same A and b as printed slide 67. Keep coefficients, fitted values, and residuals separate, then verify the geometric reason the error cannot be improved.

Select a line to see its action, array shape, and concrete operation.

Companion notebookCh4-4 Least Squares.ipynb ↗Lecture 4, printed slides 61–68 (PDF pages 71–78), with projection and QR connections. The browser displays prepared states; Python runs in Colab.

Line 1: import numpy as np
L01 / 33Show why the exact system is inconsistent
Predict

If every AθA\theta has zero inner product with ℓ\ell, can an output with ℓTb=1\ell ^{\mathsf T}b = 1 be reached?

Before

Three observations, two coefficients

For θ=(θ1,θ2)T,Aθ=(−θ1+θ2,θ2,θ1)T\theta = (\theta _{1},\theta _{2})^{\mathsf T}, A\theta = (-\theta _{1} + \theta _{2}, \theta _{2}, \theta _{1})^{\mathsf T}. The last two observations would force θ2=θ1=1\theta _{2} = \theta _{1} = 1, making the first prediction 0 rather than 1.

Aθ=bA\theta = b has no exact solution for b=(1,1,1)Tb = (1,1,1)^{\mathsf T}

A · lecture design matrix

b · observed output

After
?

Reveal to compare.

Connect the steps

Why least squares is projection

01 An unreachable target still has a nearest reachable output

The outputs AθA\theta fill Col(A), a finite-dimensional subspace of Rm\mathbb R^{m}. Every b has a unique orthogonal projection onto that subspace. Because this projection belongs to Col(A), some coefficient vector produces it. Thus least squares always has a minimizer, even when the exact equation has none.

For the running example, ℓ=(1,−1,1)T\ell = (1,-1,1)^{\mathsf T} satisfies ATℓ=0A^{\mathsf T}\ell = 0. Every reachable output obeys ℓTAθ=0\ell ^{\mathsf T}A\theta = 0, but b=(1,1,1)Tb = (1,1,1)^{\mathsf T} gives ℓTb=1\ell ^{\mathsf T}b = 1. This certifies b∉Col⁡(A)b \notin \operatorname{Col}(A). The obstruction is a nonzero component perpendicular to the reachable plane.

θ^∈arg min⁡θ∥Aθ−b∥22;b^=Aθ^=proj⁡Col⁡(A)b\hat\theta\in\operatorname*{arg\,min}_{\theta}\lVert A\theta-b\rVert_2^2;\quad\hat b=A\hat\theta=\operatorname{proj}_{\operatorname{Col}(A)}b

02 The normal equations follow from the objective

Expand f(θ)=(Aθ−b)T(Aθ−b)=θTATAθ−2bTAθ+bTbf(\theta ) = (A\theta - b)^{\mathsf T}(A\theta - b) = \theta ^{\mathsf T}A^{\mathsf T}A\theta - 2b^{\mathsf T}A\theta + b^{\mathsf T}b. ATAA^{\mathsf T}A is symmetric, so the gradient is ∇f(θ)=2ATAθ−2ATb\nabla f(\theta ) = 2A^{\mathsf T}A\theta - 2A^{\mathsf T}b. At a minimum, the gradient is zero, giving ATAθ^=ATbA^{\mathsf T}A\hat{\theta} = A^{\mathsf T}b.

This condition is sufficient as well as necessary: the Hessian is 2ATA2A^{\mathsf T}A and zTATAz=∥Az∥22≥0z^{\mathsf T}A^{\mathsf T}Az = \Vert Az\Vert _{2}^{2} \ge 0. The objective is convex, so a stationary point is a global minimizer. When the columns are independent, this squared length is positive for every nonzero z; the objective is strictly convex and the coefficient is unique. The geometric proof below establishes sufficiency without calculus.

∇f(θ^)=0 ⟺ AT(Aθ^−b)=0 ⟺ ATe=0\nabla f(\hat\theta)=0\ \Longleftrightarrow\ A^{\mathsf T}(A\hat\theta-b)=0\ \Longleftrightarrow\ A^{\mathsf T}e=0

03 A perpendicular residual proves global optimality

Suppose ATe=0A^{\mathsf T}e = 0 with e=b−Aθ^e = b - A\hat{\theta}. For any candidate θ,b−Aθ=e−A(θ−θ^)\theta , b - A\theta = e - A(\theta - \hat{\theta}). The two terms are perpendicular: e is orthogonal to Col(A), while A(θ−θ^)A(\theta - \hat{\theta}) belongs to that subspace. Pythagoras therefore splits the squared error into the best error plus a nonnegative extra term.

Equality holds precisely when A(θ−θ^)=0A(\theta - \hat{\theta}) = 0. This proves both optimality and the full minimizer set θ^+Null⁡(A)\hat{\theta} + \operatorname{Null}(A). For our example, e=(1/3,−1/3,1/3)Te = (1/3,-1/3,1/3)^{\mathsf T}, so the minimum squared error is 1/3. The minimum residual length is 1/3\sqrt{1/3}; these are different numbers. The coefficient norm ∥θ^∥2\Vert \hat{\theta}\Vert _{2} is a third quantity and is not the ordinary least-squares objective.

∥b−Aθ∥22=∥e∥22+∥A(θ−θ^)∥22≥∥e∥22\lVert b-A\theta\rVert_2^2=\lVert e\rVert_2^2+\lVert A(\theta-\hat\theta)\rVert_2^2\ge\lVert e\rVert_2^2

04 The inverse formula has a rank assumption

For z∈Rn,zTGz=∥Az∥22z \in \mathbb R^{n}, z^{\mathsf T}Gz = \Vert Az\Vert _{2}^{2}. Thus G=ATAG = A^{\mathsf T}A is invertible exactly when Null⁡(A)={0}\operatorname{Null}(A) = \{0\}, equivalently rank⁡(A)=n\operatorname{rank}(A) = n. Under this assumption θ^=(ATA)−1ATb\hat{\theta} = (A^{\mathsf T}A)^{-1}A^{\mathsf T}b and b^=Pb\hat{b} = Pb, with P=A(ATA)−1ATP = A(A^{\mathsf T}A)^{-1}A^{\mathsf T}.

The normal equations remain valid when columns are dependent, but the displayed inverse does not exist. Projection onto Col(A) still exists and is unique. One can use an orthonormal basis QrQ_{r} of its r-dimensional column space to obtain P=QrQrTP = Q_{r}Q_{r}^{\mathsf T}, or write P=AA+P = AA^{+} using the Moore–Penrose pseudoinverse A+A^{+}. The rank-deficient code example avoids using the invalid inverse formula.

rank⁡(A)=n ⇒ unique θ^;rank⁡(A)<n ⇒ multiple θ^, one Aθ^\operatorname{rank}(A)=n\ \Rightarrow\ \text{unique }\hat\theta;\quad\operatorname{rank}(A)<n\ \Rightarrow\ \text{multiple }\hat\theta,\ \text{one }A\hat\theta

05 QR computes the same projection with orthonormal coordinates

For full column rank, A=QRA = QR with reduced Q having orthonormal columns. Split b into QQTbQQ^{\mathsf T}b and its perpendicular residual. Then ∥Aθ−b∥22=∥Rθ−QTb∥22+∥(I−QQT)b∥22\Vert A\theta - b\Vert _{2}^{2} = \Vert R\theta - Q^{\mathsf T}b\Vert _{2}^{2} + \Vert (I - QQ^{\mathsf T})b\Vert _{2}^{2}. The second term cannot be changed by θ\theta; the first becomes zero when Rθ^=QTbR\hat{\theta} = Q^{\mathsf T}b.

This gives the same fitted output QQTbQQ^{\mathsf T}b as the Gram-matrix formula. In this example Q is 3 × 2, so QTQ=I2Q^{\mathsf T}Q = I_{2}, while QQTQQ^{\mathsf T} is a rank-two projection in R3\mathbb R^{3}. Different sign choices for columns of Q and matching rows of R leave QR and QQTQQ^{\mathsf T} unchanged.

Rθ^=QTb;Aθ^=QRθ^=QQTb=PbR\hat\theta=Q^{\mathsf T}b;\quad A\hat\theta=QR\hat\theta=QQ^{\mathsf T}b=Pb

06 Distinguish a linear subspace from a shifted tangent plane

Printed slide 33 projects s=(2,3,0)Ts = (2,3,0)^{\mathsf T} onto the tangent plane through p0=(1,2,−1)Tp_{0} = (1,2,-1)^{\mathsf T}. That plane is p0+Col⁡(A)p_{0} + \operatorname{Col}(A). First use the displacement b=s−p0=(1,1,1)Tb = s - p_{0} = (1,1,1)^{\mathsf T}, which is exactly the target in our least-squares example.

Pb=(2/3,4/3,2/3)TPb = (2/3,4/3,2/3)^{\mathsf T} is the projected displacement. To recover the projected point in the original coordinates, add p0:s^=p0+Pb=(5/3,10/3,−1/3)Tp_{0}: \hat{s} = p_{0} + Pb = (5/3,10/3,-1/3)^{\mathsf T}. The projection onto the shifted plane is an affine map of s; P itself projects onto the subspace through the origin.

s^=p0+P(s−p0);s−s^=b−Pb=e\hat s=p_0+P(s-p_0);\quad s-\hat s=b-Pb=e

07 Use the formulas to understand the problem and a solver to compute it

The Gram-matrix step exposes the lecture’s normal equations and uses np.linalg.solve(G, h) rather than explicitly computing G−1G^{-1}. Forming ATAA^{\mathsf T}A can worsen conditioning: for full column rank, its spectral condition number is the square of A’s. Solving with G instead of inverting it does not remove that effect. The small well-conditioned example is suitable for inspecting the formula.

For general data, use np.linalg.lstsq(A, b, rcond=None), which works directly with A and supports rank-deficient systems. It returns a minimum-Euclidean-norm coefficient if minimizers are not unique. The rank cutoff depends on singular values and numerical precision, so near-dependent columns require attention to scale and tolerance. An approximately zero ATeA^{\mathsf T}e checks stationarity to the chosen tolerance; the algebra above proves optimality.

Check your understanding

If ATe=0A^{\mathsf T}e = 0, must every residual entry be zero?

No. It means the residual is perpendicular to the column space. Here e=(1/3,−1/3,1/3)Te = (1/3,-1/3,1/3)^{\mathsf T} is nonzero, yet ATe=0A^{\mathsf T}e = 0. Zero residual occurs exactly when b is reachable.

What lives in R2\mathbb R^{2}, and what lives in R3\mathbb R^{3}?

θ\theta and θ^\hat{\theta} have two coefficient coordinates. b,b^=Aθ^b, \hat{b} = A\hat{\theta}, and e have three measurement coordinates. P acts in R3\mathbb R^{3}; the coefficient map (ATA)−1AT(A^{\mathsf T}A)^{-1}A^{\mathsf T} maps R3\mathbb R^{3} to R2\mathbb R^{2}.

Why minimize squared distance rather than distance?

For a nonnegative length, squaring is strictly increasing, so both objectives have the same minimizers. Their minimum values differ: the squared error is 1/3 here, while the residual length is 1/31/\sqrt{3}.

Does least squares always give unique coefficients?

It always gives a unique fitted output, the projection of b onto Col(A). Coefficients are unique exactly when A has independent columns. With dependent columns, adding any z in Null(A) preserves the output and error.

Can we use (ATA)−1(A^{\mathsf T}A)^{-1} if a column is duplicated?

No: duplicate columns make ATAA^{\mathsf T}A singular. The normal equations still characterize minimizers. Use lstsq, an orthonormal basis of Col(A), or a pseudoinverse.

What does an empty sums_squared array from lstsq mean?

It means that this summary is not returned for the matrix shape or rank; it does not mean a perfect fit. Our 3 × 3 rank-two example returns an empty array and still has squared error 1/3. Compute e @ e.

Is Pb the final point on the tangent plane in printed slide 33?

Pb is a displacement from p0p_{0}. The final point is p0+Pb=(5/3,10/3,−1/3)Tp_{0} + Pb = (5/3,10/3,-1/3)^{\mathsf T}. This distinction connects the linear projection to a plane that does not pass through the origin.

Code references: NumPy: lstsq results and rank cutoff ↗ · NumPy: reduced QR shapes ↗

Continue in Python

Run the complete notebook in Colab

Run the lecture example and vary the observations. The companion notebook, including QR and dependent-column checks, is maintained in this project’s GitHub repository.