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

Linear least squares

ProblemFind minimising for an matrix : the best fit to an overdetermined system, or the minimum-norm solution of an underdetermined or rank-deficient one
Devised byAdrien-Marie Legendre (1805) and Carl Friedrich Gauss (1809), least squares and the normal equations; Gene Golub (1965), solution by Householder QR; Eliakim Moore (1920) and Roger Penrose (1955), the pseudoinverse; Golub and William Kahan (1965), solution by the SVD
AccuracyQR: backward stable, error (plus times the relative residual). Normal equations: error
CostQR: flops. Normal equations: . SVD: several times more
Read firstQR factorisation, Cholesky factorisation
APILeastSquaresSvd (least_squares), LeastSquaresResult; reference: least_squares (normal_equations, qr_least_squares)

Overview

When there are more equations than unknowns, as in fitting a model with a few parameters to many measurements, generally has no solution, and the least-squares solution minimises the sum of squared residuals instead. It is the maximum-likelihood estimate when the errors are independent and Gaussian, and the most widely used method of data fitting. When there are fewer equations than unknowns, or the columns of are dependent, there are infinitely many minimisers, and the natural choice is the one of smallest norm.

There are three standard methods, in increasing order of cost and robustness: the normal equations, QR factorisation, and the singular value decomposition. The first squares the condition number; the second does not; the third also handles rank deficiency gracefully.

Where it is used

Least squares is the standard answer when there are more equations than unknowns.

  • Data fitting. Straight lines and polynomials through measurements, calibration of sensors, estimating parameters of a model.
  • Navigation and GPS. A receiver solves an overdetermined set of range equations for position and clock bias.
  • Signal processing. Designing filters and estimating channels.
  • Machine learning. Linear regression is least squares; ridge regression adds a penalty.

History

Adrien-Marie Legendre published the method of least squares in 1805, and Carl Friedrich Gauss in 1809, claiming priority and justifying it by the normal distribution of errors. Both solved the normal equations by elimination, and for a century and a half this was the method, done by hand for the geodetic surveys of Europe. Gene Golub’s 1965 paper showed that Householder QR avoids forming and its squared condition number, and made QR the standard. Eliakim Moore (1920) and Roger Penrose (1955) defined the pseudoinverse, which gives the minimum-norm solution, and Golub and William Kahan (1965) showed how to compute it stably through the SVD.

The idea

The normal equations

The problem is to choose to minimise the length of the residual , where is with .

The geometry. As varies, ranges over all combinations of the columns of , the column space, an -dimensional subspace of . The vector generally lies outside it. The closest point of a subspace to an outside point is the foot of the perpendicular, so at the minimum the residual is perpendicular to the column space. That means it is perpendicular to every column of :

Rearranged, these are the normal equations (“normal” in the sense of perpendicular),

a square system. (The same equations follow from setting the gradient of to zero.)

An example. Fit a line to the three points , , . Each point gives one equation, :

Solving and gives and . The residuals are ; they sum to zero and are orthogonal to , as the normal equations require.

The catch. If the columns of are independent, is symmetric positive definite, and Cholesky solves the system cheaply. But the method has a numerical flaw: . Forming the product squares the condition number, so the solution loses twice as many digits as the problem itself requires. With , a careful method keeps ten digits and the normal equations keep four. For the squared condition number exceeds , and the computed may not even be positive definite.

QR factorisation

The QR factorisation solves the same problem without ever forming . The idea is to rotate the problem into coordinates in which it is trivial.

Write with of size (the thin QR), and let hold further orthonormal columns that complete to a full orthogonal matrix. Multiplying a vector by an orthogonal matrix does not change its length, so the residual can be measured in the new coordinates. Its components along the columns of are , and its components along the columns of are , because . Hence

The second term does not depend on at all: it is the part of that no choice of can reach. The first term can be made exactly zero, by solving the triangular system

by back substitution. That is the least-squares solution, and the minimum residual is . With Householder QR, is computed by applying the reflections to , and is never formed.

The error of this method is proportional to , not . (There is an additional term multiplied by the relative size of the residual. It is inherent in the least-squares problem and no method avoids it, but it is small when the fit is good.)

Fitting a polynomial of degree in the monomial basis, whose Vandermonde matrix becomes more ill-conditioned as grows, shows the difference:

Figure 7.4. Normal equations against QR.

The normal equations follow and fail outright (Cholesky finds indefinite) beyond degree 13; both QR methods follow . (Better still, fit in an orthogonal basis such as Chebyshev polynomials, whose matrix is well conditioned.)

Rank deficiency and the minimum-norm solution

