Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

QR factorisation

ProblemFactor an matrix () as , with having orthonormal columns and upper triangular; with column pivoting, reveals the numerical rank
Devised byOrthogonalisation: Pierre-Simon Laplace (1812), Jørgen Pedersen Gram (1883), Erhard Schmidt (1907); reflections: Alston Householder (1958); rotations: Wallace Givens (1958); column pivoting: Peter Businger and Gene Golub (1965); the stability of modified Gram-Schmidt: Åke Björck (1967)
AccuracyHouseholder: orthogonal to machine precision, backward stable. Modified Gram-Schmidt: loss of orthogonality . Classical Gram-Schmidt:
Cost flops for Householder ( for Gram-Schmidt)
Read firstGaussian elimination and LU factorisation
APIProduction: used inside LeastSquaresSvd and the SVD (crate-internal). Reference: qr (classical_gram_schmidt, modified_gram_schmidt, householder, orthogonality_error)

Overview

The QR factorisation writes a matrix as an orthogonal factor times a triangular one. Its columns of are an orthonormal basis for the column space of , built so that the first columns of span the first columns of . It is the tool of choice for linear least squares, the first step of the SVD and of eigenvalue algorithms, and the core of the QR algorithm for eigenvalues.

Orthogonal matrices are the perfectly conditioned transformations: they preserve lengths, so they never amplify errors. That is the source of QR’s stability, but only if the computed really is orthogonal. The three classical algorithms differ precisely there: the Gram-Schmidt process orthogonalises the columns one by one and, in floating point, gradually loses orthogonality; Householder reflections build as a product of exactly orthogonal matrices and keep it.

Where it is used

QR factorisation is the numerically stable way to solve least-squares problems.

  • Regression and calibration. Fitting a model to data without squaring the condition number as the normal equations do.
  • Signal processing. Recursive least squares and adaptive filtering algorithms use QR updates.
  • Eigenvalue computation. The QR algorithm repeats this factorisation to find eigenvalues.
  • Orthogonal bases. Gram-Schmidt in disguise: orthonormalising a set of vectors.

History

The orthogonalisation of a set of functions or vectors appears in Laplace’s work on least squares (1812); Jørgen Pedersen Gram (1883) used it for series expansions, and Erhard Schmidt (1907) stated the process for functions in his work on integral equations. For computation, Alston Householder (1958) introduced the reflections that bear his name and showed how to triangularise a matrix with them, and Wallace Givens (1958) used plane rotations. Gene Golub (1965) made Householder QR the standard method for least squares, and with Peter Businger added column pivoting to reveal rank. Åke Björck (1967) showed that the modified Gram-Schmidt process, though it loses orthogonality, gives accurate least-squares solutions. Robert Schreiber and Charles Van Loan (1989) devised the compact WY representation that lets reflections be applied in blocks, at matrix-multiply speed.

The idea

Gram-Schmidt orthogonalisation

Let be an matrix with and columns . We want orthonormal vectors (mutually perpendicular, each of length 1) such that span the same space as for every .

The Gram-Schmidt process builds them one at a time.

  • Normalise the first column: .
  • From the second column remove its component along , which is . What is left, , is perpendicular to . Normalise it to get .
  • From the third column remove its components along both and , normalise, and so on.

In symbols, for each column :

Why this is a factorisation. Rearranging the middle formula, : each column of is a combination of the first columns of with coefficients . That is precisely the statement , where has the as columns and is the upper triangular matrix of the .

Classical and modified. The formulas above are classical Gram-Schmidt: every coefficient is computed from the original column . Modified Gram-Schmidt subtracts the components one at a time and computes each coefficient from the vector as it currently stands: start with , and for set and .

In exact arithmetic the two give identical results, since the are orthogonal and removing one component does not change the others. In floating point they differ. The computed are only approximately orthogonal, and when a column is nearly a combination of the previous ones, is a small difference of large vectors and its direction is contaminated by rounding errors. The modified version projects out each direction from a vector that has already had its earlier errors partly removed, so the errors do not compound as badly. The computed departs from orthogonality by about for classical Gram-Schmidt and for modified, where is the condition number of . Reorthogonalising (running the process twice) restores orthogonality.

Householder reflections

