Orthogonalization and least squares: Householder, Givens and QR
Orthogonal transformations avoid amplifying errors. Study orthogonalization with Householder reflections and Givens rotations, losses of orthogonality in Gram–Schmidt, implicit Householder QR, updating factorizations with Givens, and rank-deficient least squares with pivoted QR and truncated SVD.
After this lesson you can
- Implement Householder QR by saving reflectors without forming Q.
- Measure and explain loss of orthogonality in classical, modified and reorthogonalized Gram–Schmidt.
- Solve least squares by QR and SVD, and explain why normal equations square κ.
- Update a QR factorization when adding rows using Givens rotations.
- Determine numerical rank and the minimum-norm solution of a rank-deficient problem.
Before you start
- 09Backward stabilityPerturbation theory for linear systemsFlop countingForward and back substitutionCholesky in finite precision: stability and jitter
- 02Orthogonal projectionOrthogonal matrixQR decompositionGram-Schmidt orthogonalizationHouseholder reflectionGivens rotationSingular value decompositionMoore-Penrose pseudoinverse
Motivation: a regression gone wrong
You have 40 measurements of a noisy periodic signal and want to fit a polynomial of moderate degree , between 4 and 12. The independent variable is a date or temperature in , so you write the model in powers and solve the least-squares problem in the most direct way you know, with the normal equations .
import numpy as np
rng = np.random.default_rng(1)
s = np.linspace(0, 1, 40)
y = np.sin(2 * np.pi * s) + 0.1 * rng.standard_normal(40)
t = 1 + s # las mismas medidas, con la variable en [1, 2]
tt = np.linspace(1, 2, 400)
print("grado kappa(X) kappa(X)^2 Cholesky dif. coeficientes residuo NE / lstsq distancia curvas")
for p in range(4, 13):
X = np.vander(t, p + 1, increasing=True) # columnas 1, t, ..., t^p
G, h = X.T @ X, X.T @ y
try: # según la plataforma, Cholesky lanza un error o devuelve NaN
chol = "funciona" if np.all(np.isfinite(np.linalg.cholesky(G))) else "falla"
except np.linalg.LinAlgError:
chol = "falla"
c_ne = np.linalg.solve(G, h) # ecuaciones normales por eliminación gaussiana
c_ls = np.linalg.lstsq(X, y, rcond=None)[0] # LAPACK: SVD
k = np.linalg.cond(X)
dif = np.linalg.norm(c_ne - c_ls) / np.linalg.norm(c_ls)
exceso = np.linalg.norm(X @ c_ne - y) / np.linalg.norm(X @ c_ls - y)
dist = np.max(np.abs(np.vander(tt, p + 1, increasing=True) @ (c_ne - c_ls)))
print(f"{p:4d} {k:9.1e} {k * k:9.1e} {chol:8s} {dif:12.1e} {exceso:12.4f} {dist:9.1e}")
print(f"\n1/u = {2.0**53:.1e}")Read the table from top to bottom. Through degree 6 the solutions agree to at least three digits. At degree 7 coefficients differ by 3 %, and from degree 8 they have no digits in common: relative differences are 91 % and then 100 %. At degree 9 two other symptoms appear. Cholesky, which should work for any full-rank , fails. And the normal-equations residual is 29 % greater than that of lstsq: this is not another equally good answer to an ill-conditioned problem; the problem has not been solved, because a coefficient vector fits the same data better. The curves, however, differ by at most , and much less at other degrees: normal-equation errors lie in directions that barely change the curve over the data, so the failure goes unnoticed if you only look at the graph. (A practical detail: depending on the platform, np.linalg.cholesky raises an error or silently returns a matrix with NaN; the cell checks both.)
The columns diagnose the problem. At degree 8, is high but manageable in double precision: a stable algorithm can give about 6 coefficient digits. But normal equations work with , whose condition number is , a thousand times greater than . By linear-system perturbation theory, rounding just when forming is enough to make the matrix indistinguishable from a singular one; Cholesky completing at degree 8 and failing at degree 9 depends on rounding luck. The threshold is where the table says: coefficients deteriorate as approaches (degree 7) and are lost completely when it exceeds it. In the conditioning lesson you saw the same with and degree 12; here degree 8 suffices because the powers of are even more alike.
This lesson gives the full numerical answer. Orthogonal matrices do not amplify errors, making them the tools for stable least-squares, eigenvalue and SVD algorithms. From the linear algebra orthogonality lesson you already know Gram–Schmidt, Householder reflectors and Givens rotations. Here we study their floating-point behavior and actual implementation: why classical Gram–Schmidt loses orthogonality in proportion to and modified Gram–Schmidt to , how LAPACK stores reflectors without forming , how to update a factorization when new data arrive, why normal equations square , and what to do with a rank-deficient matrix.
Why orthogonal transformations are stable
An matrix with preserves the Euclidean norm: . Consequently and : an input error emerges with exactly the same norm. Applied to a chain of transformations, this property makes orthogonal algorithms stable.
Compare Gaussian elimination. Each step multiplies by a Gauss transformation , which is not orthogonal: can be large, and errors in one step are amplified in later steps. That is why Gaussian elimination analysis needs the growth factor, which can reach with partial pivoting. Orthogonal transformations have no such growth.
Proof
By induction on . For , and . Assume the result for and define , which is orthogonal. Then
The middle factor has , because multiplication by orthogonal matrices preserves the 2-norm. Thus with , and .
∎The key step is : the error at step can be moved back to the start of the chain without growing. If the were arbitrary matrices, this would multiply by , and with ill-conditioned factors the bound would be exponential. Applying a Householder reflector in floating point is equivalent, column by column, to multiplying by an of this kind with of order (Higham, chapter 19), yielding the lesson’s central result.
This is the theorem in chapter 19 of Higham (2002), and the normwise version of Trefethen and Bau (lecture 16). Three observations: the bound is columnwise: each column of is perturbed little relative to its own norm, even if columns have very different scales. The theorem’s is exactly orthogonal, and the computed one is orthogonal to , independently of : Gram–Schmidt does not achieve this. Nor does it say is close to the exact : if is ill-conditioned, may differ greatly entrywise and still be the exact of a nearby matrix. This is pure backward stability; final accuracy depends on conditioning of the problem solved with it.
Gram–Schmidt in floating point
In Gram–Schmidt orthogonalization, column is orthogonalized against earlier columns by subtracting its projections. There are three ways to organize these subtractions, identical in exact arithmetic:
- Classical (CGS): for every with the original vector, and . In matrix form, : two matrix-vector products, which parallelize well.
- Modified (MGS): with the already partially cleaned vector, and . This successively applies projectors .
- With reorthogonalization (CGS2): repeat the classical step twice, and , adding both coefficient sets in .
CGS and MGS cost about flops; CGS2 costs twice as much. All three give factorizations that reconstruct to . They differ in orthogonality of : this is the stability of classical and modified Gram–Schmidt, a quantitative result with precise assumptions.
The assumptions matter: CGS requires , meaning must be numerically nonsingular; MGS and CGS2 require only , that have numerical full rank. Outside these assumptions there is no guarantee: in the lab CGS with produces vectors that are not orthogonal even to one digit. The previous theorem’s Householder bounds assume nothing about . The 2005 paper is in Numerische Mathematik 101.
Where does the of CGS come from? The key to Giraud and coauthors’ proof is that the CGS is a backward-stable Cholesky factor of : with . If also with small (reconstruction is good), then
and since , the parenthesized term, of size , is divided by : . In other words, inside, CGS is a Cholesky factorization of the normal equations, and inherits their . This is not an analogy: the argument is the same as for the failure of normal equations in the motivation.
MGS avoids that mechanism because each projection is computed on the corrected vector, which has lost components introduced by rounding in earlier steps. The clearest analysis is by Björck and Paige (1992, Loss and recapture of orthogonality in the modified Gram-Schmidt algorithm, SIAM J. Matrix Anal. Appl.): MGS applied to is numerically equivalent to Householder QR applied to the augmented matrix , with rows of zeros above. Two everyday consequences follow:
- MGS’s is as good as Householder’s, although its loses orthogonality in proportion to .
- For least squares, do not compute . Apply MGS to and take the last column of as : the same dot products, but with the progressively cleaned vector. This is backward stable; with it is not. The interactive shows this in Least squares mode.
CGS2 is the practical remedy when vectors must be orthogonalized one by one and orthogonality is wanted to : the second pass cleans up what the first left, and a third adds nothing (“twice is enough,” an observation Parlett attributes to Kahan). It costs twice as much as CGS, but its matrix-vector products distribute well across threads and nodes, whereas MGS is inherently sequential within each column. Hence its common use in Arnoldi’s process for Krylov methods.
Householder in practice
Householder QR in practice involves three implementation decisions (the destination sign, compact reflector storage and implicit application of ) that turn the Householder reflection into LAPACK routine geqrf.
A closer look at the sign
To zero all of except its first entry there are two destinations of equal length, , and the reflector uses . The remaining entries of are those of , copied without error; all arithmetic is in . With destination and , subtracts nearly equal numbers when is nearly aligned with . The interactive simulates 11- or 24-bit mantissa arithmetic (float16 and float32), rounding each operation so the phenomenon is visible at larger angles; float64 behaves the same with .
The magnified view shows a detail standard analysis misses. The subtraction , with the computed value of , is exact in floating point when (Sterbenz’s lemma from catastrophic cancellation). Subtraction adds no error: it reveals the error already present in . That absolute error, about , is small relative to but enormous relative to : relative error in is of order , and normwise error in is , because . You will prove this in the guided exercise at the end. The entry that should vanish is then about .
The lower graph shows what happens for still smaller angles. When drops below half a grid spacing, that is, when , the computed value is : the computed mirror is the axis itself, sending to and zeroing nothing, and the remaining entry is . The branches and cross at , where error reaches its maximum, about . In float64 this is : Householder QR with the naive sign loses half its digits in the worst case. The interactive starts there: with (, ) and rad, the exact , , spans half a grid spacing; the computed one, , spans a full spacing, with 93 % relative error, and the entry that should vanish is , 48 times .
There are two remedies, both in the interactive:
- Choose destination so is a sum of two numbers with the same sign. LAPACK does this with .
- Keep the positive destination and rewrite the subtraction: if . This is Parlett’s formula (Golub and Van Loan, section 5.1.3), useful when a positive diagonal of is desired.
How LAPACK stores reflectors
LAPACK routine dlarfg normalizes the reflector so its first entry is 1. Given , it computes
and then satisfies . Denominator is a sum of two numbers with the same sign, so it does not cancel either. Since , scalar is always in (it equals , as required for to be orthogonal). If there is nothing to zero and dlarfg returns , that is, .
The advantage of is that it need not be stored. In step , entries of column are zeroed, leaving exactly enough space for entries of . The matrix is overwritten as follows, for and :
occupies the upper triangle and reflectors the lower: no additional memory except the scalars . This is exactly what np.linalg.qr(A, mode="raw") returns (transposed, since LAPACK stores by columns), and your lab implementation will reproduce it.
Apply without forming
With , product is computed reflector by reflector. Each touches only entries and costs one dot product and one update:
with flops. In total, flops and no matrix in memory. Forming the thin () by backward accumulation, , costs as much as factorization itself, and forming full costs still more and stores numbers: with observations, 8 TB. Least squares needs only .
Cost
If , , the same as Gram–Schmidt; if , , twice LU. This is the flop count needed to compare with normal equations.
Updating QR with Givens rotations
A Givens rotation zeros one entry by mixing two rows. For a dense matrix it costs more than Householder, but when the matrix is already almost triangular, zeroing the few remaining entries with rotations costs instead of for refactorization. This is updating QR factorizations.
Computing the rotation
To zero against , find with and
Two numerical details. is computed with hypot, which scales before squaring: overflows in float64 if even when easily fits. No angle or trigonometric function is needed: and come from division. LAPACK routine dlartg does exactly this, taking extra care with or . Applying the rotation to two rows of length costs flops (four products and two sums per column).
Adding an observation
Suppose you have the QR of a least-squares problem with data points and observation arrives, a row with response . The trick is to factor the augmented matrix : its triangular factor is
because the first columns give the QR of , the projected last column is , and what remains of outside has norm , the residual of solution . All problem information, whatever , fits in an matrix.
Proof
Write the matrix with the new observation as . Moving row immediately below and applying are orthogonal transformations, leaving the matrix as (orthogonal) times : a QR. Rotation mixes row of , which has zeros in columns , with the new row, which already has them from earlier rotations; it creates no fill and operates only on columns , using flops. The last rotation acts on pair in column and converts it to .
∎This is QR-form recursive least squares. With forgetting factor , multiply by before each new observation, and the solution is weighted least squares with weights : the observation steps ago weighs and effective memory is about observations. It is natural for rolling factor regressions in factor regressions, and you implement it in the lab. Classical recursive least squares, which updates using Sherman–Morrison, works with the normal-equations matrix and inherits its ; QR works with , whose condition number is .
Hessenberg matrices and removing columns or rows
An upper Hessenberg matrix has zeros below the first subdiagonal: just one entry to zero per column. Its QR uses rotations of adjacent rows and flops. This step is repeated in every iteration of the QR eigenvalue algorithm, which works with Hessenberg matrices.
Removing a column produces a Hessenberg matrix. If column of is deleted, later columns shift left and each retains an entry below the new diagonal: adjacent-row rotations restore triangular form. Backward variable selection and active-set methods need this operation. Adding a column requires , so reflectors or must be retained; then a reflector or rotations zero its lower part.
Removing a row (for a fixed-size sliding window) is harder. Without , it uses hyperbolic rotations, which are not orthogonal and can amplify errors when the removed row strongly influenced the solution; the problem is inherently worse conditioned because removing data can bring the matrix closer to rank deficiency. Björck (1996, chapter 3) analyzes alternatives. In practice either retain (as scipy.linalg.qr_delete does), or use exponential forgetting, which only adds rows.
Least squares: three algorithms and a bound
Let with and rank . Numerical least squares has three standard algorithms:
| Algorithm | Steps | Flops (leading order) | Order of relative error in (bound) |
|---|---|---|---|
| Normal equations | , Cholesky , two substitutions | always | |
| Householder QR | , , | ||
| SVD | , | several times QR | like QR, also handles rank deficiency |
For normal equations cost half as much as Householder ( is symmetric, so only half is computed). This is their only advantage; its price is in the last column. To understand it, we need to know how data perturbations affect the problem.
This is theorem 18.1 of Trefethen and Bau. The key cell is the bottom right. If the residual is small (), the problem’s condition number is , as for a square system. If not, appears, moderated by : the problem itself becomes sensitive to the square of , which no algorithm can avoid. Since Householder QR is backward stable for least squares (Higham, chapter 20; Trefethen and Bau, lecture 19), its error is bounded by a modest multiple of times that condition number. Normal equations instead solve a system with matrix , condition number , even when : they lose twice as many digits as QR precisely when unnecessary.
import numpy as np
import scipy.linalg as sl
def matriz_kappa(m, n, kappa, rng):
"""A = U diag(sigma) V^T con valores singulares de 1 a 1/kappa en progresión geométrica."""
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
def lstsq_normales(A, b):
L = np.linalg.cholesky(A.T @ A)
return sl.solve_triangular(L.T, sl.solve_triangular(L, A.T @ b, lower=True))
def lstsq_qr(A, b):
Q, R = np.linalg.qr(A) # Householder de LAPACK
return sl.solve_triangular(R, Q.T @ b)
rng = np.random.default_rng(2)
m, n, kappa, u = 60, 15, 1e6, 2.0**-53
A = matriz_kappa(m, n, kappa, rng)
x = rng.standard_normal(n)
y = A @ x
eta = np.linalg.norm(A, 2) * np.linalg.norm(x) / np.linalg.norm(y)
Qc, _ = np.linalg.qr(A, mode="complete")
r = Qc[:, n:] @ rng.standard_normal(m - n)
r /= np.linalg.norm(r) # dirección ortogonal a col(A)
E = rng.standard_normal((m, n))
E *= 1e-10 * np.linalg.norm(A, 2) / np.linalg.norm(E, 2) # perturbación aleatoria de tamaño relativo 1e-10
print(f"kappa = {kappa:.0e} eta = {eta:.1f} kappa u = {kappa * u:.1e} kappa^2 u = {kappa**2 * u:.1e}")
print(" tan(theta) condición teórica amplificación medida error QR error normales")
for tan in (0, 1e-8, 1e-6, 1e-4, 1e-2, 1):
b = y + tan * np.linalg.norm(y) * r # el residuo de x es exactamente tan(theta) ||y|| r
cond = kappa + kappa**2 * tan / eta
x_pert = np.linalg.lstsq(A + E, b, rcond=None)[0]
amp = np.linalg.norm(x_pert - x) / np.linalg.norm(x) / 1e-10
e_qr = np.linalg.norm(lstsq_qr(A, b) - x) / np.linalg.norm(x)
e_ne = np.linalg.norm(lstsq_normales(A, b) - x) / np.linalg.norm(x)
print(f"{tan:9.0e} {cond:10.1e} {amp:10.1e} {e_qr:8.1e} {e_ne:8.1e}")
# Läuchli: formar A^T A ya destruye la información
eps = 1e-8
L3 = np.array([[1, 1], [eps, 0], [0, eps]])
print("\nLäuchli, eps = 1e-8: fl(A^T A) =", (L3.T @ L3).tolist(), " rango", np.linalg.matrix_rank(L3.T @ L3), " frente a rango(A) =", np.linalg.matrix_rank(L3))The table separates problem from algorithm. The first two numerical columns concern the problem: theoretical conditioning and amplification measured by randomly perturbing by one part in and solving with lstsq. Random perturbation is not worst-case and amplifies 12 to 14 times less than the bound, but follows exactly the same law: constant () while dominates, and proportional to once exceeds it, which with happens near . With , relative data error causes error in , whatever the algorithm. The last two columns concern algorithms with exact data: QR stays between and throughout, below (backward stability guarantees a bound, and QR’s equivalent perturbation need not point in the worst direction); normal equations give from the first row, the level, although the problem with would justify only . They are never more accurate than QR; at best they match in order of magnitude when the residual is so large that governs the problem itself.
The last line is Läuchli’s example: has rank 2 and , but and, with , rounds to 1: the computed matrix is exactly singular. Information was present in the data and lost in the first product. No later algorithm, however good, can recover it.
The interactive shows two separate things. First, the theorem: with the same matrix, normal equations fail where QR does not. Second, depends on how the model is written. Columns with are nearly parallel (all grow similarly over the interval); centering and scaling the variable to separates them, and an orthogonal basis such as Chebyshev separates them further. For variables on different scales, the minimum remedy is column scaling: a theorem of van der Sluis (1969) says dividing each column by its norm puts within factor of the minimum across diagonal scalings . A variable in euros (of order ) alongside another in unit fractions can multiply by a factor of order without changing the statistical problem.
Rank deficiency
If has rank , least squares has infinitely many solutions, all those of , and has zeros on its diagonal. In floating point these zeros appear as small numbers, and the question changes from “what is the rank?” to “which singular values are noise?”. The numerical rank at tolerance is the number of singular values greater than , and it gives two tools.
Column-pivoted QR
Column-pivoted QR (Businger and Golub, 1965) selects at each step the remaining column with greatest active-row norm, swaps it into position and applies the reflector:
Remaining column norms are updated instead of recomputed, subtracting the square of the entry just moved to row , , and recomputing when subtraction cancels too much (LAPACK routine geqp3 does this). Extra cost over unpivoted QR is of order .
Proof
and are orthogonal, so and have the same singular values. For the first inequality, the first columns of form , with the same singular values as , and removing columns does not increase singular values (interlacing): . For the second, zeroing yields a matrix of rank at most at distance from ; by the Eckart–Young theorem, no rank- matrix is closer to than .
∎If is small, the matrix is near one of rank ; any permutation guarantees that. Pivoting does not guarantee the reverse: that large or implies large . Kahan’s matrix is the classic counterexample: with LAPACK column pivoting (and minimal rescaling of its columns, all of norm 1, to break ties), all are moderate yet the matrix is nearly singular. You will see it in the lab. Algorithms guarantee both directions (the “strong” rank-revealing QR of Gu and Eisenstat, 1996), but simple pivoting almost never fails in practice, making it the usual inexpensive numerical-rank estimate.
The minimum-norm solution
With pivoted QR and numerical rank , the most direct solution discards and solves , setting the remaining variables to zero. This is the basic solution: it uses only columns of , chosen by pivoting. It is not the minimum-norm solution and changes when column scales change.
The solution independent of these choices is the minimum-norm solution , which with SVD and a tolerance gives the truncated SVD:
This is the heart of rank-deficient least squares: the result depends on tolerance, which data should determine. Suppose , with noise of size per component. Then and
Keeping term adds noise of size ; discarding it loses . It is worthwhile to keep it while exceeds , meaning signal exceeds noise . The default relative tolerance of np.linalg.lstsq, , is designed for machine rounding, not measurement noise, and if is larger it lets through terms that are merely noise multiplied by .
Initially and tolerance is lstsq’s default: all 10 singular values are kept. Since signal in direction is , the last five (with from to ) are below noise, and relative solution error is . A cutoff at the noise level (rank 5) reduces it to . It does not reach zero: half the true solution lies in directions hidden by noise, and no algorithm can recover it from these data; the only option is not to invent it. No tolerance fits every problem: the right one depends on , so rcond requires thought, not just a technical setting. Ridge regularization, covered in ridge spectral shrinkage, replaces the hard cutoff with smooth factor .
Implementation from scratch
The first lab implements the three Gram–Schmidt variants and Householder QR with reflectors in LAPACK format, and checks that the latter reproduces LAPACK’s output.
import numpy as np
def cgs(A):
"""Gram-Schmidt clásico: todas las sombras de a_k se calculan con el vector original."""
A = np.asarray(A, dtype=float)
m, n = A.shape
Q, R = np.zeros((m, n)), np.zeros((n, n))
for k in range(n):
R[:k, k] = Q[:, :k].T @ A[:, k]
v = A[:, k] - Q[:, :k] @ R[:k, k]
R[k, k] = np.linalg.norm(v)
Q[:, k] = v / R[k, k]
return Q, R
def mgs(A):
"""Gram-Schmidt modificado (por filas de R): q_k se resta de todas las columnas en cuanto se conoce."""
Q = np.array(A, dtype=float)
n = Q.shape[1]
R = np.zeros((n, n))
for k in range(n):
R[k, k] = np.linalg.norm(Q[:, k])
Q[:, k] /= R[k, k]
R[k, k + 1:] = Q[:, k] @ Q[:, k + 1:]
Q[:, k + 1:] -= np.outer(Q[:, k], R[k, k + 1:])
return Q, R
def cgs2(A):
"""Gram-Schmidt clásico con reortogonalización: cada proyección se hace dos veces."""
A = np.asarray(A, dtype=float)
m, n = A.shape
Q, R = np.zeros((m, n)), np.zeros((n, n))
for k in range(n):
v = A[:, k].copy()
for _ in range(2):
h = Q[:, :k].T @ v
v -= Q[:, :k] @ h
R[:k, k] += h
R[k, k] = np.linalg.norm(v)
Q[:, k] = v / R[k, k]
return Q, R
def householder_qr(A):
"""QR de Householder en el formato de LAPACK (geqrf): R en el triángulo superior y, bajo la
diagonal de la columna k, el reflector v_k sin su primera entrada (que vale 1); H_k = I - tau_k v_k v_k^T."""
QR = np.array(A, dtype=float)
m, n = QR.shape
tau = np.zeros(n)
for k in range(min(m - 1, n)):
alpha, x = QR[k, k], QR[k + 1:, k]
sigma = np.linalg.norm(x)
if sigma == 0.0: # nada que anular: H_k = I
continue
beta = -np.copysign(np.hypot(alpha, sigma), alpha) # destino -sign(x1) ||x|| e1
tau[k] = (beta - alpha) / beta
QR[k + 1:, k] = x / (alpha - beta) # alpha - beta: mismo signo, no cancela
QR[k, k] = beta
v = QR[k + 1:, k]
w = QR[k, k + 1:] + v @ QR[k + 1:, k + 1:] # w = v^T A[k:, k+1:] con v[0] = 1
QR[k, k + 1:] -= tau[k] * w
QR[k + 1:, k + 1:] -= tau[k] * np.outer(v, w)
return QR, tau
def apply_qt(QR, tau, b):
"""Q^T b = H_n ... H_1 b sin formar Q: unos 4mn flops."""
b = np.array(b, dtype=float)
for k in range(len(tau)):
if tau[k] != 0.0:
v = np.concatenate(([1.0], QR[k + 1:, k]))
b[k:] -= tau[k] * v * (v @ b[k:])
return b
def form_q(QR, tau):
"""Q delgada (m x n) por acumulación hacia atrás: Q = H_1 (H_2 (... H_n [I; 0]))."""
m, n = QR.shape
Q = np.eye(m, n)
for k in reversed(range(len(tau))):
if tau[k] != 0.0:
v = np.concatenate(([1.0], QR[k + 1:, k]))
Q[k:, k:] -= tau[k] * np.outer(v, v @ Q[k:, k:])
return Q
rng = np.random.default_rng(0)
A = rng.standard_normal((7, 4))
QR, tau = householder_qr(A)
h, tau_lapack = np.linalg.qr(A, mode="raw") # LAPACK, en orden de Fortran
print("mismos reflectores, R y tau que LAPACK:", np.allclose(QR, h.T), np.allclose(tau, tau_lapack))
print("tau en [1, 2]:", np.round(tau, 4))
Q, R = form_q(QR, tau), np.triu(QR[:4])
b = rng.standard_normal(7)
print(f"||A - QR|| = {np.linalg.norm(A - Q @ R):.1e} ||I - Q^T Q|| = {np.linalg.norm(np.eye(4) - Q.T @ Q):.1e}")
print("Q^T b sin formar Q coincide:", np.allclose(apply_qt(QR, tau, b)[:4], Q.T @ b))The first three functions differ in two lines. In cgs, all coefficients of column come from A[:, k], the original vector; in mgs the loop is organized by rows of : once is normalized, its projection is subtracted from every later column, which reaches its turn already cleared of earlier directions. householder_qr reproduces LAPACK’s format bit for bit, as comparison with mode="raw" confirms, and fall in as the formula predicts.
Now the measurement summarizing this section: orthogonality of each against , with the same matrix model as the interactive.
import numpy as np
import matplotlib.pyplot as plt
def matriz_kappa(m, n, kappa, rng):
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
rng = np.random.default_rng(0)
m, n, u = 60, 15, 2.0**-53
I = np.eye(n)
exps = np.arange(0, 17, 2)
perdida = {"CGS": [], "MGS": [], "CGS2": [], "Householder": []}
print(" kappa CGS MGS CGS2 Householder peor ||A-QR||/||A||")
for e in exps:
A = matriz_kappa(m, n, 10.0**e, rng)
QR, tau = householder_qr(A)
fact = {"CGS": cgs(A), "MGS": mgs(A), "CGS2": cgs2(A), "Householder": (form_q(QR, tau), np.triu(QR[:n]))}
peor = 0.0
for nombre, (Q, R) in fact.items():
perdida[nombre].append(np.linalg.norm(I - Q.T @ Q, 2))
peor = max(peor, np.linalg.norm(A - Q @ R, 2) / np.linalg.norm(A, 2))
print(f"1e{e:<4d}" + "".join(f"{perdida[k][-1]:10.1e}" for k in perdida) + f" {peor:.1e}")
for nombre in ("CGS", "MGS"):
p = np.array(perdida[nombre])
ok = (p > 1e-14) & (p < 1e-2) # tramo entre el suelo u y la saturación
print(f"pendiente de {nombre} en escala log-log: {np.polyfit(exps[ok], np.log10(p[ok]), 1)[0]:.2f}")
k = 10.0**exps
for nombre, marca in zip(perdida, "os^d"):
plt.loglog(k, perdida[nombre], marca + "-", label=nombre)
plt.loglog(k, u * k**2, "k:", label="uκ²")
plt.loglog(k, u * k, "k--", label="uκ")
plt.ylim(1e-17, 1e2); plt.xlabel("κ₂(A)"); plt.ylabel("‖I − QᵀQ‖₂"); plt.legend(); plt.show()The measured slopes match the theorem: for CGS (near 2: the theorem’s constant is not uniform across the range) and for MGS. With , CGS’s has ; with it is 3, no longer orthogonal to any digit, and beyond that saturates between 3 and 7. MGS retains with , about 8 digits. CGS2 and Householder never exceed , even at , where CGS2’s assumptions no longer hold and theory guarantees nothing. The last column is most often forgotten: all four factorizations reconstruct with error of order . Looking only at never warns that is not orthogonal.
Finally, least squares with the lesson’s algorithms and two library routines, for zero-residual problems where a stable method’s error should be of order .
import numpy as np
import scipy.linalg as sl
def lstsq_householder(A, b):
QR, tau = householder_qr(A)
n = A.shape[1]
return sl.solve_triangular(QR[:n], apply_qt(QR, tau, b)[:n]) # solve_triangular mira solo el triángulo superior
def lstsq_mgs(A, b): # MGS y después Q^T b con la Q calculada
Q, R = mgs(A)
return sl.solve_triangular(R, Q.T @ b)
def lstsq_mgs_ampliada(A, b): # MGS sobre [A b]: la última columna de R es Q^T b
n = A.shape[1]
_, R = mgs(np.column_stack([A, b]))
return sl.solve_triangular(R[:n, :n], R[:n, n])
def lstsq_scipy_qr(A, b):
Q, R = sl.qr(A, mode="economic")
return sl.solve_triangular(R, Q.T @ b)
metodos = {"normales": lstsq_normales, "MGS, Q^T b": lstsq_mgs, "MGS [A b]": lstsq_mgs_ampliada,
"Householder": lstsq_householder, "scipy qr": lstsq_scipy_qr,
"np lstsq": lambda A, b: np.linalg.lstsq(A, b, rcond=None)[0]}
rng = np.random.default_rng(1)
m, n, u = 60, 15, 2.0**-53
print("kappa " + "".join(f"{k:>13s}" for k in metodos) + " u*kappa")
for e in (2, 4, 6, 8, 10, 12):
A = matriz_kappa(m, n, 10.0**e, rng)
x = rng.standard_normal(n)
b = A @ x # residuo nulo: theta = 0
errores = []
for f in metodos.values():
try:
errores.append(np.linalg.norm(f(A, b) - x) / np.linalg.norm(x))
except (np.linalg.LinAlgError, ValueError):
errores.append(np.nan) # Cholesky falla o devuelve NaN
print(f"1e{e:<4d}" + "".join(f"{v:13.1e}" for v in errores) + f" {10.0**e * u:.0e}")Four of six columns stay below the last, : Householder (ours), SciPy QR, lstsq and MGS applied to . The other two diverge: normal equations have error with and from Cholesky does not even finish (nan); MGS with is just as bad ( with ), and with gives error , no correct digits. The difference between columns two and three is Björck and Paige’s result: the same algorithm, the same poorly orthogonal , only where is computed changes.
Lab: online regression and rank deficiency
The second lab applies row updates to a rolling factor regression and studies nearly collinear columns. The series is synthetic with an explicit model: daily asset return is , with three independent Gaussian factors and a market beta changing regime halfway through the sample. Regression uses exponential forgetting with , an effective memory of about 50 days.
import numpy as np
import scipy.linalg as sl
import matplotlib.pyplot as plt
def givens(a, b):
"""(c, s, r) con [c s; -s c] [a; b] = [r; 0] y r = hypot(a, b) >= 0."""
if b == 0.0:
return (1.0, 0.0, a) if a >= 0 else (-1.0, 0.0, -a)
r = np.hypot(a, b)
return a / r, b / r, r
def anadir_fila(Rt, fila, lam=1.0):
"""Rt: triangular (n+1) x (n+1) de [A b]. Devuelve la de [sqrt(lam) [A b]; fila]: unos 3n^2 flops."""
Rt = np.sqrt(lam) * Rt # olvido exponencial
w = np.array(fila, dtype=float)
for k in range(len(w)):
c, s, r = givens(Rt[k, k], w[k])
fila_k = Rt[k, k + 1:].copy()
Rt[k, k] = r
Rt[k, k + 1:] = c * fila_k + s * w[k + 1:]
w[k + 1:] = -s * fila_k + c * w[k + 1:]
w[k] = 0.0
return Rt
def resolver(Rt):
"""Coeficientes y norma del residuo (ponderado) a partir de la R de [A b]."""
n = Rt.shape[0] - 1
return sl.solve_triangular(Rt[:n, :n], Rt[:n, n]), abs(Rt[n, n])
rng = np.random.default_rng(7)
T = 750
F = rng.standard_normal((T, 3)) * np.array([0.010, 0.006, 0.005]) # mercado, tamaño, valor
dias = np.arange(T)
beta_mkt = 0.8 + 0.6 * (dias > 375) + 0.1 * np.sin(dias / 40)
r = 0.0002 + beta_mkt * F[:, 0] + 0.3 * F[:, 1] - 0.2 * F[:, 2] + 0.004 * rng.standard_normal(T)
X = np.column_stack([np.ones(T), F])
lam = 0.98
Rt = np.zeros((5, 5))
betas, dif = np.full(T, np.nan), 0.0
for t in range(T):
Rt = anadir_fila(Rt, np.append(X[t], r[t]), lam)
if t >= 4:
coef, rho = resolver(Rt)
betas[t] = coef[1]
if t % 50 == 0 or t == T - 1: # comprobación: mínimos cuadrados ponderados desde cero
w = np.sqrt(lam ** (t - dias[:t + 1]))
ref = np.linalg.lstsq(w[:, None] * X[:t + 1], w * r[:t + 1], rcond=None)[0]
dif = max(dif, np.linalg.norm(coef - ref) / np.linalg.norm(ref))
print(f"máxima diferencia relativa con lstsq rehecho desde cero: {dif:.1e}")
for t in (300, 450, 700):
print(f"t = {t}: beta estimada {betas[t]:.3f}, verdadera {beta_mkt[t]:.3f}")
plt.plot(dias, beta_mkt, color="gray", label="beta verdadera")
plt.plot(dias, betas, label="estimación en línea (λ = 0.98)")
plt.ylim(0, 2); plt.xlabel("día"); plt.ylabel("beta de mercado"); plt.legend(); plt.show()Rotation updates agree with weighted least squares recomputed from scratch to relative , and each step costs the same on day 10 as day 700: the entire state is an matrix. The graph shows the statistical tradeoff of forgetting: with 50 days’ memory the estimate is noisy (on day 300 it is versus true beta ) and adapts slowly to the day-376 jump: on day 450 it is still versus . A larger smooths it and slows adaptation. This tradeoff is statistical; the algebra is exact for any .
Now rank deficiency: six variables, two nearly linear combinations of the others, with deviations of size and , and responses with noise of size .
import numpy as np
import scipy.linalg as sl
rng = np.random.default_rng(3)
m = 200
Z = rng.standard_normal((m, 4))
X = np.column_stack([Z,
0.5 * Z[:, 0] + 0.5 * Z[:, 1] + 1e-6 * rng.standard_normal(m), # x5 casi (x1 + x2)/2
Z[:, 2] - Z[:, 3] + 1e-10 * rng.standard_normal(m)]) # x6 casi x3 - x4
beta = np.array([1.0, -1.0, 0.5, 2.0, 0.0, 0.0])
ruido = 1e-3
y = X @ beta + ruido * rng.standard_normal(m)
Q, R, piv = sl.qr(X, mode="economic", pivoting=True)
print("orden de las columnas elegido por el pivoteo (desde 1):", piv + 1)
print("|r_kk|: ", np.array2string(np.abs(np.diag(R)), precision=1))
print("valores singulares:", np.array2string(np.linalg.svd(X, compute_uv=False), precision=1))
def tsvd(X, y, tol):
"""Solución de norma mínima descartando los sigma_i <= tol * sigma_1."""
U, s, Vt = np.linalg.svd(X, full_matrices=False)
k = int(np.sum(s > tol * s[0]))
return Vt[:k].T @ ((U[:, :k].T @ y) / s[:k]), k
y2 = X @ beta + ruido * rng.standard_normal(m) # otra realización del ruido
print("\n tolerancia rango ||x|| residuo cambio de x con otro ruido")
for tol in (np.finfo(float).eps * m, 1e-12, 1e-8, 1e-5, 1e-2):
x1, k = tsvd(X, y, tol)
x2, _ = tsvd(X, y2, tol)
print(f"{tol:9.1e} {k} {np.linalg.norm(x1):9.3g} {np.linalg.norm(X @ x1 - y):9.4f} {np.linalg.norm(x1 - x2):9.3g}")
k = 4
xb = np.zeros(6)
xb[piv[:k]] = sl.solve_triangular(R[:k, :k], Q[:, :k].T @ y)
xm, _ = tsvd(X, y, 1e-5)
print("\nsolución básica (QR pivotada, rango 4):", np.round(xb, 3), f" norma {np.linalg.norm(xb):.3f}")
print("solución de norma mínima (SVD): ", np.round(xm, 3), f" norma {np.linalg.norm(xm):.3f}")
# la matriz de Kahan: el pivoteo de columnas no ve que es casi singular
n, c = 90, 0.285
s_ = np.sqrt(1 - c * c)
K = np.diag(s_ ** np.arange(n)) @ (np.eye(n) - c * np.triu(np.ones((n, n)), 1))
K = K @ np.diag((1 - 1e-12) ** np.arange(n)) # rompe los empates de normas: el pivoteo no permuta
_, RK, pK = sl.qr(K, pivoting=True)
sK = np.linalg.svd(K, compute_uv=False)
print(f"\nKahan {n}x{n}: sin permutar: {np.all(pK == np.arange(n))} min |r_kk| = {np.abs(np.diag(RK)).min():.2e} sigma_min = {sK[-1]:.2e}")Read the output from top to bottom:
- Pivoting reveals rank. The first four are of order 10, and the last two, and , are of the order of the two small singular values ( and ). The diagonal of tracks singular values much more cheaply than SVD. Note which columns it leaves last: 5 and 3. It does not identify “the culprits” ; it picks one well-conditioned set of four columns among several possibilities.
- Default tolerance does not suit noisy data. With all six singular values are retained and solution norm is (the true norm is ): noise divided by . It is unstable: another noise realization changes it by . Meanwhile the residual is the same in every row, or : it cannot distinguish a sensible solution from an absurd one. With tolerances between and , above relative noise, rank is 4 and solution change between realizations is .
- Basic is not minimum norm. Both rank-4 solutions fit equally well, but the basic one uses pivot-selected columns and has norm ; minimum norm spreads weight over collinear columns and has norm .
- Pivoting can fail. In Kahan’s matrix, pivoting makes no swaps and the smallest is , while . A rule like “rank ” would call the matrix full rank and well conditioned. This is deliberately constructed, but remember pivoted QR is a very reliable heuristic, not a two-way theorem.
In libraries
| Function | What it does |
|---|---|
np.linalg.qr(A) | Thin Householder QR (geqrf + orgqr). mode="r" only ; mode="complete" of ; mode="raw" reflectors and , like your householder_qr |
scipy.linalg.qr(A, pivoting=True) | Column-pivoted QR (geqp3); returns permutation as an index vector |
scipy.linalg.qr_multiply(A, c) | factors and multiplies by or without forming it |
scipy.linalg.qr_insert, qr_delete, qr_update | updates with Givens rotations; need and |
np.linalg.lstsq(A, b, rcond=None) | SVD (gelsd) with cutoff at rcond ; default rcond |
scipy.linalg.lstsq(A, b, cond, lapack_driver) | gelsd (divide-and-conquer SVD, default), gelss (classical SVD) or gelsy (pivoted QR with complete orthogonal factorization) |
import numpy as np
import scipy
import scipy.linalg as sl
print("NumPy", np.__version__, " SciPy", scipy.__version__)
A = np.random.default_rng(0).standard_normal((1000, 5))
b = np.ones(1000)
print("formas de np.linalg.qr:", [M.shape for M in np.linalg.qr(A)], " mode='r':", np.linalg.qr(A, mode="r").shape,
" mode='raw':", [M.shape for M in np.linalg.qr(A, mode="raw")])
qtb_t, R = sl.qr_multiply(A, b, mode="right") # devuelve b^T Q (Q delgada) sin formar Q
Q, _ = np.linalg.qr(A)
print("qr_multiply da Q^T b sin formar Q:", np.allclose(qtb_t, Q.T @ b))
Qf, Rf = sl.qr(A[:999]) # Q completa de 999 x 999
Q2, R2 = sl.qr_insert(Qf, Rf, A[999], 999, which="row")
print("qr_insert de una fila reproduce A:", np.allclose(Q2 @ R2, A))
# el problema casi colineal del laboratorio: tolerancias y drivers
x_def, _, rk_def, _ = np.linalg.lstsq(X, y, rcond=None)
x_tol, _, rk_tol, _ = np.linalg.lstsq(X, y, rcond=1e-5)
print(f"\nnp.linalg.lstsq por defecto: rango {rk_def}, ||x|| = {np.linalg.norm(x_def):.3g}")
print(f"np.linalg.lstsq rcond=1e-5: rango {rk_tol}, ||x|| = {np.linalg.norm(x_tol):.3g}")
for drv in ("gelsd", "gelss", "gelsy"):
x, _, rk, _ = sl.lstsq(X, y, cond=1e-5, lapack_driver=drv)
print(f"scipy lstsq {drv}: rango {rk}, distancia a la SVD truncada {np.linalg.norm(x - xm):.1e}")All three SciPy drivers give the minimum-norm solution at the same tolerance: gelsd and gelss match truncated SVD to , and gelsy, which does not compute singular values, reproduces it to because its complete orthogonal factorization also yields minimum norm. gelsy is usually fastest; gelsd most robust. None chooses the tolerance for you.
Common mistakes
Exercises
Step 1 of 4. What is exact with ?
householder_qr(A) returning (V, R): V is an matrix whose column is the unit vector of reflector (with zeros before entry ), and R is the upper triangular factor. Also implement apply_qt(V, b) returning (a vector of length ) without forming . Handle the sign and carefully. Assume .import numpy as np
def householder_qr(A):
A = np.array(A, dtype=float)
m, n = A.shape
V = np.zeros((m, n))
# tu código: para cada k, el reflector de A[k:, k] y su aplicación a A[k:, k:]
R = np.triu(A[:n])
return V, R
def apply_qt(V, b):
b = np.array(b, dtype=float)
# tu código
return banadir_fila(R, a): given (, upper triangular) from the QR of and a new row , return for matrix using Givens rotations without or . The returned must have nonnegative diagonal and work with entries of size .import numpy as np
def anadir_fila(R, a):
R = np.array(R, dtype=float)
w = np.array(a, dtype=float)
# tu código: para k = 0..n-1, una rotación entre la fila k de R y w que anule w[k]
return RSummary
- Errors in a chain of orthogonal transformations add instead of multiplying; Householder QR is therefore columnwise backward stable and its orthogonal to for any .
- CGS loses orthogonality as because its is essentially Cholesky of ; MGS as , and its is as good as Householder’s; CGS2 maintains if . For MGS least squares, factor .
- Householder in practice: destination (or Parlett’s formula), reflectors normalized with stored below the diagonal, in flops without forming , and flops total.
- With of , a new observation is incorporated using Givens rotations and about flops, updating the residual automatically; exponential forgetting gives rolling regressions. Row removal is more delicate.
- The least-squares problem has condition number ; QR and SVD achieve it, normal equations always pay and can lose information when forming . Column scaling reduces for free.
- With deficient rank, pivoted QR cheaply estimates rank (but can fail, as with Kahan’s matrix) and truncated SVD yields the minimum-norm solution. Data noise determines tolerance, not machine epsilon.