Skip to main content

lib_jsl_machine_learning/supervised/regression/
elastic_net.rs

1//! Elastic net regression (lasso and ridge combined), by cyclic coordinate descent.
2//!
3//! See the book entry [Linear regression](https://jwkunz.github.io/lib_jsl/book/machine_learning/linear-regression.html#the-lasso-and-the-elastic-net).
4
5use super::least_squares::column_means;
6use crate::common::{Regressor, check_xy};
7use lib_jsl_core::{ErrorsJSL, R1D, VR1D, VR2D};
8
9/// Minimises `1/(2n) ‖y - Xw - b‖² + α (ρ ‖w‖₁ + (1-ρ)/2 ‖w‖²)`.
10///
11/// The L1 part (`ρ`, the `l1_ratio`) drives some weights exactly to zero, selecting features; the L2
12/// part stabilises the solution when features are correlated. `l1_ratio = 1` is the lasso and `0`
13/// is (a scaled) ridge. Coordinate descent updates one weight at a time with a closed-form
14/// soft-threshold step until the largest change falls below `tolerance`.
15#[derive(Debug, Clone)]
16pub struct ElasticNet {
17    alpha: f64,
18    l1_ratio: f64,
19    max_iterations: usize,
20    tolerance: f64,
21    weights: R1D,
22    intercept: f64,
23    iterations: usize,
24    fitted: bool,
25}
26
27fn soft_threshold(z: f64, gamma: f64) -> f64 {
28    if z > gamma { z - gamma } else if z < -gamma { z + gamma } else { 0.0 }
29}
30
31impl ElasticNet {
32    pub fn new(alpha: f64, l1_ratio: f64) -> Self {
33        ElasticNet { alpha, l1_ratio, max_iterations: 10_000, tolerance: 1e-10, weights: R1D::zeros(0), intercept: 0.0, iterations: 0, fitted: false }
34    }
35
36    /// The lasso: pure L1 penalty.
37    pub fn lasso(alpha: f64) -> Self {
38        Self::new(alpha, 1.0)
39    }
40
41    pub fn with_limits(mut self, max_iterations: usize, tolerance: f64) -> Self {
42        self.max_iterations = max_iterations;
43        self.tolerance = tolerance;
44        self
45    }
46
47    pub fn weights(&self) -> &R1D {
48        &self.weights
49    }
50
51    pub fn intercept(&self) -> f64 {
52        self.intercept
53    }
54
55    /// Sweeps used by the last fit.
56    pub fn iterations(&self) -> usize {
57        self.iterations
58    }
59
60    /// Number of non-zero weights.
61    pub fn nonzero(&self) -> usize {
62        self.weights.iter().filter(|&&w| w != 0.0).count()
63    }
64}
65
66impl Regressor for ElasticNet {
67    fn fit(&mut self, x: VR2D, y: VR1D) -> Result<(), ErrorsJSL> {
68        check_xy(x, y.len())?;
69        if self.alpha.is_nan() || self.alpha < 0.0 || !(0.0..=1.0).contains(&self.l1_ratio) {
70            return Err(ErrorsJSL::InvalidInputRange("Need alpha >= 0 and l1_ratio in [0, 1]."));
71        }
72        let (n, p) = x.dim();
73        let (x_mean, y_mean) = (column_means(x), y.sum() / n as f64);
74        let xc: Vec<Vec<f64>> = (0..p).map(|j| (0..n).map(|i| x[[i, j]] - x_mean[j]).collect()).collect(); // column-major
75        let col_sq: Vec<f64> = xc.iter().map(|c| c.iter().map(|v| v * v).sum::<f64>() / n as f64).collect();
76        let (l1, l2) = (self.alpha * self.l1_ratio, self.alpha * (1.0 - self.l1_ratio));
77        let mut w = vec![0.0; p];
78        let mut resid: Vec<f64> = y.iter().map(|v| v - y_mean).collect();
79        self.iterations = 0;
80        // ANCHOR: coordinate_descent
81        for sweep in 1..=self.max_iterations {
82            let mut max_change: f64 = 0.0;
83            for j in 0..p {
84                if col_sq[j] == 0.0 {
85                    continue;
86                }
87                // rho = (1/n) x_j · (resid + x_j w_j): the correlation with the partial residual.
88                let rho = xc[j].iter().zip(&resid).map(|(a, r)| a * r).sum::<f64>() / n as f64 + col_sq[j] * w[j];
89                let new = soft_threshold(rho, l1) / (col_sq[j] + l2);
90                let delta = new - w[j];
91                if delta != 0.0 {
92                    resid.iter_mut().zip(&xc[j]).for_each(|(r, a)| *r -= a * delta);
93                    w[j] = new;
94                }
95                max_change = max_change.max(delta.abs());
96            }
97            self.iterations = sweep;
98            if max_change < self.tolerance {
99                break;
100            }
101        }
102        // ANCHOR_END: coordinate_descent
103        self.weights = R1D::from(w);
104        self.intercept = y_mean - x_mean.dot(&self.weights);
105        self.fitted = true;
106        Ok(())
107    }
108
109    fn predict(&self, x: VR2D) -> Result<R1D, ErrorsJSL> {
110        if !self.fitted {
111            return Err(ErrorsJSL::Misconfiguration("The model has not been fitted."));
112        }
113        if x.ncols() != self.weights.len() {
114            return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.weights.len())));
115        }
116        Ok(x.dot(&self.weights) + self.intercept)
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use crate::common::MlRng;
124    use crate::metrics::r2_score;
125    use ndarray::{Array2, arr1, arr2};
126
127    /// Ten features of which only the first three matter.
128    fn sparse_problem(seed: u64) -> (Array2<f64>, R1D) {
129        let mut rng = MlRng::new(seed);
130        let x = Array2::from_shape_fn((200, 10), |_| rng.gaussian(0.0, 1.0));
131        let y = R1D::from_iter((0..200).map(|i| 4.0 * x[[i, 0]] - 3.0 * x[[i, 1]] + 2.0 * x[[i, 2]] + 1.0 + rng.gaussian(0.0, 0.2)));
132        (x, y)
133    }
134
135    #[test]
136    fn lasso_selects_the_relevant_features() {
137        let (x, y) = sparse_problem(3);
138        let mut m = ElasticNet::lasso(0.2);
139        m.fit(x.view(), y.view()).unwrap();
140        assert!(m.weights().iter().skip(3).all(|&w| w == 0.0), "{:?}", m.weights());
141        assert_eq!(m.nonzero(), 3);
142        assert!(m.weights()[0] > 3.5 && m.weights()[1] < -2.5 && m.weights()[2] > 1.5);
143        assert!(r2_score(y.view(), m.predict(x.view()).unwrap().view()).unwrap() > 0.97);
144    }
145
146    #[test]
147    fn penalty_path_and_zero_penalty_limit() {
148        let (x, y) = sparse_problem(5);
149        let counts: Vec<usize> = [0.01, 0.2, 1.0, 5.0, 50.0]
150            .iter()
151            .map(|&a| {
152                let mut m = ElasticNet::lasso(a);
153                m.fit(x.view(), y.view()).unwrap();
154                m.nonzero()
155            })
156            .collect();
157        assert!(counts.windows(2).all(|p| p[1] <= p[0]) && counts[0] >= 4 && counts[4] == 0, "{counts:?}");
158        // With no penalty it is ordinary least squares.
159        let mut free = ElasticNet::new(0.0, 0.5);
160        free.fit(x.view(), y.view()).unwrap();
161        assert!((free.weights()[0] - 4.0).abs() < 0.1 && (free.intercept() - 1.0).abs() < 0.1);
162    }
163
164    #[test]
165    fn l2_part_spreads_weight_over_correlated_features() {
166        // Two identical columns: the lasso picks one arbitrarily, the elastic net splits the weight.
167        let n = 100;
168        let mut rng = MlRng::new(2);
169        let base: Vec<f64> = (0..n).map(|_| rng.gaussian(0.0, 1.0)).collect();
170        let x = Array2::from_shape_fn((n, 2), |(i, _)| base[i]);
171        let y = R1D::from_iter(base.iter().map(|b| 2.0 * b));
172        let mut en = ElasticNet::new(0.05, 0.3);
173        en.fit(x.view(), y.view()).unwrap();
174        assert!((en.weights()[0] - en.weights()[1]).abs() < 1e-6 && en.weights()[0] > 0.5);
175    }
176
177    #[test]
178    fn errors() {
179        let (x, y) = (arr2(&[[1.0], [2.0]]), arr1(&[1.0, 2.0]));
180        assert!(ElasticNet::new(-1.0, 0.5).fit(x.view(), y.view()).is_err());
181        assert!(ElasticNet::new(1.0, 1.5).fit(x.view(), y.view()).is_err());
182        assert!(ElasticNet::lasso(0.1).predict(x.view()).is_err());
183        let mut m = ElasticNet::lasso(0.0).with_limits(5, 1e-12);
184        m.fit(x.view(), y.view()).unwrap();
185        assert!(m.iterations() <= 5);
186        // A constant column is ignored rather than dividing by zero.
187        let mut c = ElasticNet::lasso(0.1);
188        c.fit(arr2(&[[1.0, 5.0], [2.0, 5.0], [3.0, 5.0]]).view(), arr1(&[2.0, 4.0, 6.0]).view()).unwrap();
189        assert_eq!(c.weights()[1], 0.0);
190    }
191}