linreg_core/regularized/ridge.rs
1//! Ridge regression (L2-regularized linear regression).
2//!
3//! This module provides a wrapper around the elastic net implementation with `alpha=0.0`.
4
5use crate::core::{aic, bic, log_likelihood};
6use crate::error::Result;
7use crate::linalg::Matrix;
8use crate::regularized::elastic_net::{elastic_net_fit, ElasticNetOptions};
9use crate::regularized::preprocess::predict;
10
11#[cfg(feature = "wasm")]
12use serde::Serialize;
13
14/// Options for ridge regression fitting.
15///
16/// Configuration options for ridge regression (L2-regularized linear regression).
17///
18/// # Fields
19///
20/// - `lambda` - Regularization strength (≥ 0, higher = more shrinkage)
21/// - `intercept` - Whether to include an intercept term
22/// - `standardize` - Whether to standardize predictors to unit variance
23/// - `max_iter` - Maximum coordinate descent iterations
24/// - `tol` - Convergence tolerance on coefficient changes
25/// - `warm_start` - Optional initial coefficient values for warm starts
26/// - `weights` - Optional observation weights
27///
28/// # Example
29///
30/// ```
31/// # use linreg_core::regularized::ridge::RidgeFitOptions;
32/// let options = RidgeFitOptions {
33/// lambda: 1.0,
34/// intercept: true,
35/// standardize: true,
36/// ..Default::default()
37/// };
38/// ```
39#[derive(Clone, Debug)]
40pub struct RidgeFitOptions {
41 pub lambda: f64,
42 pub intercept: bool,
43 pub standardize: bool,
44 pub max_iter: usize, // Added for consistency
45 pub tol: f64, // Added for consistency
46 pub warm_start: Option<Vec<f64>>,
47 pub weights: Option<Vec<f64>>, // Observation weights
48}
49
50impl Default for RidgeFitOptions {
51 fn default() -> Self {
52 RidgeFitOptions {
53 lambda: 1.0,
54 intercept: true,
55 standardize: true,
56 max_iter: 100000,
57 tol: 1e-7,
58 warm_start: None,
59 weights: None,
60 }
61 }
62}
63
64/// Result of a ridge regression fit.
65///
66/// Contains the fitted model coefficients, predictions, and diagnostic metrics.
67///
68/// # Fields
69///
70/// - `lambda` - The regularization strength used
71/// - `intercept` - Intercept coefficient (never penalized)
72/// - `coefficients` - Slope coefficients (penalized)
73/// - `fitted_values` - Predicted values on training data
74/// - `residuals` - Residuals (y - fitted_values)
75/// - `df` - Approximate effective degrees of freedom
76/// - `r_squared` - Coefficient of determination
77/// - `adj_r_squared` - Adjusted R²
78/// - `mse` - Mean squared error
79/// - `rmse` - Root mean squared error
80/// - `mae` - Mean absolute error
81/// - `log_likelihood` - Log-likelihood of the model (for model comparison)
82/// - `aic` - Akaike Information Criterion (lower = better)
83/// - `bic` - Bayesian Information Criterion (lower = better)
84///
85/// # Example
86///
87/// ```
88/// # use linreg_core::regularized::ridge::{ridge_fit, RidgeFitOptions};
89/// # use linreg_core::linalg::Matrix;
90/// # let y = vec![2.0, 4.0, 6.0, 8.0];
91/// # let x = Matrix::new(4, 2, vec![1.0, 1.0, 1.0, 2.0, 1.0, 3.0, 1.0, 4.0]);
92/// # let options = RidgeFitOptions { lambda: 0.1, intercept: true, standardize: false, ..Default::default() };
93/// let fit = ridge_fit(&x, &y, &options).unwrap();
94///
95/// // Access model coefficients
96/// println!("Intercept: {}", fit.intercept);
97/// println!("Slopes: {:?}", fit.coefficients);
98///
99/// // Access predictions and diagnostics
100/// println!("R²: {}", fit.r_squared);
101/// println!("RMSE: {}", fit.rmse);
102/// println!("AIC: {}", fit.aic);
103/// # Ok::<(), linreg_core::Error>(())
104/// ```
105#[derive(Clone, Debug)]
106#[cfg_attr(feature = "wasm", derive(Serialize))]
107pub struct RidgeFit {
108 pub lambda: f64,
109 pub intercept: f64,
110 pub coefficients: Vec<f64>,
111 pub fitted_values: Vec<f64>,
112 pub residuals: Vec<f64>,
113 pub df: f64, // Still computed, though approximation
114 pub r_squared: f64,
115 pub adj_r_squared: f64,
116 pub mse: f64,
117 pub rmse: f64,
118 pub mae: f64,
119 pub log_likelihood: f64,
120 pub aic: f64,
121 pub bic: f64,
122}
123
124/// Fits ridge regression for a single lambda value.
125///
126/// Ridge regression adds an L2 penalty to the coefficients, which helps with
127/// multicollinearity and overfitting. The intercept is never penalized.
128///
129/// # Arguments
130///
131/// * `x` - Design matrix (n rows × p columns including intercept)
132/// * `y` - Response variable (n observations)
133/// * `options` - Configuration options for ridge regression
134///
135/// # Returns
136///
137/// A `RidgeFit` containing coefficients, fitted values, residuals, and metrics.
138///
139/// # Example
140///
141/// ```
142/// # use linreg_core::regularized::ridge::{ridge_fit, RidgeFitOptions};
143/// # use linreg_core::linalg::Matrix;
144/// let y = vec![2.0, 4.0, 6.0, 8.0];
145/// let x = Matrix::new(4, 2, vec![1.0, 1.0, 1.0, 2.0, 1.0, 3.0, 1.0, 4.0]);
146///
147/// let options = RidgeFitOptions {
148/// lambda: 0.1,
149/// intercept: true,
150/// standardize: false,
151/// ..Default::default()
152/// };
153///
154/// let fit = ridge_fit(&x, &y, &options).unwrap();
155/// assert!(fit.coefficients.len() == 1); // One slope coefficient
156/// assert!(fit.r_squared > 0.9); // Good fit for linear data
157/// # Ok::<(), linreg_core::Error>(())
158/// ```
159pub fn ridge_fit(x: &Matrix, y: &[f64], options: &RidgeFitOptions) -> Result<RidgeFit> {
160 // DEBUG: Print lambda info
161 // #[cfg(debug_assertions)]
162 // {
163 // eprintln!("DEBUG ridge_fit: user_lambda = {}, standardize = {}", options.lambda, options.standardize);
164 // }
165
166 let en_options = ElasticNetOptions {
167 lambda: options.lambda,
168 alpha: 0.0, // Ridge
169 intercept: options.intercept,
170 standardize: options.standardize,
171 max_iter: options.max_iter,
172 tol: options.tol,
173 penalty_factor: None,
174 warm_start: options.warm_start.clone(),
175 weights: options.weights.clone(),
176 coefficient_bounds: None,
177 };
178
179 let fit = elastic_net_fit(x, y, &en_options)?;
180
181 // #[cfg(debug_assertions)]
182 // {
183 // eprintln!("DEBUG ridge_fit: fit.intercept = {}, fit.coefficients[0] = {}", fit.intercept,
184 // fit.coefficients.first().unwrap_or(&0.0));
185 // }
186
187 // Approximation of degrees of freedom for ridge regression.
188 //
189 // The true effective df requires SVD: sum(eigenvalues / (eigenvalues + lambda)).
190 // Since coordinate descent doesn't compute the SVD, we use a closed-form approximation
191 // that works well when X is standardized: df ≈ p / (1 + lambda).
192 //
193 // This approximation is reasonable for most practical purposes. For exact df,
194 // users would need to implement SVD-based calculation separately.
195 let p = x.cols;
196 let df = (p as f64) / (1.0 + options.lambda);
197
198 // Model selection criteria
199 let n = y.len();
200 let ss_res: f64 = fit.residuals.iter().map(|&r| r * r).sum();
201 let ll = log_likelihood(n, fit.mse, ss_res);
202 let n_coef = fit.coefficients.len() + 1; // coefficients + intercept
203 let aic_val = aic(ll, n_coef);
204 let bic_val = bic(ll, n_coef, n);
205
206 Ok(RidgeFit {
207 lambda: fit.lambda,
208 intercept: fit.intercept,
209 coefficients: fit.coefficients,
210 fitted_values: fit.fitted_values,
211 residuals: fit.residuals,
212 df,
213 r_squared: fit.r_squared,
214 adj_r_squared: fit.adj_r_squared,
215 mse: fit.mse,
216 rmse: fit.rmse,
217 mae: fit.mae,
218 log_likelihood: ll,
219 aic: aic_val,
220 bic: bic_val,
221 })
222}
223
224/// Makes predictions using a ridge regression fit.
225///
226/// Computes predictions for new observations using the fitted ridge regression model.
227///
228/// # Arguments
229///
230/// * `fit` - Fitted ridge regression model
231/// * `x_new` - New design matrix (same number of columns as training data)
232///
233/// # Returns
234///
235/// Vector of predicted values.
236///
237/// # Example
238///
239/// ```
240/// # use linreg_core::regularized::ridge::{ridge_fit, predict_ridge, RidgeFitOptions};
241/// # use linreg_core::linalg::Matrix;
242/// // Training data
243/// let y = vec![2.0, 4.0, 6.0, 8.0];
244/// let x = Matrix::new(4, 2, vec![1.0, 1.0, 1.0, 2.0, 1.0, 3.0, 1.0, 4.0]);
245///
246/// let options = RidgeFitOptions {
247/// lambda: 0.1,
248/// intercept: true,
249/// standardize: false,
250/// ..Default::default()
251/// };
252/// let fit = ridge_fit(&x, &y, &options).unwrap();
253///
254/// // Predict on new data
255/// let x_new = Matrix::new(2, 2, vec![1.0, 5.0, 1.0, 6.0]);
256/// let predictions = predict_ridge(&fit, &x_new);
257///
258/// assert_eq!(predictions.len(), 2);
259/// // Predictions should be close to [10.0, 12.0] for the linear relationship y = 2*x
260/// # Ok::<(), linreg_core::Error>(())
261/// ```
262pub fn predict_ridge(fit: &RidgeFit, x_new: &Matrix) -> Vec<f64> {
263 predict(x_new, fit.intercept, &fit.coefficients)
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269
270 #[test]
271 fn test_ridge_fit_simple() {
272 let x_data = vec![1.0, 1.0, 1.0, 2.0, 1.0, 3.0, 1.0, 4.0];
273 let x = Matrix::new(4, 2, x_data);
274 let y = vec![2.0, 4.0, 6.0, 8.0];
275
276 let options = RidgeFitOptions {
277 lambda: 0.1,
278 intercept: true,
279 standardize: false,
280 ..Default::default()
281 };
282
283 let fit = ridge_fit(&x, &y, &options).unwrap();
284
285 // OLS: intercept ≈ 0, slope ≈ 2
286 assert!((fit.coefficients[0] - 2.0).abs() < 0.2);
287 assert!(fit.intercept.abs() < 0.5);
288 }
289}