linreg_core/regularized/path.rs
1//! Lambda path generation for regularized regression.
2//!
3//! This module provides utilities for generating a sequence of lambda values
4//! for regularization paths, matching glmnet's approach.
5//!
6//! # Lambda Path Construction
7//!
8//! glmnet generates a lambda path from `lambda_max` down to `lambda_min`:
9//!
10//! - `lambda_max`: The smallest lambda for which all penalized coefficients are zero
11//! - `lambda_min`: `lambda_min_ratio * lambda_max`
12//!
13//! For pure ridge (`alpha=0`), `lambda_max` is theoretically infinite, so we use
14//! a small `alpha` value to compute a finite starting point.
15
16use crate::linalg::Matrix;
17
18/// Options for generating a lambda path.
19///
20/// # Fields
21///
22/// * `nlambda` - Number of lambda values (default: 100)
23/// * `lambda_min_ratio` - Ratio for smallest lambda (default: 0.0001 if n < p, else 0.01)
24/// * `alpha` - Elastic net mixing parameter (0 = ridge, 1 = lasso)
25/// * `eps_for_ridge` - Small alpha to use for computing lambda_max when alpha=0 (default: 0.001)
26#[derive(Clone, Debug)]
27pub struct LambdaPathOptions {
28 /// Number of lambda values to generate
29 pub nlambda: usize,
30 /// Minimum lambda as a fraction of maximum
31 pub lambda_min_ratio: Option<f64>,
32 /// Elastic net mixing parameter (0 = ridge, 1 = lasso)
33 pub alpha: f64,
34 /// Small alpha to use for ridge lambda_max computation
35 pub eps_for_ridge: f64,
36}
37
38impl Default for LambdaPathOptions {
39 fn default() -> Self {
40 LambdaPathOptions {
41 nlambda: 100,
42 lambda_min_ratio: None,
43 alpha: 1.0,
44 eps_for_ridge: 0.001,
45 }
46 }
47}
48
49/// Computes `lambda_max`: the smallest lambda for which all penalized coefficients are zero.
50///
51/// For lasso (alpha > 0), lambda_max is the smallest value such that the soft-thresholding
52/// operation zeros out all coefficients.
53///
54/// For standardized X and centered y:
55/// ```text
56/// lambda_max = max_j |x_j^T y| / (n * alpha)
57/// ```
58///
59/// # Arguments
60///
61/// * `x` - Standardized design matrix (n × p), first column is intercept if present
62/// * `y` - Centered response vector (n elements)
63/// * `alpha` - Elastic net mixing parameter
64/// * `penalty_factor` - Per-feature penalty factors (optional, defaults to all 1.0)
65/// * `intercept_col` - Index of intercept column (typically 0, or None if no intercept)
66///
67/// # Returns
68///
69/// The maximum lambda value for the path.
70///
71/// # Note
72///
73/// If `alpha = 0` (pure ridge), this returns `f64::INFINITY` since ridge never produces
74/// exact zero coefficients. Use [`make_lambda_path`] which handles this case by using
75/// a small alpha value.
76#[allow(clippy::needless_range_loop)]
77pub fn compute_lambda_max(
78 x: &Matrix,
79 y: &[f64],
80 alpha: f64,
81 penalty_factor: Option<&[f64]>,
82 intercept_col: Option<usize>,
83) -> f64 {
84 if alpha <= 0.0 {
85 return f64::INFINITY;
86 }
87
88 let n = x.rows as f64;
89 let p = x.cols;
90
91 let mut max_corr: f64 = 0.0;
92
93 for j in 0..p {
94 // Skip intercept column
95 if let Some(ic) = intercept_col {
96 if j == ic {
97 continue;
98 }
99 }
100
101 // Compute absolute correlation: |x_j^T y|
102 // Matrix is row-major, so we iterate through rows for each column
103 let mut corr = 0.0;
104 for i in 0..x.rows {
105 corr += x.get(i, j) * y[i];
106 }
107 let corr = corr.abs();
108
109 // Apply penalty factor if provided
110 let effective_corr = if let Some(pf) = penalty_factor {
111 if j < pf.len() && pf[j] > 0.0 {
112 corr / pf[j]
113 } else {
114 corr
115 }
116 } else {
117 corr
118 };
119
120 max_corr = max_corr.max(effective_corr);
121 }
122
123 max_corr / (n * alpha)
124}
125
126/// Generates a lambda path from lambda_max down to lambda_min.
127///
128/// This creates a logarithmically-spaced sequence of lambda values, matching
129/// glmnet's approach for regularization paths.
130///
131/// # Arguments
132///
133/// * `x` - Standardized design matrix (n × p)
134/// * `y` - Centered response vector (n elements)
135/// * `options` - Lambda path generation options
136/// * `penalty_factor` - Optional per-feature penalty factors
137/// * `intercept_col` - Index of intercept column (typically 0)
138///
139/// # Returns
140///
141/// A vector of lambda values in **decreasing** order (largest to smallest).
142///
143/// # Lambda Sequence
144///
145/// The lambda values are logarithmically spaced:
146/// ```text
147/// lambda[k] = lambda_max * exp(log(lambda_min_ratio) * k / (nlambda - 1))
148/// ```
149///
150/// For ridge (`alpha ≈ 0`), we use a small alpha value to compute a finite
151/// `lambda_max`, then use that lambda sequence for the actual ridge fit.
152///
153/// # Default lambda_min_ratio
154///
155/// Following glmnet:
156/// - If `n >= p`: `lambda_min_ratio = 0.0001`
157/// - If `n < p`: `lambda_min_ratio = 0.01`
158pub fn make_lambda_path(
159 x: &Matrix,
160 y: &[f64],
161 options: &LambdaPathOptions,
162 penalty_factor: Option<&[f64]>,
163 intercept_col: Option<usize>,
164) -> Vec<f64> {
165 let n = x.rows;
166 let p = x.cols;
167
168 // Determine default lambda_min_ratio
169 let default_min_ratio = if n >= p { 0.0001 } else { 0.01 };
170 let lambda_min_ratio = options.lambda_min_ratio.unwrap_or(default_min_ratio);
171
172 // For pure ridge (alpha = 0), use a small alpha to compute lambda_max
173 let alpha_for_lambda_max = if options.alpha <= 0.0 {
174 options.eps_for_ridge
175 } else {
176 options.alpha
177 };
178
179 // Compute lambda_max
180 let lambda_max = compute_lambda_max(x, y, alpha_for_lambda_max, penalty_factor, intercept_col);
181
182 // Handle the case where lambda_max is infinite or very small
183 if !lambda_max.is_finite() || lambda_max <= 0.0 {
184 // For ridge with no good lambda_max, return a default path
185 return (0..options.nlambda)
186 .map(|k| {
187 let t = k as f64 / (options.nlambda - 1) as f64;
188 10.0_f64.powf(2.0 * (1.0 - t)) // 10^2 down to 10^0
189 })
190 .collect();
191 }
192
193 let _lambda_min = lambda_min_ratio * lambda_max;
194
195 // Generate logarithmically spaced lambdas (decreasing)
196 (0..options.nlambda)
197 .map(|k| {
198 let t = k as f64 / (options.nlambda - 1) as f64;
199 lambda_max * (lambda_min_ratio.powf(t))
200 })
201 .collect()
202}
203
204/// Extracts a specific set of lambdas from a path.
205///
206/// This is useful when you want to evaluate at specific lambda values
207/// rather than using the full path.
208///
209/// # Arguments
210///
211/// * `full_path` - The complete lambda path (must be in decreasing order)
212/// * `indices` - Indices of lambdas to extract
213///
214/// # Returns
215///
216/// A new vector containing the specified lambda values.
217pub fn extract_lambdas(full_path: &[f64], indices: &[usize]) -> Vec<f64> {
218 indices.iter().map(|&i| full_path[i]).collect()
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224
225 #[test]
226 fn test_compute_lambda_max() {
227 // Simple test: X = [1, x], y = [1, 2, 3]
228 let x_data = vec![1.0, -1.0, 1.0, 0.0, 1.0, 1.0];
229 let x = Matrix::new(3, 2, x_data);
230 let y = vec![1.0, 2.0, 3.0];
231
232 // Center y
233 let y_mean: f64 = y.iter().sum::<f64>() / 3.0;
234 let y_centered: Vec<f64> = y.iter().map(|&yi| yi - y_mean).collect();
235
236 let lambda_max = compute_lambda_max(&x, &y_centered, 1.0, None, Some(0));
237
238 // x^T y for column 1: -1*0 + 0*0 + 1*0 = 0 (since y is centered)
239 // Actually y_centered = [-1, 0, 1], so x^T y = 1*(-1) + 0*0 + 1*1 = 0
240 // y = [1,2,3], y_mean = 2, y_centered = [-1, 0, 1]
241 // back checks...
242 // Column 1 of X: [-1, 0, 1]
243 // dot = (-1)*(-1) + 0*0 + 1*1 = 1 + 0 + 1 = 2
244 // lambda_max = 2 / (3 * 1) = 2/3
245 assert!((lambda_max - 2.0 / 3.0).abs() < 1e-10);
246 }
247
248 #[test]
249 fn test_make_lambda_path_decreasing() {
250 let x_data = vec![1.0, -1.0, 1.0, 0.0, 1.0, 1.0];
251 let x = Matrix::new(3, 2, x_data);
252 let y_centered = vec![-1.0, 0.0, 1.0];
253
254 let options = LambdaPathOptions {
255 nlambda: 10,
256 lambda_min_ratio: Some(0.01),
257 alpha: 1.0,
258 eps_for_ridge: 0.001,
259 };
260
261 let path = make_lambda_path(&x, &y_centered, &options, None, Some(0));
262
263 assert_eq!(path.len(), 10);
264
265 // Check that path is decreasing
266 for i in 1..path.len() {
267 assert!(path[i] < path[i - 1]);
268 }
269
270 // First value should be lambda_max, last should be lambda_max * 0.01
271 let lambda_max = 2.0 / 3.0;
272 assert!((path[0] - lambda_max).abs() < 1e-10);
273 assert!((path[9] - lambda_max * 0.01).abs() < 1e-10);
274 }
275
276 #[test]
277 fn test_lambda_max_ridge() {
278 let x_data = vec![1.0, -1.0, 1.0, 0.0, 1.0, 1.0];
279 let x = Matrix::new(3, 2, x_data);
280 let y = vec![-1.0, 0.0, 1.0];
281
282 // For alpha = 0 (ridge), lambda_max should be infinite
283 let lambda_max = compute_lambda_max(&x, &y, 0.0, None, Some(0));
284 assert!(lambda_max.is_infinite());
285 }
286
287 #[test]
288 fn test_extract_lambdas() {
289 let path = vec![10.0, 5.0, 2.5, 1.25, 0.625];
290 let indices = vec![0, 2, 4];
291 let extracted = extract_lambdas(&path, &indices);
292
293 assert_eq!(extracted, vec![10.0, 2.5, 0.625]);
294 }
295}