linreg_core/regularized/lasso.rs
1//! Lasso regression (L1-regularized linear regression).
2//!
3//! This module provides a wrapper around the elastic net implementation with `alpha=1.0`.
4
5use crate::error::Result;
6use crate::linalg::Matrix;
7use crate::regularized::elastic_net::{elastic_net_fit, ElasticNetOptions};
8use crate::regularized::preprocess::predict;
9
10#[cfg(feature = "wasm")]
11use serde::Serialize;
12
13pub use crate::regularized::elastic_net::soft_threshold;
14
15/// Options for lasso regression fitting.
16///
17/// Configuration options for lasso regression (L1-regularized linear regression).
18///
19/// # Fields
20///
21/// - `lambda` - Regularization strength (≥ 0, higher = more sparsity)
22/// - `intercept` - Whether to include an intercept term
23/// - `standardize` - Whether to standardize predictors to unit variance
24/// - `max_iter` - Maximum coordinate descent iterations
25/// - `tol` - Convergence tolerance on coefficient changes
26/// - `penalty_factor` - Optional per-feature penalty multipliers
27/// - `warm_start` - Optional initial coefficient values for warm starts
28/// - `weights` - Optional observation weights
29///
30/// # Example
31///
32/// ```
33/// # use linreg_core::regularized::lasso::LassoFitOptions;
34/// let options = LassoFitOptions {
35/// lambda: 0.1,
36/// intercept: true,
37/// standardize: true,
38/// ..Default::default()
39/// };
40/// ```
41#[derive(Clone, Debug)]
42pub struct LassoFitOptions {
43 pub lambda: f64,
44 pub intercept: bool,
45 pub standardize: bool,
46 pub max_iter: usize,
47 pub tol: f64,
48 pub penalty_factor: Option<Vec<f64>>,
49 pub warm_start: Option<Vec<f64>>,
50 pub weights: Option<Vec<f64>>, // Observation weights
51}
52
53impl Default for LassoFitOptions {
54 fn default() -> Self {
55 LassoFitOptions {
56 lambda: 1.0,
57 intercept: true,
58 standardize: true,
59 max_iter: 100000,
60 tol: 1e-7, // Match ElasticNetOptions default
61 penalty_factor: None,
62 warm_start: None,
63 weights: None,
64 }
65 }
66}
67
68/// Result of a lasso regression fit.
69///
70/// Contains the fitted model coefficients, convergence information, and diagnostic metrics.
71///
72/// # Fields
73///
74/// - `lambda` - The regularization strength used
75/// - `intercept` - Intercept coefficient (never penalized)
76/// - `coefficients` - Slope coefficients (some may be exactly zero due to L1 penalty)
77/// - `fitted_values` - Predicted values on training data
78/// - `residuals` - Residuals (y - fitted_values)
79/// - `n_nonzero` - Number of non-zero coefficients (excluding intercept)
80/// - `iterations` - Number of coordinate descent iterations performed
81/// - `converged` - Whether the algorithm converged
82/// - `r_squared` - Coefficient of determination
83/// - `adj_r_squared` - Adjusted R²
84/// - `mse` - Mean squared error
85/// - `rmse` - Root mean squared error
86/// - `mae` - Mean absolute error
87/// - `log_likelihood` - Log-likelihood of the model (for model comparison)
88/// - `aic` - Akaike Information Criterion (lower = better)
89/// - `bic` - Bayesian Information Criterion (lower = better)
90///
91/// # Example
92///
93/// ```
94/// # use linreg_core::regularized::lasso::{lasso_fit, LassoFitOptions};
95/// # use linreg_core::linalg::Matrix;
96/// # let y = vec![2.0, 4.0, 6.0, 8.0];
97/// # let x = Matrix::new(4, 2, vec![1.0, 1.0, 1.0, 2.0, 1.0, 3.0, 1.0, 4.0]);
98/// # let options = LassoFitOptions { lambda: 0.01, intercept: true, standardize: true, ..Default::default() };
99/// let fit = lasso_fit(&x, &y, &options).unwrap();
100///
101/// // Check convergence and sparsity
102/// println!("Converged: {}", fit.converged);
103/// println!("Non-zero coefficients: {}", fit.n_nonzero);
104/// println!("Iterations: {}", fit.iterations);
105///
106/// // Access model coefficients
107/// println!("Intercept: {}", fit.intercept);
108/// println!("Slopes: {:?}", fit.coefficients);
109/// println!("AIC: {}", fit.aic);
110/// # Ok::<(), linreg_core::Error>(())
111/// ```
112#[derive(Clone, Debug)]
113#[cfg_attr(feature = "wasm", derive(Serialize))]
114pub struct LassoFit {
115 pub lambda: f64,
116 pub intercept: f64,
117 pub coefficients: Vec<f64>,
118 pub fitted_values: Vec<f64>,
119 pub residuals: Vec<f64>,
120 pub n_nonzero: usize,
121 pub iterations: usize,
122 pub converged: bool,
123 pub r_squared: f64,
124 pub adj_r_squared: f64,
125 pub mse: f64,
126 pub rmse: f64,
127 pub mae: f64,
128 pub log_likelihood: f64,
129 pub aic: f64,
130 pub bic: f64,
131}
132
133/// Fits lasso regression for a single lambda value.
134///
135/// Lasso regression adds an L1 penalty to the coefficients, which performs
136/// automatic variable selection by shrinking some coefficients to exactly zero.
137/// The intercept is never penalized.
138///
139/// # Arguments
140///
141/// * `x` - Design matrix (n rows × p columns including intercept)
142/// * `y` - Response variable (n observations)
143/// * `options` - Configuration options for lasso regression
144///
145/// # Returns
146///
147/// A `LassoFit` containing coefficients, convergence info, and metrics.
148///
149/// # Example
150///
151/// ```
152/// # use linreg_core::regularized::lasso::{lasso_fit, LassoFitOptions};
153/// # use linreg_core::linalg::Matrix;
154/// let y = vec![2.0, 4.0, 6.0, 8.0];
155/// let x = Matrix::new(4, 2, vec![1.0, 1.0, 1.0, 2.0, 1.0, 3.0, 1.0, 4.0]);
156///
157/// let options = LassoFitOptions {
158/// lambda: 0.01,
159/// intercept: true,
160/// standardize: true,
161/// ..Default::default()
162/// };
163///
164/// let fit = lasso_fit(&x, &y, &options).unwrap();
165/// assert!(fit.converged);
166/// assert!(fit.n_nonzero <= 1); // At most 1 non-zero coefficient
167/// # Ok::<(), linreg_core::Error>(())
168/// ```
169pub fn lasso_fit(x: &Matrix, y: &[f64], options: &LassoFitOptions) -> Result<LassoFit> {
170 let en_options = ElasticNetOptions {
171 lambda: options.lambda,
172 alpha: 1.0, // Lasso
173 intercept: options.intercept,
174 standardize: options.standardize,
175 max_iter: options.max_iter,
176 tol: options.tol,
177 penalty_factor: options.penalty_factor.clone(),
178 warm_start: options.warm_start.clone(),
179 weights: options.weights.clone(),
180 coefficient_bounds: None,
181 };
182
183 let fit = elastic_net_fit(x, y, &en_options)?;
184
185 Ok(LassoFit {
186 lambda: fit.lambda,
187 intercept: fit.intercept,
188 coefficients: fit.coefficients,
189 fitted_values: fit.fitted_values,
190 residuals: fit.residuals,
191 n_nonzero: fit.n_nonzero,
192 iterations: fit.iterations,
193 converged: fit.converged,
194 r_squared: fit.r_squared,
195 adj_r_squared: fit.adj_r_squared,
196 mse: fit.mse,
197 rmse: fit.rmse,
198 mae: fit.mae,
199 log_likelihood: fit.log_likelihood,
200 aic: fit.aic,
201 bic: fit.bic,
202 })
203}
204
205/// Makes predictions using a lasso regression fit.
206///
207/// Computes predictions for new observations using the fitted lasso regression model.
208///
209/// # Arguments
210///
211/// * `fit` - Fitted lasso regression model
212/// * `x_new` - New design matrix (same number of columns as training data)
213///
214/// # Returns
215///
216/// Vector of predicted values.
217///
218/// # Example
219///
220/// ```
221/// # use linreg_core::regularized::lasso::{lasso_fit, predict_lasso, LassoFitOptions};
222/// # use linreg_core::linalg::Matrix;
223/// // Training data
224/// let y = vec![2.0, 4.0, 6.0, 8.0];
225/// let x = Matrix::new(4, 2, vec![1.0, 1.0, 1.0, 2.0, 1.0, 3.0, 1.0, 4.0]);
226///
227/// let options = LassoFitOptions {
228/// lambda: 0.01,
229/// intercept: true,
230/// standardize: true,
231/// ..Default::default()
232/// };
233/// let fit = lasso_fit(&x, &y, &options).unwrap();
234///
235/// // Predict on new data
236/// let x_new = Matrix::new(2, 2, vec![1.0, 5.0, 1.0, 6.0]);
237/// let predictions = predict_lasso(&fit, &x_new);
238///
239/// assert_eq!(predictions.len(), 2);
240/// // Predictions should be close to [10.0, 12.0] for the linear relationship y = 2*x
241/// # Ok::<(), linreg_core::Error>(())
242/// ```
243pub fn predict_lasso(fit: &LassoFit, x_new: &Matrix) -> Vec<f64> {
244 predict(x_new, fit.intercept, &fit.coefficients)
245}
246
247#[cfg(test)]
248mod tests {
249 use super::*;
250
251 #[test]
252 fn test_soft_threshold() {
253 assert_eq!(soft_threshold(5.0, 2.0), 3.0);
254 assert_eq!(soft_threshold(-5.0, 2.0), -3.0);
255 assert_eq!(soft_threshold(1.0, 2.0), 0.0);
256 }
257
258 #[test]
259 fn test_lasso_fit_simple() {
260 // Simple test: y = 2*x with perfect linear relationship
261 let x_data = vec![1.0, 1.0, 1.0, 2.0, 1.0, 3.0, 1.0, 4.0];
262 let x = Matrix::new(4, 2, x_data);
263 let y = vec![2.0, 4.0, 6.0, 8.0];
264
265 let options = LassoFitOptions {
266 lambda: 0.01,
267 intercept: true,
268 standardize: true,
269 ..Default::default()
270 };
271
272 let fit = lasso_fit(&x, &y, &options).unwrap();
273
274 assert!(fit.converged);
275 // Predictions should be close to actual values
276 for i in 0..4 {
277 assert!((fit.fitted_values[i] - y[i]).abs() < 0.5);
278 }
279 }
280}