Gram-Schmidt makes by operating on with triangular transformations, and orthogonality is the hoped-for result. Householder’s method does the reverse: it operates on with orthogonal transformations until it is triangular, so orthogonality is guaranteed by construction.

The reflection. For a unit vector , the matrix

is a Householder reflection. Applied to a vector, : it subtracts twice the component of along , which reverses that component and leaves the rest alone. Geometrically, reflects in the plane (hyperplane) perpendicular to . It is symmetric, and it is orthogonal, since reflecting twice restores the original: .

Zeroing a column. A reflection preserves length, so it can map a given vector onto any vector of the same length. We want it mapped onto a multiple of the first unit vector , so that all its entries but the first become zero; the target must be . A reflection that takes to has its mirror perpendicular to , so

Of the two possible signs of the target, this one is chosen so that the first component of is plus a number of the same sign. With the other choice it would be a difference of two nearly equal numbers whenever is already close to a multiple of , and would lose accuracy to cancellation.

The factorisation. Apply a reflection that zeroes the first column of below the diagonal. Then apply , built from the part of the second column on and below the diagonal, which zeroes that column below the diagonal without disturbing the first row or column. After such steps,

Two practical points. A reflection is never formed as a matrix; it is applied to each column by the formula , at the cost of a dot product and a vector update. And is usually not formed either, but kept as the list of vectors , from which or can be computed whenever needed.

Because every factor is orthogonal to working precision, so is the product: the computed is orthogonal to about regardless of the conditioning of .

Figure 7.3. Loss of orthogonality.

The figure shows the three methods on matrices with singular values spread between 1 and . Classical Gram-Schmidt has lost all orthogonality by , modified Gram-Schmidt follows , and Householder stays at the level of rounding throughout. All three reproduce to rounding error: the difference is entirely in .

Column pivoting

Plain QR processes the columns in the order given. If some columns are (nearly) combinations of others, so that has fewer than independent columns, that fact is hidden somewhere inside . QR with column pivoting brings it into the open. At each step it swaps the remaining column of largest norm into the current position, giving with a permutation.

The effect is that the most independent columns are processed first. The diagonal of then decreases in magnitude, , and each measures how much of column is new, that is, not already explained by the columns before it. A sharp drop reveals the numerical rank: if is close to a matrix of rank , then is small.

Recomputing the norms of all remaining columns at every step would double the cost. Instead they are downdated: after a reflection, the squared norm of what remains of a column is its previous value minus the square of the entry just fixed in . The subtraction can cancel, so the norm is recomputed from scratch when the downdated value becomes unreliable (the safeguard used in LAPACK’s geqp3). The production library uses pivoted QR for least squares and to precondition the Jacobi SVD.

Algorithm

Householder QR. Input: an matrix with . For :

  1. Form the reflector. Take , the part of column from row to row . Set and normalise it. (If is zero, skip the step.)
  2. Apply it to each column : replace the part of that column in rows to by . Column becomes on the diagonal and zero below.
  3. Store as .

At the end the upper triangle of the array is . To apply to a vector, apply the reflections in the order ; to apply , in the order . To form the thin explicitly, apply to the first columns of the identity. The factorisation costs about flops.

With column pivoting. Compute the squared norm of every column at the start. Before step :

  1. find the remaining column of largest (downdated) norm, swap it with column , and record the swap in the permutation;
  2. after applying the reflection, subtract from the squared norm of each remaining column ; if the result has lost most of its digits to cancellation, recompute that norm from the column itself.

Implementation

Modified Gram-Schmidt (reference):

/// Modified Gram-Schmidt: `r_ij = q_i · v` with the column `v` as orthogonalised so far.
pub fn modified_gram_schmidt(a: &Array2<f64>) -> (Array2<f64>, Array2<f64>) {
    let (m, n) = a.dim();
    let mut q = Array2::zeros((m, n));
    let mut r = Array2::zeros((n, n));
    for j in 0..n {
        let mut v = a.column(j).to_owned();
        for i in 0..j {
            r[[i, j]] = q.column(i).dot(&v);
            v.scaled_add(-r[[i, j]], &q.column(i));
        }
        r[[j, j]] = v.dot(&v).sqrt();
        q.column_mut(j).assign(&(v / r[[j, j]]));
    }
    (q, r)
}

