ndarray_glm/response/
logistic.rs1#[cfg(feature = "stats")]
5use crate::response::Response;
6use crate::{
7 error::{RegressionError, RegressionResult},
8 glm::{DispersionType, Glm},
9 link::Link,
10 math::prod_log,
11 num::Float,
12 response::Yval,
13};
14use ndarray::Array1;
15#[cfg(feature = "stats")]
16use statrs::distribution::Bernoulli;
17use std::marker::PhantomData;
18
19pub struct Logistic<L = link::Logit>
21where
22 L: Link<Logistic<L>>,
23{
24 _link: PhantomData<L>,
25}
26
27impl<L> Yval<Logistic<L>> for bool
29where
30 L: Link<Logistic<L>>,
31{
32 fn into_float<F: Float>(self) -> RegressionResult<F, F> {
33 Ok(if self { F::one() } else { F::zero() })
34 }
35}
36impl<L> Yval<Logistic<L>> for f32
40where
41 L: Link<Logistic<L>>,
42{
43 fn into_float<F: Float>(self) -> RegressionResult<F, F> {
44 if !(0.0..=1.0).contains(&self) {
45 return Err(RegressionError::InvalidY(self.to_string()));
46 }
47 F::from(self).ok_or_else(|| RegressionError::InvalidY(self.to_string()))
48 }
49}
50impl<L> Yval<Logistic<L>> for f64
51where
52 L: Link<Logistic<L>>,
53{
54 fn into_float<F: Float>(self) -> RegressionResult<F, F> {
55 if !(0.0..=1.0).contains(&self) {
56 return Err(RegressionError::InvalidY(self.to_string()));
57 }
58 F::from(self).ok_or_else(|| RegressionError::InvalidY(self.to_string()))
59 }
60}
61
62#[cfg(feature = "stats")]
63impl<L> Response for Logistic<L>
64where
65 L: Link<Logistic<L>>,
66{
67 type DistributionType = Bernoulli;
68
69 fn get_distribution(mu: f64, _phi: f64) -> Self::DistributionType {
70 Bernoulli::new(mu).unwrap()
71 }
72}
73
74impl<L> Glm for Logistic<L>
76where
77 L: Link<Logistic<L>>,
78{
79 type Link = L;
80 const DISPERSED: DispersionType = DispersionType::NoDispersion;
81
82 fn log_partition<F: Float>(nat_par: F) -> F {
85 num_traits::Float::exp(nat_par).ln_1p()
86 }
87
88 fn variance<F: Float>(mean: F) -> F {
90 mean * (F::one() - mean)
91 }
92
93 fn log_like_natural<F>(y: F, logit_p: F) -> F
96 where
97 F: Float,
98 {
99 let (yt, xt) = if logit_p < F::zero() {
100 (y, logit_p)
101 } else {
102 (F::one() - y, -logit_p)
103 };
104 yt * xt - num_traits::Float::exp(xt).ln_1p()
105 }
106
107 fn log_like_sat<F: Float>(y: F) -> F {
110 prod_log(y) + prod_log(F::one() - y)
111 }
112}
113
114pub mod link {
115 use super::*;
117 use crate::link::{Canonical, Link, Transform};
118 use crate::num::Float;
119
120 pub struct Logit {}
123 impl Canonical for Logit {}
124 impl Link<Logistic<Logit>> for Logit {
125 fn func<F: Float>(y: F) -> F {
126 num_traits::Float::ln(y / (F::one() - y))
127 }
128 fn func_inv<F: Float>(lin_pred: F) -> F {
129 (F::one() + num_traits::Float::exp(-lin_pred)).recip()
130 }
131 }
132
133 pub struct Cloglog {}
137 impl Link<Logistic<Cloglog>> for Cloglog {
138 fn func<F: Float>(y: F) -> F {
139 num_traits::Float::ln(-F::ln_1p(-y))
140 }
141 fn func_inv<F: Float>(lin_pred: F) -> F {
143 -F::exp_m1(-num_traits::Float::exp(lin_pred))
144 }
145 }
146 impl Transform for Cloglog {
147 fn nat_param<F: Float>(lin_pred: Array1<F>) -> Array1<F> {
148 lin_pred.mapv(|x| num_traits::Float::ln(num_traits::Float::exp(x).exp_m1()))
149 }
150 fn d_nat_param<F: Float>(lin_pred: &Array1<F>) -> Array1<F> {
151 let neg_exp_lin = -lin_pred.mapv(num_traits::Float::exp);
152 &neg_exp_lin / &neg_exp_lin.mapv(F::exp_m1)
153 }
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 use super::*;
160 use crate::{error::RegressionResult, model::ModelBuilder};
161 use approx::assert_abs_diff_eq;
162 use ndarray::array;
163
164 #[test]
166 fn log_reg() -> RegressionResult<(), f64> {
167 let beta = array![0., 1.0];
168 let ln2 = f64::ln(2.);
169 let data_x = array![[0.], [0.], [ln2], [ln2], [ln2]];
170 let data_y = array![true, false, true, true, false];
171 let model = ModelBuilder::<Logistic>::data(&data_y, &data_x).build()?;
172 let fit = model.fit()?;
173 assert_abs_diff_eq!(beta, fit.result, epsilon = 0.5 * f32::EPSILON as f64);
178 Ok(())
180 }
181
182 #[test]
183 fn logit_closure() {
185 use crate::link::TestLink;
186 let x = array![-500., -50., -2.0, -0.2, 0., 0.5, 20.];
190 super::link::Logit::check_closure(&x);
191 let y = array![0., 1e-5, 0.25, 0.5, 0.8, 0.9999, 1.0];
192 super::link::Logit::check_closure_y(&y);
193 }
194
195 #[test]
197 fn cloglog_closure() {
198 use crate::link::TestLink;
199 use link::Cloglog;
200 let mu_test_vals = array![1e-8, 0.01, 0.1, 0.3, 0.5, 0.7, 0.9, 0.99, 0.9999999];
201 Cloglog::check_closure_y(&mu_test_vals);
202 let lin_test_vals = array![-10., -2., -0.1, 0.0, 0.1, 1., 2.];
203 Cloglog::check_closure(&lin_test_vals);
204 }
205
206 #[test]
207 fn cloglog_nat_par() {
208 use crate::link::TestLink;
209 use link::Cloglog;
210 let lin_test_vals = array![-10., -2., -0.1, 0.0, 0.1, 1., 2.];
212 Cloglog::check_nat_par::<Logistic<link::Logit>>(&lin_test_vals);
213 Cloglog::check_nat_par_d(&lin_test_vals);
214 }
215}