Skip to main content

lib_jsl_linalg_reference/
least_squares.rs

1//! Linear least squares, `min ‖A x − b‖₂` for a tall `A`, two ways.
2//!
3//! The **normal equations** `AᵀA x = Aᵀb` come straight from setting the gradient to zero and are
4//! solved cheaply with Cholesky, but forming `AᵀA` squares the condition number. **QR** writes
5//! `A = Q R`, so `‖A x − b‖ = ‖R x − Qᵀb‖` in the column space, and solves the triangular system
6//! `R x = Qᵀb` directly, with error proportional to `κ(A)` rather than `κ(A)²`.
7//!
8//! See the book entry [Linear least squares](https://jwkunz.github.io/lib_jsl/book/linear_algebra/least-squares.html).
9
10use crate::Error;
11use crate::gaussian_elimination::back_substitute;
12use ndarray::{Array1, Array2};
13
14// ANCHOR: normal_equations
15/// Solves the normal equations `AᵀA x = Aᵀb` with Cholesky: `L y = Aᵀb`, then `Lᵀ x = y`.
16pub fn normal_equations(a: &Array2<f64>, b: &Array1<f64>) -> Result<Array1<f64>, Error> {
17    let l = crate::cholesky::cholesky(&a.t().dot(a))?;
18    let rhs = a.t().dot(b);
19    let n = l.nrows();
20    let mut y = Array1::zeros(n);
21    for i in 0..n {
22        y[i] = (rhs[i] - (0..i).map(|j| l[[i, j]] * y[j]).sum::<f64>()) / l[[i, i]];
23    }
24    back_substitute(&l.t().to_owned(), &y)
25}
26// ANCHOR_END: normal_equations
27
28/// Solves `R x = Qᵀb` with the Householder QR factorisation.
29pub fn qr_least_squares(a: &Array2<f64>, b: &Array1<f64>) -> Result<Array1<f64>, Error> {
30    let (q, r) = crate::qr::householder(a);
31    back_substitute(&r, &q.t().dot(b))
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn qr_survives_an_ill_conditioned_polynomial_fit() {
40        // Fit a degree-11 polynomial with all coefficients one on 40 points in [0, 1];
41        // the Vandermonde matrix has condition number ≈ 10⁸.
42        let a = Array2::from_shape_fn((40, 12), |(i, j)| (i as f64 / 39.0).powi(j as i32));
43        let exact = Array1::from_elem(12, 1.0);
44        let b = a.dot(&exact);
45        let error = |x: &Array1<f64>| (x - &exact).iter().fold(0.0f64, |m, d| m.max(d.abs()));
46        let qr = error(&qr_least_squares(&a, &b).unwrap());
47        assert!(qr < 1e-6, "QR error {qr:e}");
48        // Cholesky may fail outright (rounding makes AᵀA numerically indefinite), an even clearer
49        // failure; when it succeeds, the answer is far less accurate.
50        if let Ok(x) = normal_equations(&a, &b) {
51            assert!(error(&x) > 1e3 * qr, "normal equations error {:e} vs QR {qr:e}", error(&x));
52        }
53    }
54
55    #[test]
56    fn both_agree_on_a_well_conditioned_problem() {
57        let a = crate::random_matrix(30, 5, 12);
58        let b = Array1::from_iter((0..30).map(|i| (i as f64 * 0.3).cos()));
59        let (x1, x2) = (normal_equations(&a, &b).unwrap(), qr_least_squares(&a, &b).unwrap());
60        assert!((&x1 - &x2).iter().all(|d| d.abs() < 1e-12));
61    }
62}