Skip to main content

lib_jsl_machine_learning/supervised/regression/
least_squares.rs

1//! Ordinary least squares linear regression.
2//!
3//! See the book entry [Linear regression](https://jwkunz.github.io/lib_jsl/book/machine_learning/linear-regression.html#least-squares).
4
5use crate::common::{Regressor, check_xy};
6use lib_jsl_core::{ErrorsJSL, R1D, R2D, VR1D, VR2D};
7use ndarray::{Array1, Array2, Axis};
8use lib_jsl_linalg::LeastSquaresSvd;
9
10/// `y ≈ X w + b`, fitted by minimum-norm least squares through the SVD, so rank-deficient designs
11/// (collinear features, more features than samples) are handled gracefully.
12#[derive(Debug, Clone)]
13pub struct LinearRegression {
14    fit_intercept: bool,
15    weights: R1D,
16    intercept: f64,
17    fitted: bool,
18}
19
20impl LinearRegression {
21    /// A model that fits an intercept.
22    pub fn new() -> Self {
23        LinearRegression { fit_intercept: true, weights: R1D::zeros(0), intercept: 0.0, fitted: false }
24    }
25
26    /// Sets whether an intercept is fitted (`false` forces the plane through the origin).
27    pub fn with_intercept(mut self, fit_intercept: bool) -> Self {
28        self.fit_intercept = fit_intercept;
29        self
30    }
31
32    pub fn weights(&self) -> &R1D {
33        &self.weights
34    }
35
36    pub fn intercept(&self) -> f64 {
37        self.intercept
38    }
39}
40
41impl Default for LinearRegression {
42    fn default() -> Self {
43        Self::new()
44    }
45}
46
47/// Appends a column of ones.
48pub(crate) fn with_ones(x: VR2D) -> R2D {
49    let mut out = Array2::ones((x.nrows(), x.ncols() + 1));
50    out.slice_mut(ndarray::s![.., ..x.ncols()]).assign(&x);
51    out
52}
53
54impl Regressor for LinearRegression {
55    // ANCHOR: ols_fit
56    fn fit(&mut self, x: VR2D, y: VR1D) -> Result<(), ErrorsJSL> {
57        check_xy(x, y.len())?;
58        let design = if self.fit_intercept { with_ones(x) } else { x.to_owned() };
59        let sol = design.least_squares(&y.to_owned()).map_err(|_| ErrorsJSL::RuntimeError("The least-squares solve failed."))?;
60        let coef: Array1<f64> = sol.solution;
61        if self.fit_intercept {
62            self.intercept = coef[coef.len() - 1];
63            self.weights = coef.slice(ndarray::s![..coef.len() - 1]).to_owned();
64        } else {
65            self.intercept = 0.0;
66            self.weights = coef;
67        }
68        self.fitted = true;
69        Ok(())
70    }
71    // ANCHOR_END: ols_fit
72
73    fn predict(&self, x: VR2D) -> Result<R1D, ErrorsJSL> {
74        if !self.fitted {
75            return Err(ErrorsJSL::Misconfiguration("The model has not been fitted."));
76        }
77        if x.ncols() != self.weights.len() {
78            return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.weights.len())));
79        }
80        Ok(x.dot(&self.weights) + self.intercept)
81    }
82}
83
84/// Column means of a matrix.
85pub(crate) fn column_means(x: VR2D) -> R1D {
86    x.mean_axis(Axis(0)).unwrap_or_else(|| R1D::zeros(x.ncols()))
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92    use crate::datasets::{make_regression, make_sine};
93    use crate::metrics::r2_score;
94    use crate::preprocessing::polynomial_features;
95    use ndarray::{arr1, arr2};
96
97    #[test]
98    fn recovers_the_true_model() {
99        let (x, y, w, b) = make_regression(300, 4, 0.01, 2);
100        let mut m = LinearRegression::new();
101        m.fit(x.view(), y.view()).unwrap();
102        for (got, want) in m.weights().iter().zip(w.iter()) {
103            assert!((got - want).abs() < 0.01);
104        }
105        assert!((m.intercept() - b).abs() < 0.01);
106        assert!(r2_score(y.view(), m.predict(x.view()).unwrap().view()).unwrap() > 0.999);
107    }
108
109    #[test]
110    fn intercept_options_collinearity_and_polynomials() {
111        let x = arr2(&[[1.0], [2.0], [3.0]]);
112        let y = arr1(&[3.0, 5.0, 7.0]);
113        let mut with = LinearRegression::new();
114        with.fit(x.view(), y.view()).unwrap();
115        assert!((with.weights()[0] - 2.0).abs() < 1e-10 && (with.intercept() - 1.0).abs() < 1e-10);
116        let mut without = LinearRegression::new().with_intercept(false);
117        without.fit(x.view(), y.view()).unwrap();
118        assert_eq!(without.intercept(), 0.0);
119        // Perfectly collinear columns still give a fit (minimum-norm weights).
120        let dup = arr2(&[[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]);
121        let mut c = LinearRegression::new();
122        c.fit(dup.view(), y.view()).unwrap();
123        assert!(c.predict(dup.view()).unwrap().iter().zip(y.iter()).all(|(a, b)| (a - b).abs() < 1e-9));
124        // A cubic polynomial fit to a sine wave beats a straight line.
125        let (sx, sy) = make_sine(200, 0.05, 3);
126        let mut line = LinearRegression::new();
127        line.fit(sx.view(), sy.view()).unwrap();
128        let px = polynomial_features(sx.view(), 5).unwrap();
129        let mut poly = LinearRegression::new();
130        poly.fit(px.view(), sy.view()).unwrap();
131        let (r_line, r_poly) = (r2_score(sy.view(), line.predict(sx.view()).unwrap().view()).unwrap(), r2_score(sy.view(), poly.predict(px.view()).unwrap().view()).unwrap());
132        assert!(r_poly > 0.95 && r_line < 0.7, "{r_line} {r_poly}");
133    }
134
135    #[test]
136    fn errors() {
137        let mut m = LinearRegression::new();
138        assert!(m.predict(arr2(&[[1.0]]).view()).is_err());
139        assert!(m.fit(arr2(&[[1.0], [2.0]]).view(), arr1(&[1.0]).view()).is_err());
140        assert!(m.fit(arr2(&[[f64::NAN]]).view(), arr1(&[1.0]).view()).is_err());
141        m.fit(arr2(&[[1.0], [2.0]]).view(), arr1(&[1.0, 2.0]).view()).unwrap();
142        assert!(m.predict(arr2(&[[1.0, 2.0]]).view()).is_err());
143    }
144}