So far the columns of were assumed independent. If they are not, so that has rank , there is some nonzero with , and adding any multiple of to a minimiser gives another minimiser with the same residual. The minimisers form a whole family, and a rule is needed to choose one. The standard rule is to take the minimiser of smallest norm.

The singular value decomposition makes this choice explicit. In the orthonormal bases given by the columns of and of , the matrix acts as a simple scaling: it maps to . To undo it, take the component of along each , divide by , and place the result along . The directions with cannot be undone; they are left out, which is exactly what makes the solution as short as possible:

The matrix defined by this formula is the pseudoinverse of .

Numerically, rank is a matter of degree. Rounding turns singular values that should be exactly zero into tiny nonzero numbers, and dividing by them would give a huge, meaningless solution. Singular values below a threshold, here , are therefore treated as zero.

The library’s least_squares combines the methods. It factorises with pivoted QR and, if the diagonal of shows full column rank, solves by back substitution. Otherwise, or when the system is underdetermined, it uses the SVD and returns the minimum-norm solution. It reports the numerical rank, the singular values and the residual sum of squares:

Table 7.5. Least squares on rank-deficient systems.

systemrank foundsolutionsingular values
full rank, 4 × 2: fit to 2(0.9000, 1.9000)(4.1000, 1.0908)
rank 1, 3 × 2: the second column is twice the first1(0.2000, 0.4000)(8.3666, 0.0000)
underdetermined, 1 × 3: 1(1.0000, 1.0000, 1.0000)(1.7321)

On the full-rank path, the singular values used to be computed as the square roots of the eigenvalues of , which reintroduces the squared condition number. For a matrix with singular values , and the smallest came out as . They now come from the SVD of .

Algorithm

least_squares(A, b), for an matrix :

  1. Overdetermined or square (). Factor by Householder QR with column pivoting, and apply the reflections to to get .
  2. Test the rank. The diagonal of decreases in magnitude. If every , the matrix has full column rank numerically: go to step 3. Otherwise go to step 4.
  3. Full rank. Solve the triangular system by back substitution and undo the column permutation, . The residual sum of squares is the squared norm of the remaining components , and the singular values reported are those of , from its SVD. Done.
  4. Rank deficient or underdetermined (, or the test failed). Compute the thin SVD . Count as the rank the singular values above . Return the minimum-norm solution .

The full-rank path costs one QR factorisation; the other costs one SVD, several times more.

Implementation

The normal equations (reference):

/// Solves the normal equations `AᵀA x = Aᵀb` with Cholesky: `L y = Aᵀb`, then `Lᵀ x = y`.
pub fn normal_equations(a: &Array2<f64>, b: &Array1<f64>) -> Result<Array1<f64>, Error> {
    let l = crate::cholesky::cholesky(&a.t().dot(a))?;
    let rhs = a.t().dot(b);
    let n = l.nrows();
    let mut y = Array1::zeros(n);
    for i in 0..n {
        y[i] = (rhs[i] - (0..i).map(|j| l[[i, j]] * y[j]).sum::<f64>()) / l[[i, i]];
    }
    back_substitute(&l.t().to_owned(), &y)
}

The production solver:

        if m >= n && n > 0 {
            let qr = qr::householder_pivoted(&a);
            let mut qtb = rhs.clone();
            qr.apply_adjoint(&mut qtb);
            let r00 = qr.r.at(0, 0).abs();
            let tolerance = r00 * f64::EPSILON * m.max(n) as f64;
            if r00 > 0.0 && (0..n).all(|i| qr.r.at(i, i).abs() > tolerance * 1e3) {
                // Full column rank: back-substitute R z = (Qᴴ b)[..n], then undo the pivoting.
                let mut z = qtb[..n].to_vec();
                for i in (0..n).rev() {
                    let s = (i + 1..n).fold(T::zero(), |s, k| s + qr.r.at(i, k) * z[k]);
                    z[i] = (z[i] - s) / qr.r.at(i, i);
                }
                let mut x = vec![T::zero(); n];
                for (j, &p) in qr.permutation.iter().enumerate() {
                    x[p] = z[j];
                }
                // The singular values of A are those of R. (Taking them as the square roots of
                // eig(RᴴR) squared the condition number: σ = 1e-10 next to σ = 1 came out 3.5e-9.)
                let singular_values = Array1::from_vec(svd::singular_values(&qr.upper())?);
                let residual = (m > n).then(|| qtb[n..].iter().map(|v| v.abs_sqr()).sum::<f64>());
                return Ok(LeastSquaresResult { solution: to_array1(x), singular_values, rank: n, residual_sum_of_squares: residual });
            }
        }
        let thin = svd::thin_svd(&a)?;
        let threshold = thin.sigma.first().copied().unwrap_or(0.0) * f64::EPSILON * m.max(n) as f64;
        let rank = thin.sigma.iter().filter(|&&s| s > threshold).count();
        // x = V Σ⁺ Uᴴ b over the numerically non-zero singular values.
        let mut x = vec![T::zero(); n];
        for j in 0..rank {
            let coefficient = (0..m).fold(T::zero(), |s, i| s + thin.u.at(i, j).conj() * rhs[i]).scale(1.0 / thin.sigma[j]);
            for (i, xi) in x.iter_mut().enumerate() {
                *xi += thin.v.at(i, j) * coefficient;
            }
        }
        let residual_sum_of_squares = (m > n && rank == n).then(|| {
            (0..m).map(|i| (rhs[i] - (0..n).fold(T::zero(), |s, j| s + a.at(i, j) * x[j])).abs_sqr()).sum::<f64>()
        });
        Ok(LeastSquaresResult { solution: to_array1(x), singular_values: Array1::from_vec(thin.sigma), rank, residual_sum_of_squares })
  • Works for real and complex matrices.
  • For weighted least squares, scale each row of and by the square root of its weight; for nonlinear models, see nonlinear least squares.

