Type at least 2 letters. Enter opens the first result, Esc closes.

    Linear Algebra · Lesson 12 · Factorizations, norms and least squares

    QR (Gram–Schmidt, Householder, Givens) and least squares done right

    Intermediate 90 min 5 interactive figures 4 videos Colab notebook

    Before this lesson: lesson 03 (inverse, determinant, dot product and orthogonal projection), lesson 04 (orthogonal matrices and change of basis) and lesson 08 (the SVD and the pseudoinverse). The condition number κ(A)\kappa(A) appears here and gets its full treatment in lesson 13. Time: about 90 minutes, plus the notebook.


    Why this matters #

    Least squares, min⁡x∥Ax−b∥2\min_x \|Ax - b\|_2, is the most common computation in data analysis: linear regression, curve fitting, linear probes, every Gauss–Newton step, and many inverse problems in science. In exact arithmetic all standard methods give the same answer. In floating point they do not. The textbook formula (A⊤A)−1A⊤b(A^\top A)^{-1}A^\top b squares the condition number: with κ(A)=107\kappa(A) = 10^7 it keeps about 2–3 correct digits, while QR keeps about 9–10. QR is also a building block you will meet again: it orthonormalizes the sketch in randomized SVD (lesson 09), it drives the QR eigenvalue algorithm, and Arnoldi is Gram–Schmidt on a Krylov sequence (lesson 14).

    1. Predict first #

    2. The picture #

    One column first. Fit b≈x ab \approx x\,a with one column a∈Rma \in \mathbb{R}^m and a scalar xx. The best xx makes the error b−xab - xa orthogonal to aa: a⊤(b−x^a)=0a^\top(b - \hat x a) = 0, so x^=a⊤b/a⊤a\hat x = a^\top b / a^\top a. The fitted vector x^a\hat x a is the orthogonal projection of bb onto the line through aa.

    Many columns. Ax=x1a1+⋯+xnanAx = x_1a_1 + \dots + x_na_n ranges over the column space C(A)C(A). The closest point to bb is the orthogonal projection p=Ax^p = A\hat x, and the residual r=b−Ax^r = b - A\hat x is orthogonal to every column. In the language of lesson 02: r∈N(A⊤)r \in N(A^\top).

    Interactive figure: loading…

    Least squares is a projection. The green plane is C(A)C(A), spanned by the columns a1a_1 and a2a_2. The vector bb is not in the plane, so Ax=bAx = b has no solution. The closest point is p=Ax^p = A\hat x, and the residual r=b−pr = b - p meets the plane at a right angle: A⊤r=0A^\top r = 0. Rotate the figure and move bb with the sliders. With line through 3 points, the same picture fits a line c0+c1tc_0 + c_1 t to three data points: the three values bib_i are one vector in R3\mathbb{R}^3.

    Orthonormal columns make this easy. If A=QA = Q with Q⊤Q=IQ^\top Q = I, the coordinates are plain dot products, x^=Q⊤b\hat x = Q^\top b: no system to solve. QR is the step that makes the columns orthonormal and records the change in an upper triangular matrix RR.

    Three ways to get there.

    • Gram–Schmidt builds q1,q2,…q_1, q_2, \dots one at a time: take aka_k, remove its components along q1,…,qk−1q_1, \dots, q_{k-1}, normalize ("triangular orthogonalization").
    • Householder multiplies AA on the left by reflections until it is upper triangular ("orthogonal triangularization").
    • Givens does the same with 2-D rotations, each one zeroing a single entry.
    Quick check

    AA is 3×23 \times 2 with independent columns, bb is not in C(A)C(A), and x^\hat x is the least-squares solution. Which statement about r=b−Ax^r = b - A\hat x is always true?

    3. Definitions and main results #

    For A∈Rm×nA \in \mathbb{R}^{m\times n}, m≥nm \ge n, the reduced (thin) QR is A=QRA = QR with Q∈Rm×nQ \in \mathbb{R}^{m\times n}, Q⊤Q=InQ^\top Q = I_n, and R∈Rn×nR \in \mathbb{R}^{n\times n} upper triangular. The full QR is A=Q~(R0)A = \tilde Q \binom{R}{0} with Q~=[ Q    Q2 ]\tilde Q = [\,Q \;\; Q_2\,] orthogonal (m×mm \times m). For full column rank, the columns of Q2Q_2 are an orthonormal basis of N(A⊤)N(A^\top).

    Existence and uniqueness of QR #

    Gram–Schmidt by hand first. Take a1=(1,1,0)a_1 = (1, 1, 0) and a2=(1,0,1)a_2 = (1, 0, 1).

    1. Normalize a1a_1: r11=∥a1∥=2r_{11} = \|a_1\| = \sqrt2, so q1=(1,1,0)/2q_1 = (1, 1, 0)/\sqrt2.
    2. The part of a2a_2 along q1q_1 has length r12=q1⊤a2=(1+0+0)/2=1/2r_{12} = q_1^\top a_2 = (1 + 0 + 0)/\sqrt2 = 1/\sqrt2.
    3. Remove it: v2=a2−r12q1v_2 = a_2 - r_{12}q_1. Here r12q1=12⋅12(1,1,0)=(12,12,0)r_{12}q_1 = \tfrac{1}{\sqrt2}\cdot\tfrac{1}{\sqrt2}(1, 1, 0) = (\tfrac12, \tfrac12, 0), so v2=(1,0,1)−(12,12,0)=(12,−12,1)v_2 = (1, 0, 1) - (\tfrac12, \tfrac12, 0) = (\tfrac12, -\tfrac12, 1). Check: q1⊤v2=(12−12+0)/2=0q_1^\top v_2 = (\tfrac12 - \tfrac12 + 0)/\sqrt2 = 0 ✓.
    4. Normalize: r22=∥v2∥=14+14+1=1.5r_{22} = \|v_2\| = \sqrt{\tfrac14 + \tfrac14 + 1} = \sqrt{1.5}, so q2=v2/1.5=(1,−1,2)/6q_2 = v_2/\sqrt{1.5} = (1, -1, 2)/\sqrt6.
    5. Collect the coefficients in RR. Column kk of RR holds the numbers that rebuild aka_k: a1=r11q1a_1 = r_{11}q_1 and a2=r12q1+r22q2a_2 = r_{12}q_1 + r_{22}q_2. So
    (111001)⏟A=(1/21/61/2−1/602/6)⏟Q(21/201.5)⏟R.\underbrace{\begin{pmatrix} 1 & 1 \\ 1 & 0 \\ 0 & 1 \end{pmatrix}}_{A} = \underbrace{\begin{pmatrix} 1/\sqrt2 & 1/\sqrt6 \\ 1/\sqrt2 & -1/\sqrt6 \\ 0 & 2/\sqrt6 \end{pmatrix}}_{Q} \underbrace{\begin{pmatrix} \sqrt2 & 1/\sqrt2 \\ 0 & \sqrt{1.5} \end{pmatrix}}_{R}.

    Check one entry: row 3 of QQ times column 2 of RR is 0⋅12+261.5=26⋅62=1=a320 \cdot \tfrac{1}{\sqrt2} + \tfrac{2}{\sqrt6}\sqrt{1.5} = \tfrac{2}{\sqrt6}\cdot\tfrac{\sqrt6}{2} = 1 = a_{32} ✓. RR is upper triangular because a1a_1 uses only q1q_1, and a2a_2 uses only q1q_1 and q2q_2.

    Interactive figure: loading…

    Step through Gram–Schmidt. Press Next step. The grey arrows are the columns of AA: the two vectors above and a3=(0,1,1)a_3 = (0, 1, 1). At each step the magenta vector vv is what is left of a column after its parts along the earlier qq's are removed (dashed); then it is normalized to q1q_1, q2q_2 or q3q_3. Watch RR fill in column by column. Then choose nearly dependent, set δ=10−8\delta = 10^{-8}, go to the last step and switch between CGS and MGS: CGS gives a q3q_3 that is 45°45° away from orthogonal to q2q_2.

    For the three columns of the figure, step 4 and 5 continue the same way: r13=q1⊤a3=1/2r_{13} = q_1^\top a_3 = 1/\sqrt2, r23=q2⊤a3=1/6r_{23} = q_2^\top a_3 = 1/\sqrt6, v3=a3−r13q1−r23q2=(−23,23,23)v_3 = a_3 - r_{13}q_1 - r_{23}q_2 = (-\tfrac23, \tfrac23, \tfrac23), r33=2/3r_{33} = 2/\sqrt3 and q3=(−1,1,1)/3q_3 = (-1, 1, 1)/\sqrt3.

    Theorem (QR). If AA has independent columns a1,…,ana_1, \dots, a_n, then A=QRA = QR with orthonormal columns in QQ and RR upper triangular with rkk>0r_{kk} > 0, and this factorization is unique.

    Proof of existence (Gram–Schmidt).

    1. a1≠0a_1 \ne 0 (independent columns). Set r11=∥a1∥r_{11} = \|a_1\| and q1=a1/r11q_1 = a_1/r_{11}.
    2. Assume q1,…,qk−1q_1, \dots, q_{k-1} are orthonormal and span⁡(q1,…,qk−1)=span⁡(a1,…,ak−1)\operatorname{span}(q_1, \dots, q_{k-1}) = \operatorname{span}(a_1, \dots, a_{k-1}).
    3. Set rjk=qj⊤akr_{jk} = q_j^\top a_k for j<kj < k and vk=ak−∑j<krjkqjv_k = a_k - \sum_{j<k} r_{jk}q_j. Then qi⊤vk=qi⊤ak−rik=0q_i^\top v_k = q_i^\top a_k - r_{ik} = 0 for every i<ki < k.
    4. vk≠0v_k \ne 0: otherwise ak∈span⁡(q1,…,qk−1)=span⁡(a1,…,ak−1)a_k \in \operatorname{span}(q_1, \dots, q_{k-1}) = \operatorname{span}(a_1, \dots, a_{k-1}), which contradicts independence. Set rkk=∥vk∥>0r_{kk} = \|v_k\| > 0 and qk=vk/rkkq_k = v_k/r_{kk}. The span property now holds for kk.
    5. Rearranged, ak=∑j<krjkqj+rkkqka_k = \sum_{j<k} r_{jk}q_j + r_{kk}q_k: column kk of AA is QQ times column kk of RR, and it uses only q1,…,qkq_1, \dots, q_k, so RR is upper triangular. Hence A=QRA = QR. ■\blacksquare
    Proof of uniqueness
    1. Let A=Q1R1=Q2R2A = Q_1R_1 = Q_2R_2, both of this form. Then Q1=Q2TQ_1 = Q_2T with T=R2R1−1T = R_2R_1^{-1}, which is upper triangular with positive diagonal. Also I=Q1⊤Q1=T⊤Q2⊤Q2T=T⊤TI = Q_1^\top Q_1 = T^\top Q_2^\top Q_2 T = T^\top T, so TT is orthogonal.
    2. T−1=T⊤T^{-1} = T^\top is upper triangular (inverse of an upper triangular matrix) and lower triangular (transpose of one), so TT is diagonal with entries ±1\pm 1. A positive diagonal forces T=IT = I: R1=R2R_1 = R_2 and Q1=Q2Q_1 = Q_2. ■\blacksquare

    Another route: A⊤A=R⊤RA^\top A = R^\top R is the Cholesky factorization of the positive definite A⊤AA^\top A, and the Cholesky factor with positive diagonal is unique (lesson 07).

    rkk=∥vk∥r_{kk} = \|v_k\| is the distance from aka_k to the span of the earlier columns. A tiny rkkr_{kk} warns that aka_k is nearly a combination of earlier columns. Without independence, QR still exists (Householder computes it for any AA), but some rkk=0r_{kk} = 0 and uniqueness is lost.

    Classical and modified Gram–Schmidt #

    The two versions differ only in which vector each projection is computed from. Look at column 3:

    • Classical Gram–Schmidt (CGS) computes all coefficients from the original column: r13=q1⊤a3r_{13} = q_1^\top a_3 and r23=q2⊤a3r_{23} = q_2^\top a_3. Then it subtracts both: v3=a3−r13q1−r23q2v_3 = a_3 - r_{13}q_1 - r_{23}q_2.
    • Modified Gram–Schmidt (MGS) subtracts one projection at a time and computes the next coefficient from what is left: v←a3−r13q1v \leftarrow a_3 - r_{13}q_1 with r13=q1⊤a3r_{13} = q_1^\top a_3, then r23=q2⊤vr_{23} = q_2^\top v (the current, partly reduced vector) and v3=v−r23q2v_3 = v - r_{23}q_2.

    In exact arithmetic q2⊤q1=0q_2^\top q_1 = 0, so q2⊤(a3−r13q1)=q2⊤a3q_2^\top(a_3 - r_{13}q_1) = q_2^\top a_3: the two methods give the same numbers. In floating point they do not:

    • Why CGS fails. If aka_k is nearly in the span of the earlier columns, vkv_k is a small difference of large, nearly equal vectors (rkk≪∥ak∥r_{kk} \ll \|a_k\|). Rounding errors of size about ε∥ak∥\varepsilon\|a_k\| (ε≈2.2×10−16\varepsilon \approx 2.2 \times 10^{-16}, the machine epsilon of double precision, lesson 13) survive the subtraction and are divided by rkkr_{kk}. So qkq_k keeps a component of size about ε∥ak∥/rkk\varepsilon\|a_k\|/r_{kk} along the earlier qjq_j, and the errors grow from column to column.
    • Why MGS helps. MGS takes each coefficient from the vector that is actually being reduced. So each subtraction also removes the qjq_j-part of the rounding errors made in the earlier subtractions. CGS fixes all coefficients in advance and never corrects these errors.
    • How large. The loss of orthogonality ∥Q⊤Q−I∥2\|Q^\top Q - I\|_2 is about εκ(A)2\varepsilon\kappa(A)^2 for CGS (order 1 from κ≈108\kappa \approx 10^8 on), about εκ(A)\varepsilon\kappa(A) for MGS, and about ε\varepsilon for Householder, independent of κ\kappa. Orthogonalizing each column twice (CGS2) brings Gram–Schmidt back to order ε\varepsilon when εκ(A)≪1\varepsilon\kappa(A) \ll 1.

    In the nearly dependent case of the figure, a1=(1,δ,0)a_1 = (1, \delta, 0), a2=(1,0,δ)a_2 = (1, 0, \delta), a3=(1,0,0)a_3 = (1, 0, 0) with δ=10−8\delta = 10^{-8} (κ(A)≈3×108\kappa(A) \approx 3 \times 10^8): CGS gives ∥Q⊤Q−I∥2≈0.71\|Q^\top Q - I\|_2 \approx 0.71 (the angle between q2q_2 and q3q_3 is 45°45°), MGS gives about 10−810^{-8}.

    Householder reflections #

    A Householder reflection is H=I−2 vv⊤/(v⊤v)H = I - 2\,vv^\top/(v^\top v) for a nonzero vv. It reflects across the hyperplane orthogonal to vv: Hv=−vHv = -v, and Hw=wHw = w for w⊥vw \perp v. So HH is symmetric and orthogonal, and H2=IH^2 = I.

    To map xx to a multiple of e1e_1, the target must be ±∥x∥e1\pm\|x\|e_1 (reflections keep length), and v=x−targetv = x - \text{target}. Choose

    v=x+sign⁡(x1) ∥x∥ e1,Hx=−sign⁡(x1) ∥x∥ e1,v = x + \operatorname{sign}(x_1)\,\|x\|\,e_1, \qquad Hx = -\operatorname{sign}(x_1)\,\|x\|\,e_1,

    with the convention sign⁡(0)=+1\operatorname{sign}(0) = +1.

    One step by hand. Let x=(1,2,2)x = (1, 2, 2) be the first column of a 3×33 \times 3 matrix.

    1. ∥x∥=1+4+4=3\|x\| = \sqrt{1 + 4 + 4} = 3 and x1>0x_1 > 0, so the target is −3e1-3e_1.
    2. v=x+3e1=(4,2,2)v = x + 3e_1 = (4, 2, 2); here v1=1+3v_1 = 1 + 3 adds two positive numbers.
    3. v⊤v=16+4+4=24v^\top v = 16 + 4 + 4 = 24 and v⊤x=4+4+4=12v^\top x = 4 + 4 + 4 = 12.
    4. Hx=x−2 v⊤xv⊤v v=x−v=(−3,0,0)Hx = x - 2\,\tfrac{v^\top x}{v^\top v}\,v = x - v = (-3, 0, 0) ✓: two entries are zeroed.
    5. Apply the same HH to another column y=(1,0,1)y = (1, 0, 1), without building HH: v⊤y=6v^\top y = 6, so Hy=y−2⋅624 v=y−12v=(−1,−1,0)Hy = y - 2 \cdot \tfrac{6}{24}\,v = y - \tfrac12 v = (-1, -1, 0). Check: ∥Hy∥=2=∥y∥\|Hy\| = \sqrt2 = \|y\| ✓.

    With the other sign, v=x−3e1=(−2,2,2)v = x - 3e_1 = (-2, 2, 2) and Hx=(3,0,0)Hx = (3, 0, 0). That is also correct in exact arithmetic. The problem appears when xx is close to the e1e_1 axis: then v1=x1−∥x∥v_1 = x_1 - \|x\| subtracts two nearly equal numbers (cancellation). Example: x=(1,10−9,0)x = (1, 10^{-9}, 0). ∥x∥\|x\| rounds to exactly 1, so the wrong sign gives v1=1−1=0v_1 = 1 - 1 = 0 (true value −5×10−19-5 \times 10^{-19}), and the computed HH maps xx to (1,−10−9,0)(1, -10^{-9}, 0): nothing was zeroed. The right sign gives v=(2,10−9,0)v = (2, 10^{-9}, 0) and Hx=(−1,0,0)Hx = (-1, 0, 0).

    Interactive figure: loading…

    Reflect xx onto the axis. The mirror is the line orthogonal to vv. Reflecting xx across it gives HxHx, a point on the e1e_1 axis at distance ∥x∥\|x\| from 0. Drag xx close to the positive e1e_1 axis and switch to other sign: vv becomes very short, which is where cancellation hits in floating point (the readout repeats the x=(1,10−9,0)x = (1, 10^{-9}, 0) example in real double precision). Givens rotation reaches the axis by turning instead of reflecting.

    Quick check

    v≠0v \ne 0 and H=I−2vv⊤/(v⊤v)H = I - 2vv^\top/(v^\top v). What is H2H^2?

    Householder QR. For k=1,…,nk = 1, \dots, n: let xx be column kk on and below the diagonal, build vkv_k, and update the remaining block XX by the rank-1 formula X←X−2vk(vk⊤X)/(vk⊤vk)X \leftarrow X - 2v_k(v_k^\top X)/(v_k^\top v_k). Never form the m×mm\times m matrix HkH_k. After nn steps Hn⋯H1A=(R0)H_n\cdots H_1A = \binom{R}{0}, so Q~=H1⋯Hn\tilde Q = H_1\cdots H_n. For least squares you do not need QQ itself: apply the same reflections to bb. Cost: about 2mn2−23n32mn^2 - \tfrac23 n^3 flops.

    Why Householder QR is backward stable. Backward stable means: the computed R^\hat R is the exact R-factor of a nearby matrix, Q~R^=A+δA\tilde Q\hat R = A + \delta A with Q~\tilde Q exactly orthogonal and ∥δA∥≤c ε∥A∥\|\delta A\| \le c\,\varepsilon\|A\| (cc a modest constant depending on m,nm, n).

    1. Each step multiplies by an orthogonal matrix. Its rounding error is a perturbation of relative size O(ε)O(\varepsilon) of the current matrix.
    2. Orthogonal maps keep 2-norms (∥Hy∥=∥y∥\|Hy\| = \|y\|), so later steps carry earlier errors along without enlarging them. The errors only add up: no division by a small rkkr_{kk}, no cancelling subtraction.
    3. The computed Q^\hat Q is a product of reflections, so ∥Q^⊤Q^−I∥=O(ε)\|\hat Q^\top\hat Q - I\| = O(\varepsilon) for every κ(A)\kappa(A). Orthogonality is built in, not produced by subtraction.

    Gram–Schmidt also gives a small ∥A−Q^R^∥\|A - \hat Q\hat R\|, but for large κ(A)\kappa(A) its Q^\hat Q is far from every orthogonal matrix. So CGS (and MGS) are not backward stable as QR algorithms.

    Interactive figure: loading…

    Four QR algorithms, one test. Each dot is a random 60×1560 \times 15 matrix with condition number κ\kappa, factored in double precision by classical Gram–Schmidt, modified Gram–Schmidt, Cholesky QR (RR from the Cholesky factor of A⊤AA^\top A, then Q=AR−1Q = AR^{-1}) and Householder. The dashed lines are εκ\varepsilon\kappa and εκ2\varepsilon\kappa^2. CGS and Cholesky QR follow εκ2\varepsilon\kappa^2 and reach order 1 near κ=108\kappa = 10^8 (Cholesky QR then breaks down: A⊤AA^\top A is no longer numerically positive definite). MGS follows εκ\varepsilon\kappa. Householder stays at 10−1510^{-15}. Move the κ\kappa slider: the table shows that all four have a tiny residual ∥A−QR∥\|A - QR\|.

    Quick check

    Your Gram–Schmidt code returns Q,RQ, R with ∥A−QR∥/∥A∥=10−16\|A - QR\|/\|A\| = 10^{-16} for a matrix with κ(A)=1010\kappa(A) = 10^{10}. What do you know about QQ?

    Givens rotations #

    A Givens rotation changes two coordinates and leaves the others alone. On the pair (a,b)(a, b):

    G=(cs−sc),r=a2+b2,  c=a/r,  s=b/r,G(ab)=(r0).G = \begin{pmatrix} c & s \\ -s & c\end{pmatrix}, \quad r = \sqrt{a^2 + b^2},\; c = a/r,\; s = b/r, \qquad G\begin{pmatrix} a \\ b\end{pmatrix} = \begin{pmatrix} r \\ 0\end{pmatrix}.

    Example: (3,4)(3, 4) gives r=5r = 5, c=3/5c = 3/5, s=4/5s = 4/5, and G(3,4)=(9/5+16/5, −12/5+12/5)=(5,0)G(3, 4) = (9/5 + 16/5,\ -12/5 + 12/5) = (5, 0). Givens QR zeros the subdiagonal entries one by one.

    Givens rotations in practice
    • Compute rr with hypot(a, b) so that a2a^2 cannot overflow.
    • Givens QR is as stable as Householder but costs about 1.5 times more on a dense matrix (≈3mn2−n3\approx 3mn^2 - n^3 flops).
    • It wins when only a few entries must be zeroed: Hessenberg matrices (one rotation per column in the QR eigenvalue algorithm, lesson 14), sparse matrices, and updating RR when a new data row arrives (one sweep of nn rotations instead of a new factorization).
    • Rotations on disjoint pairs of rows commute, so many of them can run in parallel.

    The normal equations and the QR solution #

    Theorem (least squares). Let AA have full column rank. Then x^\hat x minimizes ∥Ax−b∥2\|Ax - b\|_2 if and only if A⊤Ax^=A⊤bA^\top A\hat x = A^\top b (the normal equations), and x^\hat x solves Rx^=Q⊤bR\hat x = Q^\top b, where A=QRA = QR is the reduced QR.

    Proof.

    1. Projection. The closest point Ax^∈C(A)A\hat x \in C(A) to bb is the orthogonal projection, so the residual is orthogonal to every column: A⊤(b−Ax^)=0A^\top(b - A\hat x) = 0, i.e. A⊤Ax^=A⊤bA^\top A\hat x = A^\top b.
    2. Global minimum. For any xx: b−Ax=(b−Ax^)+A(x^−x)b - Ax = (b - A\hat x) + A(\hat x - x). The first part is in N(A⊤)N(A^\top), the second in C(A)C(A), so they are orthogonal. By Pythagoras ∥b−Ax∥2=∥b−Ax^∥2+∥A(x^−x)∥2\|b - Ax\|^2 = \|b - A\hat x\|^2 + \|A(\hat x - x)\|^2, which is smallest only at x=x^x = \hat x (AA has full column rank, so A(x^−x)=0A(\hat x - x) = 0 forces x=x^x = \hat x).
    3. QR. A⊤A=R⊤Q⊤QR=R⊤RA^\top A = R^\top Q^\top QR = R^\top R and A⊤b=R⊤Q⊤bA^\top b = R^\top Q^\top b, so R⊤Rx^=R⊤Q⊤bR^\top R\hat x = R^\top Q^\top b. R⊤R^\top is invertible, hence Rx^=Q⊤bR\hat x = Q^\top b: one back substitution.
    4. Full-QR view, without normal equations. Q~⊤\tilde Q^\top keeps norms, so ∥Ax−b∥2=∥Rx−Q⊤b∥2+∥Q2⊤b∥2\|Ax - b\|^2 = \|Rx - Q^\top b\|^2 + \|Q_2^\top b\|^2. The first term is zero at Rx^=Q⊤bR\hat x = Q^\top b; the second is the minimal squared residual. ■\blacksquare
    Interactive figure: loading…

    Fit a line, then try to beat it. The model is y≈c0+c1ty \approx c_0 + c_1 t, so AA has the columns (1,…,1)(1, \dots, 1) and (t1,…,tm)(t_1, \dots, t_m). Drag the data points. The least-squares line keeps A⊤r=0A^\top r = 0: the residuals add up to 0, and so do the tirit_i r_i. Switch to your own line and drag its two grey points: A⊤rA^\top r is no longer 0, and by the Pythagoras step of the proof its ∥r∥2\|r\|^2 is always at least the least-squares value, with equality only on the least-squares line.

    Why QR and not the normal equations #

    • Squared condition number. From the SVD A=UΣV⊤A = U\Sigma V^\top: A⊤A=VΣ2V⊤A^\top A = V\Sigma^2V^\top, so κ(A⊤A)=κ(A)2\kappa(A^\top A) = \kappa(A)^2 (proof in lesson 13).
    • Error sizes. For a small residual, a backward-stable method has relative error in x^\hat x of about εκ(A)\varepsilon\kappa(A). Householder QR and SVD solvers are backward stable for least squares. The normal equations are not: their error is about εκ(A)2\varepsilon\kappa(A)^2, even when the residual is zero. (For a large residual, the problem itself has sensitivity of order κ+κ2tan⁡θ\kappa + \kappa^2\tan\theta, with θ\theta the angle between bb and C(A)C(A); QR reaches this, and no method does better.)
    • Total failure. For κ(A)≳1/ε≈108\kappa(A) \gtrsim 1/\sqrt{\varepsilon} \approx 10^8, the computed A⊤AA^\top A can be exactly singular. Läuchli example: A=(11δ00δ)A = \begin{pmatrix} 1 & 1 \\ \delta & 0 \\ 0 & \delta\end{pmatrix}, δ=10−8\delta = 10^{-8}, has full rank, but A⊤A=(1+δ2111+δ2)A^\top A = \begin{pmatrix} 1 + \delta^2 & 1 \\ 1 & 1 + \delta^2\end{pmatrix} and 1+10−161 + 10^{-16} rounds to 11.
    • Cost. Normal equations ≈mn2+n3/3\approx mn^2 + n^3/3 flops, Householder QR ≈2mn2−23n3\approx 2mn^2 - \tfrac23 n^3 (up to 2× more), SVD ≈2mn2+11n3\approx 2mn^2 + 11n^3. For small κ\kappa the normal equations are fine (κ≤103\kappa \le 10^3 gives errors near 10−1010^{-10}).
    Quick check

    A regression has κ(A)=106\kappa(A) = 10^6 and a tiny residual. About how many correct digits does x^\hat x have in double precision (ε≈2×10−16\varepsilon \approx 2 \times 10^{-16})?

    Answers to section 1. (1) Normal equations: εκ2≈10−16⋅1014=10−2\varepsilon\kappa^2 \approx 10^{-16}\cdot 10^{14} = 10^{-2}, so about 2–3 digits (a test with a random AA gave 10−310^{-3}). QR: εκ≈10−9\varepsilon\kappa \approx 10^{-9}, about 9–10 digits (the test gave 7×10−117 \times 10^{-11}). (2) No. Classical Gram–Schmidt's QQ has lost orthogonality completely (∥Q⊤Q−I∥\|Q^\top Q - I\| of order 1); Householder's is at 10−1510^{-15}. A small ∥A−QR∥\|A - QR\| says nothing about orthogonality.

    The minimum-norm solution #

    If AA is m×nm \times n with m<nm < n and full row rank, Ax=bAx = b has infinitely many solutions xp+N(A)x_p + N(A).

    Theorem. The solution of smallest ∥x∥2\|x\|_2 is the unique solution in the row space: x+=A⊤(AA⊤)−1b=A+bx^+ = A^\top(AA^\top)^{-1}b = A^+b. We call it the minimum-norm solution.

    1. Try x=A⊤yx = A^\top y: then AA⊤y=bAA^\top y = b, and AA⊤AA^\top is invertible (full row rank). So x+x^+ solves Ax=bAx = b and lies in C(A⊤)C(A^\top).
    2. Any other solution is x++zx^+ + z with z∈N(A)⊥C(A⊤)z \in N(A) \perp C(A^\top), so ∥x++z∥2=∥x+∥2+∥z∥2≥∥x+∥2\|x^+ + z\|^2 = \|x^+\|^2 + \|z\|^2 \ge \|x^+\|^2, with equality only for z=0z = 0. ■\blacksquare

    Simplest case: the plane x1+2x2+2x3=9x_1 + 2x_2 + 2x_3 = 9. The closest point to the origin lies along the normal a=(1,2,2)a = (1, 2, 2): x+=9a/(a⊤a)=(1,2,2)x^+ = 9a/(a^\top a) = (1, 2, 2), norm 3. The solution (9,0,0)(9, 0, 0) has norm 9. To avoid forming AA⊤AA^\top (again κ2\kappa^2), use A⊤=QRA^\top = QR: then A=R⊤Q⊤A = R^\top Q^\top; set x=Qyx = Qy and solve R⊤y=bR^\top y = b by forward substitution.

    Rank-deficient AA (any shape). The least-squares solutions are x^+N(A)\hat x + N(A); the minimum-norm one is A+b=∑σi>0(ui⊤b/σi) viA^+b = \sum_{\sigma_i > 0}(u_i^\top b/\sigma_i)\,v_i (the pseudoinverse, lesson 08). Plain QR fails here: back substitution divides by rkk≈0r_{kk} \approx 0. Use instead

    • a truncated SVD (singular values below a tolerance count as 0), as np.linalg.lstsq does with rcond;
    • QR with column pivoting, AP=QRAP = QR: at each step the remaining column of largest norm goes first, so ∣r11∣≥∣r22∣≥…|r_{11}| \ge |r_{22}| \ge \dots, and a drop to about ε∥A∥\varepsilon\|A\| usually reveals the numerical rank;
    • ridge, (A⊤A+λI)x=A⊤b(A^\top A + \lambda I)x = A^\top b, which tends to A+bA^+b as λ→0\lambda \to 0.

    4. Worked example #

    A=(211120),b=(123).A = \begin{pmatrix} 2 & 1 \\ 1 & 1 \\ 2 & 0\end{pmatrix}, \qquad b = \begin{pmatrix} 1 \\ 2 \\ 3\end{pmatrix}.

    This is the worked example case of the first figure.

    Gram–Schmidt.

    • r11=∥a1∥=4+1+4=3r_{11} = \|a_1\| = \sqrt{4 + 1 + 4} = 3, so q1=(2,1,2)/3q_1 = (2, 1, 2)/3.
    • r12=q1⊤a2=(2+1+0)/3=1r_{12} = q_1^\top a_2 = (2 + 1 + 0)/3 = 1, and v2=(1,1,0)−(2,1,2)/3=(1,2,−2)/3v_2 = (1, 1, 0) - (2, 1, 2)/3 = (1, 2, -2)/3.
    • r22=∥v2∥=1+4+4/3=1r_{22} = \|v_2\| = \sqrt{1 + 4 + 4}/3 = 1, so q2=(1,2,−2)/3q_2 = (1, 2, -2)/3. Check: q1⊤q2=(2+2−4)/9=0q_1^\top q_2 = (2 + 2 - 4)/9 = 0.
    Q=13(21122−2),R=(3101).Q = \frac13\begin{pmatrix} 2 & 1 \\ 1 & 2 \\ 2 & -2\end{pmatrix}, \qquad R = \begin{pmatrix} 3 & 1 \\ 0 & 1\end{pmatrix}.

    Least squares by QR. Q⊤b=((2+2+6)/3,  (1+4−6)/3)=(10/3,−1/3)Q^\top b = \big((2 + 2 + 6)/3,\; (1 + 4 - 6)/3\big) = (10/3, -1/3). Back substitution, from the last row up: row 2 says x^2=−1/3\hat x_2 = -1/3; row 1 says 3x^1+x^2=10/33\hat x_1 + \hat x_2 = 10/3, so 3x^1=10/3+1/3=11/33\hat x_1 = 10/3 + 1/3 = 11/3 and x^1=11/9\hat x_1 = 11/9.

    Check with the normal equations. A⊤A=(9332)=R⊤RA^\top A = \begin{pmatrix} 9 & 3 \\ 3 & 2\end{pmatrix} = R^\top R and A⊤b=(10,3)A^\top b = (10, 3). Solving 9x^1+3x^2=109\hat x_1 + 3\hat x_2 = 10, 3x^1+2x^2=33\hat x_1 + 2\hat x_2 = 3 gives the same x^=(11/9,−1/3)\hat x = (11/9, -1/3).

    Residual. r=b−Ax^=(−10,10,5)/9r = b - A\hat x = (-10, 10, 5)/9, and A⊤r=0A^\top r = 0 ✓. ∥r∥=225/9=5/3\|r\| = \sqrt{225}/9 = 5/3. The full QR gives this without x^\hat x: q3=(2,−2,−1)/3q_3 = (2, -2, -1)/3 completes the orthonormal basis, and ∣q3⊤b∣=∣2−4−3∣/3=5/3|q_3^\top b| = |2 - 4 - 3|/3 = 5/3 ✓.

    Householder on the same AA. x=a1=(2,1,2)x = a_1 = (2, 1, 2), ∥x∥=3\|x\| = 3, x1>0x_1 > 0, so v1=(5,1,2)v_1 = (5, 1, 2), v1⊤v1=30v_1^\top v_1 = 30, H1a1=a1−2v1(15/30)=a1−v1=(−3,0,0)H_1a_1 = a_1 - 2v_1(15/30) = a_1 - v_1 = (-3, 0, 0) and H1a2=(1,1,0)−2⋅630(5,1,2)=(−1,3/5,−4/5)H_1a_2 = (1, 1, 0) - \tfrac{2\cdot 6}{30}(5, 1, 2) = (-1, 3/5, -4/5). Step 2 on x=(3/5,−4/5)x = (3/5, -4/5), ∥x∥=1\|x\| = 1: v2=(8/5,−4/5)v_2 = (8/5, -4/5) and H2x=(−1,0)H_2x = (-1, 0). So Householder gives (−3−10−1)=−R\begin{pmatrix} -3 & -1 \\ 0 & -1\end{pmatrix} = -R: the same factorization up to the signs D=−ID = -I, as uniqueness predicts.

    Quick check

    A least-squares problem has R=(2103)R = \begin{pmatrix} 2 & 1 \\ 0 & 3 \end{pmatrix} and Q⊤b=(5,6)Q^\top b = (5, 6). What is x^\hat x?

    5. In code #

    NumPy checks the hand computation. The notebook for this lesson has these cells and the exercises.

    import numpy as np
    
    A = np.array([[2., 1.], [1., 1.], [2., 0.]])
    b = np.array([1., 2., 3.])
    
    Q, R = np.linalg.qr(A)                  # Householder (LAPACK geqrf); the signs of diag(R) are free
    print(R.round(12))                      # [[-3. -1.] [ 0. -1.]]: our R with D = -I
    d = np.sign(np.diag(R))
    print((d[:, None] * R).round(12) + 0.0) # [[3. 1.] [0. 1.]]: the unique R with positive diagonal
    
    x, res, rank, sv = np.linalg.lstsq(A, b, rcond=None)   # SVD-based LAPACK solver (gelsd)
    print(x, res)                           # [ 1.2222 -0.3333] [2.7778]: (11/9, -1/3), ‖r‖² = 25/9
    print(A.T @ (b - A @ x))                # ~1e-15: the residual is orthogonal to C(A)
    

    Orthogonality that is built in (Householder) against orthogonality computed through A⊤AA^\top A ("Cholesky QR": RR from the Cholesky factor of A⊤AA^\top A, then Q=AR−1Q = AR^{-1}):

    import numpy as np
    from scipy.linalg import solve_triangular
    
    rng = np.random.default_rng(0)
    def with_condition(kappa, m=80, n=20):  # random A with singular values from 1 down to 1/kappa
        U, _ = np.linalg.qr(rng.standard_normal((m, n)))
        V, _ = np.linalg.qr(rng.standard_normal((n, n)))
        return (U * np.logspace(0, -np.log10(kappa), n)) @ V.T
    
    for kappa in [1e2, 1e4, 1e6]:
        A = with_condition(kappa)
        I = np.eye(A.shape[1])
        Qh, _ = np.linalg.qr(A)                         # Householder
        L = np.linalg.cholesky(A.T @ A)                 # Cholesky QR: R = Lᵀ, Q = A R⁻¹
        Qc = solve_triangular(L, A.T, lower=True).T
        print(f"kappa {kappa:.0e}  cond(AᵀA) {np.linalg.cond(A.T @ A):.1e}  "
              f"Householder {np.abs(Qh.T @ Qh - I).max():.0e}  Cholesky-QR {np.abs(Qc.T @ Qc - I).max():.0e}")
    # cond(AᵀA) = 1e4, 1e8, 1e12 = kappa²; Householder stays near 1e-15; Cholesky-QR grows like
    # eps·kappa² (2e-13, 1e-9, 2e-5)
    

    The Läuchli matrix, a rank-deficient matrix with pivoted QR, and the minimum-norm solution:

    import numpy as np
    from scipy.linalg import qr
    
    d = 1e-8
    A = np.array([[1., 1.], [d, 0.], [0., d]])
    print(A.T @ A)                                      # [[1. 1.] [1. 1.]]: 1 + d² rounded to 1
    print(np.linalg.matrix_rank(A), np.linalg.matrix_rank(A.T @ A))   # 2 1
    print(np.linalg.lstsq(A, np.array([2., d, d]), rcond=None)[0])     # [1. 1.]: fine on A itself
    
    B = np.array([[1., 0., 1.], [0., 1., 1.], [1., 1., 2.], [1., 0., 1.]])   # col 3 = col 1 + col 2
    Q, R, perm = qr(B, pivoting=True)                   # column-pivoted QR: B[:, perm] = Q R
    print(np.abs(np.diag(R)))                           # [2.6 0.85 ~2e-16]: numerical rank 2
    x = np.linalg.lstsq(B, np.array([1., 2., 3., 4.]), rcond=None)[0]   # minimum-norm LS solution
    print(x @ np.array([1., 1., -1.]))                  # ~0: x is orthogonal to N(B) = span(1, 1, -1)
    

    6. Where it shows up #

    • Regression software. R's lm uses Householder QR; NumPy's lstsq and scikit-learn's LinearRegression use the SVD-based LAPACK driver gelsd. None of them forms (X⊤X)−1(X^\top X)^{-1}.
    • Random orthogonal matrices. torch.nn.init.orthogonal_ takes the QR of a Gaussian matrix and multiplies the columns of QQ by sign⁡(diag⁡R)\operatorname{sign}(\operatorname{diag} R). Without this sign fix, QQ is not uniformly (Haar) distributed.
    • ML for science. Gauss–Newton and Levenberg–Marquardt steps in inverse problems and data assimilation are linear least-squares problems. Square-root Kalman filters update a triangular factor with orthogonal transformations, so the covariance stays positive semidefinite. Streaming sensor data can update RR with Givens rotations, one sweep per new row.
    • Overparameterized models. Gradient descent on ∥Ax−b∥2\|Ax - b\|^2 from x0=0x_0 = 0 moves only along gradients A⊤(Ax−b)∈C(A⊤)A^\top(Ax - b) \in C(A^\top), so with a small enough step it converges to the minimum-norm solution A+bA^+b: the simplest example of the implicit bias of gradient descent.

    7. Common mistakes #

    • Computing inv(A.T @ A) @ A.T @ b. It squares κ\kappa and adds an explicit inverse. Use QR or lstsq.
    • The wrong Householder sign. v=x−sign⁡(x1)∥x∥e1v = x - \operatorname{sign}(x_1)\|x\|e_1 cancels when xx is near the e1e_1 axis.
    • Building the m×mm \times m matrix HH. Apply HH as a rank-1 update instead.
    • Testing a QR code only with ∥A−QR∥\|A - QR\|. Gram–Schmidt passes this test even when QQ is far from orthogonal. Check ∥Q⊤Q−I∥\|Q^\top Q - I\| too, and fix the signs with D=diag⁡(sign⁡rkk)D = \operatorname{diag}(\operatorname{sign} r_{kk}) before comparing with a library QR.
    • Computing every CGS coefficient from the original column and calling it MGS. MGS takes rjkr_{jk} from the partly reduced vector; this one change is the difference between εκ2\varepsilon\kappa^2 and εκ\varepsilon\kappa.
    • Plain QR on a rank-deficient matrix. Use pivoted QR, a truncated SVD or ridge.

    8. Check yourself #

    1. Give the Householder vector vv that maps x=(3,4)x = (3, 4) to a multiple of e1e_1, and HxHx. Give the Givens (c,s)(c, s) for the same vector.
      Answerx1>0x_1 > 0, so v=(3+5,4)=(8,4)v = (3 + 5, 4) = (8, 4). v⊤x=40v^\top x = 40, v⊤v=80v^\top v = 80, so Hx=x−v=(−5,0)Hx = x - v = (-5, 0). Givens: r=5r = 5, c=3/5c = 3/5, s=4/5s = 4/5, and Gx=(5,0)G x = (5, 0).
    2. A regression has κ(A)=105\kappa(A) = 10^5 and a small residual. About how many correct digits do the normal equations and Householder QR give in double precision?
      AnswerNormal equations: εκ2≈2×10−6\varepsilon\kappa^2 \approx 2 \times 10^{-6}, about 5–6 digits. QR: εκ≈2×10−11\varepsilon\kappa \approx 2 \times 10^{-11}, about 10–11 digits.
    3. Find the minimum-norm solution of x1+x3=1x_1 + x_3 = 1, x2+x3=2x_2 + x_3 = 2, and check it against N(A)N(A).
      AnswerAA⊤=(2112)AA^\top = \begin{pmatrix} 2 & 1 \\ 1 & 2\end{pmatrix}, y=(AA⊤)−1(1,2)=(0,1)y = (AA^\top)^{-1}(1, 2) = (0, 1), x+=A⊤y=(0,1,1)x^+ = A^\top y = (0, 1, 1). N(A)=span⁡(1,1,−1)N(A) = \operatorname{span}(1, 1, -1) and (0,1,1)⋅(1,1,−1)=0(0, 1, 1)\cdot(1, 1, -1) = 0. All solutions: (0,1,1)+t(1,1,−1)(0, 1, 1) + t(1, 1, -1), with ∥x∥2=2+3t2\|x\|^2 = 2 + 3t^2, smallest at t=0t = 0.
    4. CGS and MGS give the same numbers in exact arithmetic. How do they compare with each other and with Householder in floating point, for κ(A)=108\kappa(A) = 10^8?
      AnswerLoss of orthogonality: CGS ≈εκ2\approx \varepsilon\kappa^2, i.e. order 1 (orthogonality gone); MGS ≈εκ≈10−8\approx \varepsilon\kappa \approx 10^{-8}; Householder ≈10−16\approx 10^{-16}, independent of κ\kappa. MGS is better than CGS but not as good as Householder.
    5. Run Gram–Schmidt on a1=(3,4)a_1 = (3, 4), a2=(1,0)a_2 = (1, 0). Give QQ and RR.
      Answerr11=5r_{11} = 5, q1=(3,4)/5q_1 = (3, 4)/5. r12=q1⊤a2=3/5r_{12} = q_1^\top a_2 = 3/5, v2=(1,0)−35⋅15(3,4)=(16,−12)/25v_2 = (1, 0) - \tfrac35 \cdot \tfrac15(3, 4) = (16, -12)/25, r22=∥v2∥=20/25=4/5r_{22} = \|v_2\| = 20/25 = 4/5, q2=(4,−3)/5q_2 = (4, -3)/5. So Q=15(344−3)Q = \tfrac15\begin{pmatrix} 3 & 4 \\ 4 & -3 \end{pmatrix} and R=(53/504/5)R = \begin{pmatrix} 5 & 3/5 \\ 0 & 4/5 \end{pmatrix}. Check: r11r22=4=∣det⁡A∣r_{11}r_{22} = 4 = |\det A|.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. State the QR theorem for a matrix with independent columns.

    2. Write one Gram–Schmidt step for column kk.

    3. Gram–Schmidt on a1=(1,1,0)a_1 = (1, 1, 0), a2=(1,0,1)a_2 = (1, 0, 1): what are q2q_2 and r22r_{22}?

    4. Which vector vv defines the Householder reflection that maps xx to a multiple of e1e_1, and why this sign?

    5. Give the Givens rotation that maps (a,b)(a, b) to (r,0)(r, 0).

    6. Why do the normal equations A⊤Ax^=A⊤bA^\top A\hat x = A^\top b hold at the least-squares solution?

    7. How do you solve least squares with a QR factorization?

    8. What is κ(A⊤A)\kappa(A^\top A), and what does it cost the normal equations?

    9. What is the minimum-norm solution of Ax=bAx = b for a wide AA with full row rank?

    10. Why is Householder QR backward stable while Gram–Schmidt is not?

    Open the review →

    9. Interview angle #

    • "How do you fit linear regression in practice? Why not (X⊤X)−1X⊤y(X^\top X)^{-1}X^\top y?" — QR or an SVD solver (lstsq). The closed form squares κ\kappa and fails near κ≈108\kappa \approx 10^8. For small κ\kappa, the normal equations (or ridge with Cholesky) are fine and cheaper.
    • "Gram–Schmidt or Householder?" — Gram–Schmidt builds orthogonality by subtraction (CGS ≈εκ2\approx\varepsilon\kappa^2, MGS ≈εκ\approx\varepsilon\kappa). Householder reaches triangular form with reflections: backward stable, orthogonal to O(ε)O(\varepsilon). Gram–Schmidt (with reorthogonalization) stays useful when vectors arrive one at a time, as in Krylov methods.
    • "What does np.linalg.lstsq return for a rank-deficient XX?" — the minimum-norm least-squares solution; singular values below rcond·σmax⁡\sigma_{\max} count as zero.

    10. Practice #

    The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:

    1. Write classical and modified Gram–Schmidt.
    2. Write Householder QR with the stable sign choice, applying each reflection as a rank-1 update.
    3. Write a Givens rotation with hypot.
    4. Solve least squares by QR (Rx^=Q⊤bR\hat x = Q^\top b) and compare its accuracy with the normal equations as κ\kappa grows.
    5. Compute the minimum-norm solution of an underdetermined system through the QR of A⊤A^\top.

    The notebook then runs the stability shootout of the fourth figure with your own Gram–Schmidt and Householder codes, and shows the Läuchli matrix.

    11. Watch and read #

    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Open on YouTube · the player loads from youtube-nocookie.com when you press play