The QR Factorization
Orthogonal matrices preserve lengths, so they do not amplify errors. The QR factorization writes with having orthonormal columns and upper triangular. It turns least squares into a triangular solve without ever forming , and it is the standard method in numerical libraries.
Thin and full QR
For an matrix with :
- Thin QR: with of size () and of size .
- Full QR: with square orthogonal () and of size with zeros below row .
The columns of are an orthonormal basis of the column space of .
Gram-Schmidt
The classical way to build : orthogonalize each column of against the previous 's and normalize. The coefficients form . The modified version subtracts projections one at a time, which is mathematically identical but much more robust in floating point.
import numpy as np
def gram_schmidt(A, modified=True):
m, n = A.shape
Q = np.zeros((m, n)); R = np.zeros((n, n))
for j in range(n):
v = A[:, j].astype(float).copy()
for i in range(j):
R[i, j] = Q[:, i] @ (v if modified else A[:, j])
v -= R[i, j] * Q[:, i]
R[j, j] = np.linalg.norm(v)
Q[:, j] = v / R[j, j]
return Q, R
t = np.linspace(0, 1, 60)
A = np.vander(t, 10, increasing=True) # ill-conditioned columns
for name, mod in (("classical", False), ("modified ", True)):
Q, R = gram_schmidt(A, mod)
print(f"{name} GS: ||Q^T Q - I|| = {np.linalg.norm(Q.T @ Q - np.eye(10)):.1e}, ||QR - A|| = {np.linalg.norm(Q @ R - A):.1e}")
Q, R = np.linalg.qr(A)
print(f"Householder: ||Q^T Q - I|| = {np.linalg.norm(Q.T @ Q - np.eye(10)):.1e}")classical GS: ||Q^T Q - I|| = 1.1e-01, ||QR - A|| = 1.2e-15
modified GS: ||Q^T Q - I|| = 1.4e-10, ||QR - A|| = 1.2e-15
Householder: ||Q^T Q - I|| = 2.2e-15
All three reproduce , but the classical version loses orthogonality badly, and even modified Gram-Schmidt degrades in proportion to . Householder reflections keep orthogonal to machine precision (Householder Reflections).
Least squares by QR
With , the normal equations become , and since is invertible:
One matrix-vector product and one backward substitution. The conditioning is that of , not of .
import numpy as np
from scipy.linalg import solve_triangular
t = np.linspace(0, 1, 100)
A = np.vander(t, 14, increasing=True)
y = A @ np.ones(14) # exact coefficients: all ones
Q, R = np.linalg.qr(A) # thin QR by default
c_qr = solve_triangular(R, Q.T @ y)
c_ne = np.linalg.solve(A.T @ A, A.T @ y)
print(f"QR error: {np.max(np.abs(c_qr - 1)):.1e}")
print(f"NE error: {np.max(np.abs(c_ne - 1)):.1e}")QR error: 4.5e-07
NE error: 1.3e+01
Cost
Householder QR costs about flops, roughly twice the normal equations when . That price buys stability, and it is almost always worth paying.
In software
np.linalg.qr(A)(thin by default;mode="complete"for full),scipy.linalg.qr(with column pivotingpivoting=Truefor rank-revealing QR).np.polyfitandscipy.linalg.lstsq(lapack_driver="gelsy")use QR;np.linalg.lstsquses the SVD (Computing the SVD).- QR is also the engine of the eigenvalue algorithm (The QR Algorithm).
Exercises
Exercise 1: QR by hand
Find the thin QR factorization of by Gram-Schmidt.
Answer
, .
Solution
, . ; , , .
Exercise 2: Why orthogonal?
Why do multiplications by an orthogonal not amplify errors?
Answer
, so .
Solution
. A perturbation keeps its size after multiplication by .
Exercise 3: Residual from QR (code)
With the full QR, the least-squares residual norm equals . Verify this for a line fit to 20 noisy points (seed 33).
Answer
The two numbers agree.
Solution
import numpy as np
rng = np.random.default_rng(33)
t = np.linspace(0, 1, 20); y = 2 - t + rng.normal(0, 0.1, 20)
A = np.column_stack([np.ones(20), t])
Q, R = np.linalg.qr(A, mode="complete")
qty = Q.T @ y
c = np.linalg.solve(R[:2], qty[:2])
print(round(float(np.linalg.norm(y - A @ c)), 10), round(float(np.linalg.norm(qty[2:])), 10))0.3886842625 0.3886842625
Test yourself
Least squares via QR solves…
- exactly
Why is modified Gram-Schmidt preferred to classical?
- It is faster
- It keeps the columns of much closer to orthogonal in floating point
- It gives a different in exact arithmetic
- It needs no square roots
The columns of in a thin QR of full-rank form…
- the null space of
- an orthonormal basis of the column space of
- the eigenvectors of
- the rows of