Householder QR (reference):

/// Householder QR. Reflection `k` maps column `k` (from row `k` down) onto a multiple of `e_1`;
/// `Q` is then accumulated by applying the reflections to the first `n` columns of the identity.
pub fn householder(a: &Array2<f64>) -> (Array2<f64>, Array2<f64>) {
    let (m, n) = a.dim();
    let mut r = a.clone();
    let mut reflectors: Vec<Array1<f64>> = Vec::with_capacity(n);
    for k in 0..n {
        let mut v = r.slice(s![k.., k]).to_owned();
        let norm = v.dot(&v).sqrt();
        // Reflect onto −sign(x₀)‖x‖ e₁ so that v₀ = x₀ + sign(x₀)‖x‖ involves no cancellation.
        v[0] += if v[0] >= 0.0 { norm } else { -norm };
        let v_norm = v.dot(&v).sqrt();
        if v_norm > 0.0 {
            v /= v_norm;
        }
        apply_reflector(&mut r, &v, k);
        reflectors.push(v);
    }
    let mut q = Array2::from_shape_fn((m, n), |(i, j)| if i == j { 1.0 } else { 0.0 });
    for (k, v) in reflectors.iter().enumerate().rev() {
        apply_reflector(&mut q, v, k);
    }
    let r = Array2::from_shape_fn((n, n), |(i, j)| if j >= i { r[[i, j]] } else { 0.0 });
    (q, r)
}

Pivoted Householder QR (production), for real and complex matrices:

/// Factorises `A P = Q R`, choosing at each step the remaining column of largest norm. Column
/// norms are downdated rather than recomputed, with a recomputation when cancellation would make
/// the downdated value unreliable (the safeguard of LAPACK's `geqp3`).
///
/// This is the unblocked form: every reflector updates the whole trailing matrix, two passes over
/// memory per column. [`householder_pivoted`] gives the same factorisation with most of the work
/// in matrix multiplications.
pub(crate) fn householder_pivoted_unblocked<T: Scalar>(a: &Mat<T>) -> Householder<T> {
    let (m, n) = (a.rows, a.cols);
    let mut r = a.clone();
    let mut permutation: Vec<usize> = (0..n).collect();
    let mut reflectors = Vec::with_capacity(n);
    let mut norms2 = vec![0.0f64; n];
    for row in r.data.chunks_exact(n.max(1)) {
        for (s, v) in norms2.iter_mut().zip(row) {
            *s += v.abs_sqr();
        }
    }
    let mut reference = norms2.clone();
    let mut w = vec![T::zero(); n];
    let recompute_below = f64::EPSILON.sqrt();
    for k in 0..n.min(m) {
        let p = (k..n).fold(k, |best, j| if norms2[j] > norms2[best] { j } else { best });
        if p != k {
            for row in r.data.chunks_exact_mut(n) {
                row.swap(k, p);
            }
            permutation.swap(k, p);
            norms2.swap(k, p);
            reference.swap(k, p);
        }
        let norm = (k..m).map(|i| r.data[i * n + k].abs_sqr()).sum::<f64>().sqrt();
        if norm == 0.0 {
            break;
        }
        let x0 = r.at(k, k);
        let phase = if x0.abs() > 0.0 { x0.scale(1.0 / x0.abs()) } else { T::one() };
        let alpha = phase.scale(-norm);
        // v = x − α e₁, normalised.
        let mut v: Vec<T> = (k..m).map(|i| r.at(i, k)).collect();
        v[0] -= alpha;
        let vnorm = v.iter().map(|z| z.abs_sqr()).sum::<f64>().sqrt();
        if vnorm == 0.0 {
            reflectors.push(Vec::new());
            continue;
        }
        v.iter_mut().for_each(|z| *z = z.scale(1.0 / vnorm));
        // R ← (I − 2vvᴴ) R on rows k.., columns k.., row by row for contiguous access.
        let w = &mut w[k..n];
        w.fill(T::zero());
        for (ii, &vi) in v.iter().enumerate() {
            axpy_sub(w, -vi.conj(), &r.data[(k + ii) * n + k..(k + ii + 1) * n]);
        }
        for (ii, &vi) in v.iter().enumerate() {
            axpy_sub(&mut r.data[(k + ii) * n + k..(k + ii + 1) * n], vi.scale(2.0), w);
        }
        reflectors.push(v);
        for j in k + 1..n {
            norms2[j] -= r.data[k * n + j].abs_sqr();
            if norms2[j] <= recompute_below * reference[j] {
                norms2[j] = (k + 1..m).map(|i| r.data[i * n + j].abs_sqr()).sum();
                reference[j] = norms2[j];
            }
        }
    }
    Householder { r, permutation, reflectors }
}
  • For complex matrices the reflection maps onto , where is the phase of .
  • When an explicit orthogonal factor is needed (in the SVD and both eigensolvers), the library accumulates blocks of reflections in the compact WY form and applies each block with three matrix multiplications.
  • The production QR is not exposed directly; least squares and the SVD use it.

