Skip to main content

dml_core/learner/
logistic.rs

1use ndarray::{concatenate, Array1, Array2, ArrayView1, ArrayView2, Axis};
2
3use super::Classifier;
4use crate::error::{DmlError, Result};
5use crate::linalg::cholesky_solve;
6
7/// L2-penalised logistic regression with an unpenalised intercept, fitted by
8/// Newton's method with backtracking line search.
9///
10/// Minimises `C · Σ logloss + ½‖w‖²`, the same objective as scikit-learn's
11/// `LogisticRegression(C=c)`; the default `C = 1` matches scikit-learn's default.
12#[derive(Debug, Clone)]
13pub struct LogisticRegression {
14    c: f64,
15    tol: f64,
16    max_iter: usize,
17    coef: Option<Array1<f64>>,
18    intercept: f64,
19}
20
21impl Default for LogisticRegression {
22    fn default() -> Self {
23        Self::new(1.0)
24    }
25}
26
27impl LogisticRegression {
28    /// Inverse regularisation strength `c` (larger = weaker penalty).
29    pub fn new(c: f64) -> Self {
30        Self {
31            c,
32            tol: 1e-10,
33            max_iter: 100,
34            coef: None,
35            intercept: 0.0,
36        }
37    }
38
39    /// No penalty. Fails to converge if the classes are perfectly separable.
40    pub fn unpenalized() -> Self {
41        Self::new(f64::INFINITY)
42    }
43
44    pub fn tol(mut self, tol: f64) -> Self {
45        self.tol = tol;
46        self
47    }
48
49    pub fn max_iter(mut self, max_iter: usize) -> Self {
50        self.max_iter = max_iter;
51        self
52    }
53
54    pub fn coef(&self) -> Option<&Array1<f64>> {
55        self.coef.as_ref()
56    }
57
58    pub fn intercept(&self) -> f64 {
59        self.intercept
60    }
61}
62
63/// `log(1 + e^η)` without overflow.
64fn softplus(eta: f64) -> f64 {
65    if eta > 0.0 {
66        eta + (-eta).exp().ln_1p()
67    } else {
68        eta.exp().ln_1p()
69    }
70}
71
72fn sigmoid(eta: f64) -> f64 {
73    if eta >= 0.0 {
74        1.0 / (1.0 + (-eta).exp())
75    } else {
76        let e = eta.exp();
77        e / (1.0 + e)
78    }
79}
80
81impl LogisticRegression {
82    /// `[intercept, coef…]` of the fitted model, to warm-start another fit.
83    pub(super) fn params(&self) -> Option<Array1<f64>> {
84        let coef = self.coef.as_ref()?;
85        let mut beta = Array1::zeros(coef.len() + 1);
86        beta[0] = self.intercept;
87        beta.slice_mut(ndarray::s![1..]).assign(coef);
88        Some(beta)
89    }
90
91    /// Newton's method started from `init = [intercept, coef…]` if given,
92    /// else from the intercept-only fit.
93    pub(super) fn fit_from(
94        &mut self,
95        x: ArrayView2<'_, f64>,
96        y: ArrayView1<'_, f64>,
97        init: Option<&Array1<f64>>,
98    ) -> Result<()> {
99        let (n, p) = x.dim();
100        if y.len() != n {
101            return Err(DmlError::DimensionMismatch(
102                "LogisticRegression::fit x/y rows".into(),
103            ));
104        }
105        if !y.iter().all(|&v| v == 0.0 || v == 1.0) {
106            return Err(DmlError::InvalidArgument(
107                "LogisticRegression labels must be 0 or 1".into(),
108            ));
109        }
110        let n1 = y.sum();
111        if n1 == 0.0 || n1 == n as f64 {
112            return Err(DmlError::InvalidArgument(
113                "LogisticRegression needs both classes in the training data".into(),
114            ));
115        }
116        let lambda = if self.c.is_finite() {
117            1.0 / self.c
118        } else {
119            0.0
120        };
121        // Design with a leading column of ones; beta = [intercept, w].
122        let xa = concatenate![Axis(1), Array2::ones((n, 1)), x];
123        let objective = |beta: &Array1<f64>| -> f64 {
124            let eta = xa.dot(beta);
125            let loss: f64 = eta
126                .iter()
127                .zip(y.iter())
128                .map(|(&e, &t)| softplus(e) - t * e)
129                .sum();
130            loss + 0.5
131                * lambda
132                * beta
133                    .slice(ndarray::s![1..])
134                    .dot(&beta.slice(ndarray::s![1..]))
135        };
136
137        let mut beta = match init {
138            Some(b) if b.len() == p + 1 => b.clone(),
139            _ => {
140                let mean = n1 / n as f64;
141                let mut b = Array1::<f64>::zeros(p + 1);
142                b[0] = (mean / (1.0 - mean)).ln();
143                b
144            }
145        };
146        let mut obj = objective(&beta);
147        let mut converged = false;
148        for _ in 0..self.max_iter {
149            let prob = xa.dot(&beta).mapv(sigmoid);
150            let mut grad = xa.t().dot(&(&prob - &y));
151            let w = prob.mapv(|q| q * (1.0 - q));
152            let mut hess = xa.t().dot(&(&xa * &w.insert_axis(Axis(1))));
153            for j in 1..=p {
154                grad[j] += lambda * beta[j];
155                hess[[j, j]] += lambda;
156            }
157            let step = cholesky_solve(&hess, &grad)?;
158            // Backtracking: halve the Newton step until the objective decreases.
159            let mut t = 1.0;
160            let mut candidate = &beta - &step;
161            let mut cand_obj = objective(&candidate);
162            while cand_obj > obj && t > 1e-10 {
163                t *= 0.5;
164                candidate = &beta - &(t * &step);
165                cand_obj = objective(&candidate);
166            }
167            let change = (t * &step).iter().fold(0.0_f64, |m, v| m.max(v.abs()));
168            beta = candidate;
169            obj = cand_obj;
170            if change <= self.tol * beta.iter().fold(1.0_f64, |m, v| m.max(v.abs())) {
171                converged = true;
172                break;
173            }
174        }
175        if !converged || !beta.iter().all(|v| v.is_finite()) {
176            return Err(DmlError::Convergence(format!(
177                "LogisticRegression did not converge in {} Newton steps (separable classes?)",
178                self.max_iter
179            )));
180        }
181        self.intercept = beta[0];
182        self.coef = Some(beta.slice(ndarray::s![1..]).to_owned());
183        Ok(())
184    }
185}
186
187impl Classifier for LogisticRegression {
188    fn fit(&mut self, x: ArrayView2<'_, f64>, y: ArrayView1<'_, f64>) -> Result<()> {
189        self.fit_from(x, y, None)
190    }
191
192    fn predict_proba(&self, x: ArrayView2<'_, f64>) -> Result<Array1<f64>> {
193        let coef = self.coef.as_ref().ok_or(DmlError::NotFitted)?;
194        if x.ncols() != coef.len() {
195            return Err(DmlError::DimensionMismatch(
196                "LogisticRegression::predict_proba feature count".into(),
197            ));
198        }
199        Ok((x.dot(coef) + self.intercept).mapv(sigmoid))
200    }
201
202    fn fresh(&self) -> Box<dyn Classifier> {
203        Box::new(Self::new(self.c).tol(self.tol).max_iter(self.max_iter))
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use ndarray::array;
211
212    #[test]
213    fn gradient_is_zero_at_optimum() {
214        let x = array![
215            [0.0, 1.0],
216            [1.0, 0.5],
217            [2.0, -1.0],
218            [3.0, 0.0],
219            [1.5, 2.0],
220            [0.5, -0.5]
221        ];
222        let y = array![0.0, 0.0, 1.0, 1.0, 0.0, 1.0];
223        let mut m = LogisticRegression::new(2.0);
224        m.fit(x.view(), y.view()).unwrap();
225        let p = m.predict_proba(x.view()).unwrap();
226        let r = &p - &y;
227        // Intercept gradient: Σ (p − y) = 0; slopes: C·Xᵀ(p − y) + w = 0.
228        assert!(r.sum().abs() < 1e-9);
229        let g = 2.0 * x.t().dot(&r) + m.coef().unwrap();
230        assert!(g.iter().all(|v| v.abs() < 1e-9));
231    }
232
233    #[test]
234    fn rejects_single_class_and_bad_labels() {
235        let x = array![[0.0], [1.0]];
236        let mut m = LogisticRegression::default();
237        assert!(m.fit(x.view(), array![1.0, 1.0].view()).is_err());
238        assert!(m.fit(x.view(), array![0.0, 2.0].view()).is_err());
239    }
240
241    #[test]
242    fn separable_unpenalized_reports_non_convergence() {
243        let x = array![[0.0], [1.0], [2.0], [3.0]];
244        let y = array![0.0, 0.0, 1.0, 1.0];
245        let err = LogisticRegression::unpenalized()
246            .fit(x.view(), y.view())
247            .unwrap_err();
248        assert!(matches!(err, DmlError::Convergence(_) | DmlError::Singular));
249    }
250}