In practice

//! Linear least squares: normal equations, QR and the production solver.
//!
//! Run with `cargo run -p lib_jsl_linalg_reference --example linalg_least_squares`.

use lib_jsl_linalg::LeastSquaresSvd;
use lib_jsl_linalg_reference::least_squares::{normal_equations, qr_least_squares};
use ndarray::{Array1, Array2, array};

fn main() {
    // Fit y = c₀ + c₁ t + c₂ t² to noisy measurements.
    let t: Array1<f64> = Array1::linspace(0.0, 2.0, 9);
    let y = array![1.02, 1.29, 1.84, 2.47, 3.33, 4.24, 5.36, 6.61, 8.04];
    let a = Array2::from_shape_fn((9, 3), |(i, j)| t[i].powi(j as i32));

    let fit = a.least_squares(&y).unwrap();
    println!("coefficients {:.4}, rank {}, residual sum of squares {:.4}", fit.solution, fit.rank, fit.residual_sum_of_squares.unwrap());
    println!("condition number σ₁/σ₃ = {:.1}", fit.singular_values[0] / fit.singular_values[2]);
    println!("normal equations: {:.4}", normal_equations(&a, &y).unwrap());
    println!("reference QR:     {:.4}", qr_least_squares(&a, &y).unwrap());

    // A rank-deficient system has many minimisers; least_squares returns the one of least norm.
    let dependent = array![[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]];
    let r = dependent.least_squares(&array![2.0, 4.0, 6.0]).unwrap();
    println!("rank {}: minimum-norm solution {:.4}", r.rank, r.solution);
}

Strengths

  • Backward-stable QR for full-rank problems, the SVD for rank-deficient ones, chosen automatically.
  • Reports the rank and singular values, which diagnose ill-conditioning.

Weaknesses

  • Dense: very large or sparse problems need iterative methods (LSQR, conjugate gradients on the normal equations).
  • The rank threshold is a judgement: noisy data may need a larger threshold (truncated SVD) or regularisation.

Exercises

  1. Derive the normal equations by setting the gradient of to zero.
  2. Show that using the SVD.
  3. Show that the minimum-norm solution is orthogonal to the null space of .
  4. Fit a degree-15 polynomial on in the monomial and in the Chebyshev basis, and compare the condition numbers and the errors.
  5. Add Tikhonov regularisation, , by augmenting with , and study the effect of on an ill-conditioned fit.
Hints and answers
  1. gives .
  2. With , , whose singular values are , so .
  3. Any solution is with in the null space. The minimum-norm solution has no component in the null space, i.e. it lies in its orthogonal complement, the row space of .
  4. The monomial Vandermonde matrix on with degree 15 has a condition number far above (and many digits are lost); the Chebyshev basis on the same interval has a condition number of order 10, and the fit is accurate to nearly rounding level.
  5. The least-squares solution of minimises . Plot the residual norm against the solution norm as varies (the L-curve).

Further reading

  • G. H. Golub, “Numerical methods for solving linear least squares problems”, Numerische Mathematik 7 (1965) 206–216.
  • Å. Björck, Numerical Methods for Least Squares Problems, SIAM, 1996.
  • C. L. Lawson and R. J. Hanson, Solving Least Squares Problems, Prentice-Hall, 1974 (SIAM reprint, 1995).
  • L. N. Trefethen and D. Bau, Numerical Linear Algebra, SIAM, 1997, lectures 11, 18 and 19.