In practice

//! QR factorisation: Gram-Schmidt against Householder reflections.
//!
//! Run with `cargo run -p lib_jsl_linalg_reference --example linalg_qr`.

use lib_jsl_linalg_reference::qr::{classical_gram_schmidt, householder, modified_gram_schmidt, orthogonality_error};
use ndarray::Array2;

fn main() {
    // The columns of a Vandermonde matrix in [0, 1] are nearly parallel: κ ≈ 10⁹ for degree 9.
    let a = Array2::from_shape_fn((30, 10), |(i, j)| (i as f64 / 29.0).powi(j as i32));
    for (name, (q, r)) in [
        ("classical Gram-Schmidt", classical_gram_schmidt(&a)),
        ("modified Gram-Schmidt", modified_gram_schmidt(&a)),
        ("Householder", householder(&a)),
    ] {
        let residual = (q.dot(&r) - &a).iter().fold(0.0f64, |m, v| m.max(v.abs()));
        println!("{name:>24}: ‖QᵀQ − I‖ = {:.1e}, max |QR − A| = {residual:.1e}", orthogonality_error(&q));
    }
    // All three reproduce A = QR to rounding error; only Householder keeps Q orthogonal.
}

Strengths

  • Householder QR is backward stable and keeps orthogonal for any conditioning.
  • Column pivoting reveals numerical rank cheaply.

Weaknesses

  • Twice the cost of LU for square matrices.
  • Gram-Schmidt needs reorthogonalisation to be reliable (but is the natural choice when columns arrive one at a time, as in Krylov methods).

Exercises

  1. Show that with is symmetric, orthogonal and an involution ().
  2. Show that classical and modified Gram-Schmidt compute the same and in exact arithmetic.
  3. Apply classical Gram-Schmidt to with below rounding (Läuchli’s matrix) and compute by hand.
  4. Run classical Gram-Schmidt twice (“twice is enough”) and measure the loss of orthogonality as in the figure.
  5. Show that column pivoting gives .
Hints and answers
  1. , and . Symmetry plus orthogonality gives .
  2. Both subtract from the projections onto . Classical Gram-Schmidt computes all the coefficients from the original , modified from the partially reduced vector, but when the are orthogonal, and (reduced vector) are equal.
  3. Below rounding, and . Then , so , and similarly . Then : orthogonality is completely lost.
  4. A second pass orthogonalises the result against the again; Kahan and Parlett showed that two passes give orthogonality at the level of rounding error.
  5. At step pivoting chooses the remaining column of largest norm (after projecting out the first directions), and is that norm. Projecting out one more direction cannot increase any remaining column’s norm, so the next pivot is no larger.

Further reading

  • A. S. Householder, “Unitary triangularization of a nonsymmetric matrix”, Journal of the ACM 5 (1958) 339–342.
  • Å. Björck, “Solving linear least squares problems by Gram-Schmidt orthogonalization”, BIT 7 (1967) 1–21.
  • R. Schreiber and C. Van Loan, “A storage-efficient WY representation for products of Householder transformations”, SIAM Journal on Scientific and Statistical Computing 10 (1989) 53–57.
  • L. N. Trefethen and D. Bau, Numerical Linear Algebra, SIAM, 1997, lectures 7–10 and 16.
  • G. H. Golub and C. F. Van Loan, Matrix Computations, 4th ed., Johns Hopkins University Press, 2013, chapter 5.