1use crate::common::{Classifier, argmax, check_features, check_xy, class_count};
6use lib_jsl_core::{ErrorsJSL, R2D, VR2D};
7
8#[derive(Debug, Clone)]
13pub struct LogisticRegression {
14 l2: f64,
15 max_iterations: usize,
16 tolerance: f64,
17 weights: R2D,
19 iterations: usize,
20}
21
22impl LogisticRegression {
23 pub fn new(l2: f64) -> Self {
25 LogisticRegression { l2, max_iterations: 500, tolerance: 1e-7, weights: R2D::zeros((0, 0)), iterations: 0 }
26 }
27
28 pub fn with_limits(mut self, max_iterations: usize, tolerance: f64) -> Self {
29 self.max_iterations = max_iterations;
30 self.tolerance = tolerance;
31 self
32 }
33
34 pub fn coefficients(&self) -> R2D {
36 self.weights.slice(ndarray::s![.., ..self.weights.ncols().saturating_sub(1)]).to_owned()
37 }
38
39 pub fn intercepts(&self) -> Vec<f64> {
40 self.weights.column(self.weights.ncols() - 1).to_vec()
41 }
42
43 pub fn iterations(&self) -> usize {
45 self.iterations
46 }
47
48 pub fn predict_proba(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
50 if self.weights.nrows() == 0 {
51 return Err(ErrorsJSL::Misconfiguration("The model has not been fitted."));
52 }
53 check_features(x)?;
54 if x.ncols() + 1 != self.weights.ncols() {
55 return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.weights.ncols() - 1)));
56 }
57 Ok(softmax_rows(&self.weights, x))
58 }
59}
60
61fn softmax_rows(w: &R2D, x: VR2D) -> R2D {
62 let p = x.ncols();
63 let mut out = R2D::from_shape_fn((x.nrows(), w.nrows()), |(i, c)| w[[c, p]] + (0..p).map(|j| w[[c, j]] * x[[i, j]]).sum::<f64>());
64 for mut row in out.rows_mut() {
65 let m = row.iter().copied().fold(f64::NEG_INFINITY, f64::max);
66 row.mapv_inplace(|v| (v - m).exp());
67 let s = row.sum();
68 row.mapv_inplace(|v| v / s);
69 }
70 out
71}
72
73fn objective(theta: &[f64], x: VR2D, labels: &[usize], classes: usize, l2: f64) -> (f64, Vec<f64>) {
76 let (n, p) = x.dim();
77 let w = R2D::from_shape_vec((classes, p + 1), theta.to_vec()).expect("shape");
78 let proba = softmax_rows(&w, x);
79 let mut loss = 0.0;
80 let mut grad = R2D::zeros((classes, p + 1));
81 for i in 0..n {
82 loss -= proba[[i, labels[i]]].max(1e-300).ln();
83 for c in 0..classes {
84 let err = proba[[i, c]] - f64::from(c == labels[i]);
85 for j in 0..p {
86 grad[[c, j]] += err * x[[i, j]];
87 }
88 grad[[c, p]] += err;
89 }
90 }
91 loss /= n as f64;
92 grad /= n as f64;
93 for c in 0..classes {
94 for j in 0..p {
95 loss += 0.5 * l2 * w[[c, j]] * w[[c, j]];
96 grad[[c, j]] += l2 * w[[c, j]];
97 }
98 }
99 (loss, grad.into_raw_vec_and_offset().0)
100}
101pub(crate) fn lbfgs(mut f: impl FnMut(&[f64]) -> (f64, Vec<f64>), x0: Vec<f64>, max_iterations: usize, tolerance: f64) -> (Vec<f64>, usize) {
106 const MEMORY: usize = 10;
107 let dot = |a: &[f64], b: &[f64]| a.iter().zip(b).map(|(x, y)| x * y).sum::<f64>();
108 let mut x = x0;
109 let (mut fx, mut g) = f(&x);
110 let mut history: Vec<(Vec<f64>, Vec<f64>, f64)> = Vec::new(); for iter in 1..=max_iterations {
112 if g.iter().fold(0.0f64, |m, v| m.max(v.abs())) < tolerance {
113 return (x, iter - 1);
114 }
115 let mut q = g.clone();
117 let mut alphas = Vec::with_capacity(history.len());
118 for (s, y, rho) in history.iter().rev() {
119 let a = rho * dot(s, &q);
120 q.iter_mut().zip(y).for_each(|(qi, yi)| *qi -= a * yi);
121 alphas.push(a);
122 }
123 if let Some((s, y, _)) = history.last() {
124 let gamma = dot(s, y) / dot(y, y);
125 q.iter_mut().for_each(|v| *v *= gamma);
126 }
127 for ((s, y, rho), a) in history.iter().zip(alphas.iter().rev()) {
128 let b = rho * dot(y, &q);
129 q.iter_mut().zip(s).for_each(|(qi, si)| *qi += (a - b) * si);
130 }
131 let mut dir: Vec<f64> = q.iter().map(|v| -v).collect();
132 let mut slope = dot(&dir, &g);
133 if slope >= 0.0 {
134 dir = g.iter().map(|v| -v).collect(); slope = -dot(&g, &g);
136 history.clear();
137 }
138 let mut step = if history.is_empty() { 1.0 / dot(&g, &g).sqrt().max(1.0) } else { 1.0 };
139 let mut accepted = None;
140 for _ in 0..40 {
141 let trial: Vec<f64> = x.iter().zip(&dir).map(|(a, d)| a + step * d).collect();
142 let (ft, gt) = f(&trial);
143 if ft <= fx + 1e-4 * step * slope {
144 accepted = Some((trial, ft, gt));
145 break;
146 }
147 step *= 0.5;
148 }
149 let Some((nx, nf, ng)) = accepted else { return (x, iter) };
150 let s: Vec<f64> = nx.iter().zip(&x).map(|(a, b)| a - b).collect();
151 let y: Vec<f64> = ng.iter().zip(&g).map(|(a, b)| a - b).collect();
152 let sy = dot(&s, &y);
153 if sy > 1e-12 {
154 if history.len() == MEMORY {
155 history.remove(0);
156 }
157 history.push((s, y, 1.0 / sy));
158 }
159 let converged = (fx - nf).abs() < 1e-15 * fx.abs().max(1.0);
160 (x, fx, g) = (nx, nf, ng);
161 if converged {
162 return (x, iter);
163 }
164 }
165 (x, max_iterations)
166}
167
168impl Classifier for LogisticRegression {
169 fn fit(&mut self, x: VR2D, labels: &[usize]) -> Result<(), ErrorsJSL> {
170 check_xy(x, labels.len())?;
171 let classes = class_count(labels);
172 if classes < 2 {
173 return Err(ErrorsJSL::InvalidInputRange("At least two classes are required."));
174 }
175 if self.l2.is_nan() || self.l2 < 0.0 {
176 return Err(ErrorsJSL::InvalidInputRange("The penalty must be non-negative."));
177 }
178 let p = x.ncols();
179 let (theta, iterations) = lbfgs(|t| objective(t, x, labels, classes, self.l2), vec![0.0; classes * (p + 1)], self.max_iterations, self.tolerance);
180 self.weights = R2D::from_shape_vec((classes, p + 1), theta).expect("shape");
181 self.iterations = iterations;
182 Ok(())
183 }
184
185 fn predict(&self, x: VR2D) -> Result<Vec<usize>, ErrorsJSL> {
186 Ok(self.predict_proba(x)?.rows().into_iter().map(|r| argmax(&r.to_vec()).unwrap_or(0)).collect())
187 }
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193 use crate::common::Transformer;
194 use crate::datasets::{make_blobs, make_classification, make_moons};
195 use crate::metrics::accuracy;
196 use crate::preprocessing::StandardScaler;
197 use ndarray::arr2;
198
199 #[test]
200 fn separable_blobs_are_classified_perfectly_with_calibrated_probabilities() {
201 let (x, l) = make_blobs(40, &[vec![0.0, 0.0], vec![5.0, 5.0], vec![-5.0, 5.0]], 0.8, 3);
202 let mut m = LogisticRegression::new(1e-3);
203 m.fit(x.view(), &l).unwrap();
204 assert_eq!(accuracy(&l, &m.predict(x.view()).unwrap()).unwrap(), 1.0);
205 let p = m.predict_proba(x.view()).unwrap();
206 assert!(p.rows().into_iter().all(|r| (r.sum() - 1.0).abs() < 1e-12));
207 assert!(p[[0, 0]] > 0.95);
208 }
209
210 #[test]
211 fn linear_model_on_overlapping_classes_and_nonlinear_failure() {
212 let (x, l) = make_classification(150, 5);
213 let mut sc = StandardScaler::new();
214 let z = sc.fit_transform(x.view()).unwrap();
215 let mut m = LogisticRegression::new(1e-2);
216 m.fit(z.view(), &l).unwrap();
217 assert!(accuracy(&l, &m.predict(z.view()).unwrap()).unwrap() > 0.8);
218 let (mx, ml) = make_moons(150, 0.1, 2);
220 let mut lin = LogisticRegression::new(1e-3);
221 lin.fit(mx.view(), &ml).unwrap();
222 let acc = accuracy(&ml, &lin.predict(mx.view()).unwrap()).unwrap();
223 assert!((0.75..0.95).contains(&acc), "{acc}");
224 }
225
226 #[test]
227 fn regularisation_shrinks_weights_and_binary_matches_known_solution() {
228 let (x, l) = make_blobs(50, &[vec![-1.0, 0.0], vec![1.0, 0.0]], 1.0, 4);
229 let norm = |lam: f64| {
230 let mut m = LogisticRegression::new(lam);
231 m.fit(x.view(), &l).unwrap();
232 m.coefficients().iter().map(|v| v * v).sum::<f64>().sqrt()
233 };
234 assert!(norm(10.0) < norm(0.1) && norm(0.1) < norm(0.0001) * 1.0001);
235 let x1 = arr2(&[[-3.0], [-2.0], [-1.0], [1.0], [2.0], [3.0]]);
238 let mut m = LogisticRegression::new(0.0).with_limits(2000, 1e-9);
239 m.fit(x1.view(), &[0, 0, 0, 1, 1, 1]).unwrap();
240 assert_eq!(m.predict(x1.view()).unwrap(), vec![0, 0, 0, 1, 1, 1]);
241 assert!(m.intercepts().iter().all(|b| b.abs() < 1e-3)); }
243
244 #[test]
245 fn errors() {
246 let x = arr2(&[[0.0], [1.0]]);
247 assert!(LogisticRegression::new(0.1).fit(x.view(), &[0, 0]).is_err()); assert!(LogisticRegression::new(-1.0).fit(x.view(), &[0, 1]).is_err());
249 assert!(LogisticRegression::new(0.1).predict(x.view()).is_err());
250 let mut m = LogisticRegression::new(0.1);
251 m.fit(x.view(), &[0, 1]).unwrap();
252 assert!(m.predict(arr2(&[[1.0, 2.0]]).view()).is_err());
253 assert_eq!(m.intercepts().len(), 2);
254 }
255}