Skip to main content

ndarray_glm/response/
poisson.rs

1//! Model for Poisson regression
2
3#[cfg(feature = "stats")]
4use crate::response::Response;
5use crate::{
6    error::{RegressionError, RegressionResult},
7    glm::{DispersionType, Glm},
8    link::Link,
9    math::prod_log,
10    num::Float,
11    response::Yval,
12};
13use num_traits::{ToPrimitive, Unsigned};
14#[cfg(feature = "stats")]
15use statrs::distribution::Poisson as PoisDist;
16use std::marker::PhantomData;
17
18/// Poisson regression over an unsigned integer type.
19pub struct Poisson<L = link::Log>
20where
21    L: Link<Poisson<L>>,
22{
23    _link: PhantomData<L>,
24}
25
26/// Poisson variables can be any unsigned integer.
27impl<U, L> Yval<Poisson<L>> for U
28where
29    U: Unsigned + ToPrimitive + ToString + Copy,
30    L: Link<Poisson<L>>,
31{
32    fn into_float<F: Float>(self) -> RegressionResult<F, F> {
33        F::from(self).ok_or_else(|| RegressionError::InvalidY(self.to_string()))
34    }
35}
36// TODO: A floating point response for Poisson might also be do-able.
37
38#[cfg(feature = "stats")]
39impl<L> Response for Poisson<L>
40where
41    L: Link<Poisson<L>>,
42{
43    type DistributionType = PoisDist;
44
45    fn get_distribution(mu: f64, _phi: f64) -> Self::DistributionType {
46        PoisDist::new(mu).unwrap()
47    }
48}
49
50impl<L> Glm for Poisson<L>
51where
52    L: Link<Poisson<L>>,
53{
54    type Link = L;
55    const DISPERSED: DispersionType = DispersionType::NoDispersion;
56
57    /// The logarithm of the partition function for Poisson is the exponential of the natural
58    /// parameter, which is the logarithm of the mean.
59    fn log_partition<F: Float>(nat_par: F) -> F {
60        num_traits::Float::exp(nat_par)
61    }
62
63    /// The variance of a Poisson variable is equal to its mean.
64    fn variance<F: Float>(mean: F) -> F {
65        mean
66    }
67
68    /// The saturation likelihood of the Poisson distribution is non-trivial.
69    /// It is equal to y * (log(y) - 1).
70    fn log_like_sat<F: Float>(y: F) -> F {
71        prod_log(y) - y
72    }
73}
74
75pub mod link {
76    //! Link functions for Poisson regression
77    use super::Poisson;
78    use crate::{
79        link::{Canonical, Link},
80        num::Float,
81    };
82
83    /// The canonical link function of the Poisson response is the logarithm.
84    pub struct Log {}
85    impl Canonical for Log {}
86    impl Link<Poisson<Log>> for Log {
87        fn func<F: Float>(y: F) -> F {
88            num_traits::Float::ln(y)
89        }
90        fn func_inv<F: Float>(lin_pred: F) -> F {
91            num_traits::Float::exp(lin_pred)
92        }
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99    use crate::{error::RegressionResult, model::ModelBuilder};
100    use approx::assert_abs_diff_eq;
101    use ndarray::{Array1, array};
102
103    #[test]
104    fn poisson_reg() -> RegressionResult<(), f64> {
105        let ln2 = f64::ln(2.);
106        let beta = array![0., ln2, -ln2];
107        let data_x = array![[1., 0.], [1., 1.], [0., 1.], [0., 1.]];
108        let data_y: Array1<u32> = array![2, 1, 0, 1];
109        let model = ModelBuilder::<Poisson>::data(&data_y, &data_x).build()?;
110        let fit = model.fit_options().max_iter(10).fit()?;
111        dbg!(fit.n_iter);
112        assert_abs_diff_eq!(beta, fit.result, epsilon = f32::EPSILON as f64);
113        Ok(())
114    }
115}