Skip to main content

lib_jsl_machine_learning/supervised/regression/
general_least_squares.rs

1//! Weighted and generalised least squares.
2//!
3//! See the book entry [Linear regression](https://jwkunz.github.io/lib_jsl/book/machine_learning/linear-regression.html#weighted-and-generalised-least-squares).
4
5use super::least_squares::with_ones;
6use crate::common::{Regressor, check_xy};
7use lib_jsl_core::{ErrorsJSL, R1D, R2D, VR1D, VR2D};
8use ndarray::Array1;
9use lib_jsl_linalg::{Cholesky, LeastSquaresSvd, SolveTriangular, UPLO};
10
11/// Least squares with a known error structure: minimise `(y - Xw)ᵀ Σ⁻¹ (y - Xw)` where `Σ` is the
12/// covariance of the errors (generalised least squares), or the special case of independent errors
13/// with per-sample weights (weighted least squares, `Σ = diag(1/weight)`). This is the best linear
14/// unbiased estimator when `Σ` is right: noisy or correlated samples count for less.
15///
16/// Implemented by whitening: factor `Σ = L Lᵀ` and solve the ordinary problem for `L⁻¹ y ~ L⁻¹ X`.
17#[derive(Debug, Clone)]
18pub struct GeneralLeastSquares {
19    covariance: Option<R2D>,
20    weights_per_sample: Option<R1D>,
21    fit_intercept: bool,
22    coef: R1D,
23    intercept: f64,
24    fitted: bool,
25}
26
27impl GeneralLeastSquares {
28    /// Errors with the full covariance matrix `Σ` (symmetric positive definite, `n × n`).
29    pub fn with_covariance(covariance: R2D) -> Self {
30        GeneralLeastSquares { covariance: Some(covariance), weights_per_sample: None, fit_intercept: true, coef: R1D::zeros(0), intercept: 0.0, fitted: false }
31    }
32
33    /// Independent errors with the given positive per-sample weights (inverse variances).
34    pub fn with_sample_weights(weights: R1D) -> Self {
35        GeneralLeastSquares { covariance: None, weights_per_sample: Some(weights), fit_intercept: true, coef: R1D::zeros(0), intercept: 0.0, fitted: false }
36    }
37
38    pub fn with_intercept(mut self, fit_intercept: bool) -> Self {
39        self.fit_intercept = fit_intercept;
40        self
41    }
42
43    pub fn weights(&self) -> &R1D {
44        &self.coef
45    }
46
47    pub fn intercept(&self) -> f64 {
48        self.intercept
49    }
50}
51
52impl Regressor for GeneralLeastSquares {
53    fn fit(&mut self, x: VR2D, y: VR1D) -> Result<(), ErrorsJSL> {
54        check_xy(x, y.len())?;
55        let n = x.nrows();
56        let design = if self.fit_intercept { with_ones(x) } else { x.to_owned() };
57        // ANCHOR: whitening
58        let (wd, wy): (R2D, R1D) = if let Some(cov) = &self.covariance {
59            if cov.dim() != (n, n) {
60                return Err(ErrorsJSL::IncompatibleArraySizes((cov.nrows(), n)));
61            }
62            let l = cov.cholesky(UPLO::Lower).map_err(|_| ErrorsJSL::InvalidInputRange("The covariance must be symmetric positive definite."))?;
63            let wd = l.solve_triangular(UPLO::Lower, lib_jsl_linalg::Diag::NonUnit, &design).map_err(|_| ErrorsJSL::RuntimeError("Whitening failed."))?;
64            let wy = l.solve_triangular(UPLO::Lower, lib_jsl_linalg::Diag::NonUnit, &y.to_owned()).map_err(|_| ErrorsJSL::RuntimeError("Whitening failed."))?;
65            (wd, wy)
66        } else {
67            let w = self.weights_per_sample.as_ref().ok_or(ErrorsJSL::Misconfiguration("No error model was given."))?;
68            if w.len() != n {
69                return Err(ErrorsJSL::IncompatibleArraySizes((w.len(), n)));
70            }
71            if w.iter().any(|&v| !v.is_finite() || v <= 0.0) {
72                return Err(ErrorsJSL::InvalidInputRange("Sample weights must be positive and finite."));
73            }
74            let s: Array1<f64> = w.mapv(f64::sqrt);
75            (R2D::from_shape_fn(design.dim(), |(i, j)| design[[i, j]] * s[i]), R1D::from_iter(y.iter().zip(&s).map(|(a, b)| a * b)))
76        };
77        // ANCHOR_END: whitening
78        let sol = wd.least_squares(&wy).map_err(|_| ErrorsJSL::RuntimeError("The least-squares solve failed."))?.solution;
79        if self.fit_intercept {
80            self.intercept = sol[sol.len() - 1];
81            self.coef = sol.slice(ndarray::s![..sol.len() - 1]).to_owned();
82        } else {
83            self.intercept = 0.0;
84            self.coef = sol;
85        }
86        self.fitted = true;
87        Ok(())
88    }
89
90    fn predict(&self, x: VR2D) -> Result<R1D, ErrorsJSL> {
91        if !self.fitted {
92            return Err(ErrorsJSL::Misconfiguration("The model has not been fitted."));
93        }
94        if x.ncols() != self.coef.len() {
95            return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.coef.len())));
96        }
97        Ok(x.dot(&self.coef) + self.intercept)
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use crate::common::MlRng;
105    use ndarray::{Array2, arr1, arr2};
106
107    #[test]
108    fn heteroscedastic_weights_beat_plain_least_squares() {
109        // y = 2x + 1 with a few wildly noisy points that get tiny weights.
110        let mut rng = MlRng::new(4);
111        let n = 60;
112        let x = Array2::from_shape_fn((n, 1), |(i, _)| i as f64 / 10.0);
113        let noisy: Vec<bool> = (0..n).map(|i| i % 6 == 0).collect();
114        let y = R1D::from_iter((0..n).map(|i| 2.0 * x[[i, 0]] + 1.0 + rng.gaussian(0.0, if noisy[i] { 8.0 } else { 0.05 })));
115        let w = R1D::from_iter(noisy.iter().map(|&b| if b { 1.0 / 64.0 } else { 1.0 / 0.0025 }));
116        let mut wls = GeneralLeastSquares::with_sample_weights(w);
117        wls.fit(x.view(), y.view()).unwrap();
118        let mut ols = super::super::least_squares::LinearRegression::new();
119        ols.fit(x.view(), y.view()).unwrap();
120        let err = |slope: f64, b: f64| (slope - 2.0).abs() + (b - 1.0).abs();
121        assert!(err(wls.weights()[0], wls.intercept()) < 0.05, "{:?} {}", wls.weights(), wls.intercept());
122        assert!(err(wls.weights()[0], wls.intercept()) < err(ols.weights()[0], ols.intercept()));
123    }
124
125    #[test]
126    fn full_covariance_matches_weights_when_diagonal() {
127        let x = arr2(&[[1.0], [2.0], [3.0], [4.0]]);
128        let y = arr1(&[1.1, 2.3, 2.8, 4.4]);
129        let var = [1.0, 4.0, 0.25, 2.0];
130        let mut gls = GeneralLeastSquares::with_covariance(Array2::from_diag(&arr1(&var)));
131        gls.fit(x.view(), y.view()).unwrap();
132        let mut wls = GeneralLeastSquares::with_sample_weights(arr1(&var).mapv(|v| 1.0 / v));
133        wls.fit(x.view(), y.view()).unwrap();
134        assert!((gls.weights()[0] - wls.weights()[0]).abs() < 1e-10 && (gls.intercept() - wls.intercept()).abs() < 1e-10);
135        assert!(gls.predict(x.view()).unwrap().len() == 4);
136    }
137
138    #[test]
139    fn identity_covariance_is_ordinary_least_squares_and_errors() {
140        let x = arr2(&[[1.0], [2.0], [3.0]]);
141        let y = arr1(&[3.0, 5.0, 7.0]);
142        let mut g = GeneralLeastSquares::with_covariance(Array2::eye(3));
143        g.fit(x.view(), y.view()).unwrap();
144        assert!((g.weights()[0] - 2.0).abs() < 1e-10 && (g.intercept() - 1.0).abs() < 1e-10);
145        let mut bad_shape = GeneralLeastSquares::with_covariance(Array2::eye(2));
146        assert!(bad_shape.fit(x.view(), y.view()).is_err());
147        let mut not_pd = GeneralLeastSquares::with_covariance(arr2(&[[1.0, 2.0, 0.0], [2.0, 1.0, 0.0], [0.0, 0.0, 1.0]]));
148        assert!(not_pd.fit(x.view(), y.view()).is_err());
149        let mut bad_w = GeneralLeastSquares::with_sample_weights(arr1(&[1.0, 0.0, 1.0]));
150        assert!(bad_w.fit(x.view(), y.view()).is_err());
151        assert!(GeneralLeastSquares::with_sample_weights(arr1(&[1.0])).predict(x.view()).is_err());
152    }
153}