Skip to main content

ndarray_glm/response/
gamma.rs

1//! Gamma response in that y is drawn from the gamma distribution. This is very similar to
2//! exponential regression
3
4#[cfg(feature = "stats")]
5use crate::response::Response;
6use crate::{
7    error::{RegressionError, RegressionResult},
8    glm::{DispersionType, Glm},
9    link::Link,
10    num::Float,
11    response::Yval,
12};
13use ndarray::Array1;
14#[cfg(feature = "stats")]
15use statrs::distribution::Gamma as GammaDist;
16use std::marker::PhantomData;
17
18/// Gamma regression
19pub struct Gamma<L = link::NegRec>
20where
21    L: Link<Gamma<L>>,
22{
23    _link: PhantomData<L>,
24}
25
26// Note that for gamma regression, y=0 is invalid.
27impl<L> Yval<Gamma<L>> for f32
28where
29    L: Link<Gamma<L>>,
30{
31    fn into_float<F: Float>(self) -> RegressionResult<F, F> {
32        if self <= 0. {
33            return Err(RegressionError::InvalidY(self.to_string()));
34        }
35        F::from(self).ok_or_else(|| RegressionError::InvalidY(self.to_string()))
36    }
37}
38impl<L> Yval<Gamma<L>> for f64
39where
40    L: Link<Gamma<L>>,
41{
42    fn into_float<F: Float>(self) -> RegressionResult<F, F> {
43        if self <= 0. {
44            return Err(RegressionError::InvalidY(self.to_string()));
45        }
46        F::from(self).ok_or_else(|| RegressionError::InvalidY(self.to_string()))
47    }
48}
49
50#[cfg(feature = "stats")]
51impl<L> Response for Gamma<L>
52where
53    L: Link<Gamma<L>>,
54{
55    type DistributionType = GammaDist;
56
57    fn get_distribution(mu: f64, phi: f64) -> Self::DistributionType {
58        // Clamp phi to be no lower than epsilon ~2e-16. This will avoid overflows for
59        // overspecified models. f64::MAX_POSITIVE would probably be overkill and might lead to
60        // infinite values.
61        let alpha = 1. / phi.max(f64::EPSILON);
62        // mu = alpha / beta
63        let beta = alpha / mu;
64        let beta = beta.clamp(f64::MIN_POSITIVE, f64::MAX);
65        GammaDist::new(alpha, beta).unwrap()
66    }
67}
68
69/// Implementation of GLM functionality for gamma regression.
70impl<L> Glm for Gamma<L>
71where
72    L: Link<Gamma<L>>,
73{
74    type Link = L;
75    const DISPERSED: DispersionType = DispersionType::FreeDispersion;
76
77    /// The log-partition function $`A(\eta)`$ for the gamma family, expressed in terms of the
78    /// canonical natural parameter $`\eta = -1/\mu`$:
79    ///
80    /// ```math
81    /// A(\eta) = -\ln(-\eta)
82    /// ```
83    fn log_partition<F: Float>(nat_par: F) -> F {
84        -num_traits::Float::ln(-nat_par)
85    }
86
87    /// The variance function $`V(\mu) = \mu^2`$, equal to $`A''(\eta)`$ evaluated at
88    /// $`\eta = -1/\mu`$.
89    fn variance<F: Float>(mean: F) -> F {
90        mean * mean
91    }
92
93    /// The saturated likelihood is -1 - log(y). This is one reason why gamma regression can't deal
94    /// with y=0.
95    fn log_like_sat<F: Float>(y: F) -> F {
96        -(F::one() + num_traits::Float::ln(y))
97    }
98}
99
100pub mod link {
101    //! Link functions for gamma regression
102    use super::*;
103    use crate::link::{Canonical, Link, Transform};
104    use crate::num::Float;
105
106    /// The canonical link function for gamma regression is the negative reciprocal
107    /// $`\eta = -1/\mu`$. This fails to prevent negative predicted y-values.
108    pub struct NegRec {}
109    impl Canonical for NegRec {}
110    impl Link<Gamma<NegRec>> for NegRec {
111        fn func<F: Float>(y: F) -> F {
112            -num_traits::Float::recip(y)
113        }
114        fn func_inv<F: Float>(lin_pred: F) -> F {
115            -num_traits::Float::recip(lin_pred)
116        }
117    }
118
119    /// The log link $`g(\mu) = \log(\mu)`$ avoids linear predictors that give negative
120    /// expectations.
121    pub struct Log {}
122    impl Link<Gamma<Log>> for Log {
123        fn func<F: Float>(y: F) -> F {
124            num_traits::Float::ln(y)
125        }
126        fn func_inv<F: Float>(lin_pred: F) -> F {
127            num_traits::Float::exp(lin_pred)
128        }
129    }
130    impl Transform for Log {
131        fn nat_param<F: Float>(lin_pred: Array1<F>) -> Array1<F> {
132            lin_pred.mapv(|x| -num_traits::Float::exp(-x))
133        }
134        fn d_nat_param<F: Float>(lin_pred: &Array1<F>) -> Array1<F> {
135            lin_pred.mapv(|x| num_traits::Float::exp(-x))
136        }
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143    use crate::{error::RegressionResult, model::ModelBuilder};
144    use approx::assert_abs_diff_eq;
145    use ndarray::array;
146
147    /// A simple test where the correct value for the data is known exactly.
148    ///
149    /// With the canonical NegRec link, the MLE satisfies β₀ = -1/ȳ₀ and β₀+β₁ = -1/ȳ₁,
150    /// where ȳ₀ and ȳ₁ are the within-group sample means. Choosing group means 2 and 4
151    /// gives β = [-0.5, 0.25], both exactly representable in f64.
152    #[test]
153    fn gamma_ex() -> RegressionResult<(), f64> {
154        // Group 0 (x=0): y ∈ {1, 3}, ȳ₀ = 2  → β₀       = -1/2 = -0.5
155        // Group 1 (x=1): y ∈ {2, 4, 6}, ȳ₁ = 4 → β₀ + β₁ = -1/4, β₁ = 0.25
156        let beta = array![-0.5, 0.25];
157        let data_x = array![[0.], [0.], [1.0], [1.0], [1.0]];
158        let data_y = array![1.0, 3.0, 2.0, 4.0, 6.0];
159        let model = ModelBuilder::<Gamma>::data(&data_y, &data_x).build()?;
160        let fit = model.fit()?;
161        assert_abs_diff_eq!(beta, fit.result, epsilon = 0.5 * f32::EPSILON as f64);
162        let _cov = fit.covariance()?;
163        Ok(())
164    }
165
166    /// Analogous test using the Log link. With g(μ) = log(μ), the MLE satisfies
167    /// β₀ = log(ȳ₀) and β₁ = log(ȳ₁/ȳ₀). Same group data as gamma_ex gives
168    /// ȳ₀=2, ȳ₁=4, so β = [ln 2, ln 2].
169    #[test]
170    fn gamma_log_link_ex() -> RegressionResult<(), f64> {
171        // Group 0 (x=0): y ∈ {1, 3}, ȳ₀ = 2 → β₀      = ln(2)
172        // Group 1 (x=1): y ∈ {2, 4, 6}, ȳ₁ = 4 → β₀+β₁ = ln(4), β₁ = ln(2)
173        let ln2 = f64::ln(2.);
174        let beta = array![ln2, ln2];
175        let data_x = array![[0.], [0.], [1.0], [1.0], [1.0]];
176        let data_y = array![1.0, 3.0, 2.0, 4.0, 6.0];
177        let model = ModelBuilder::<Gamma<link::Log>>::data(&data_y, &data_x).build()?;
178        let fit = model.fit()?;
179        assert_abs_diff_eq!(beta, fit.result, epsilon = 0.5 * f32::EPSILON as f64);
180        let _cov = fit.covariance()?;
181        Ok(())
182    }
183
184    #[test]
185    // Confirm inverse reciprocal closure.
186    fn neg_rec_closure() {
187        use super::link::NegRec;
188        use crate::link::TestLink;
189        // Note that the positive values aren't good linear predictor values, but they should be
190        // closed under the canonical transformation anyway.
191        let x = array![-360., -12., -5., -1.0, -0.002, 0., 0.5, 20.];
192        NegRec::check_closure(&x);
193        let y = array![1e-5, 0.25, 0.8, 2.5, 10., 256.];
194        NegRec::check_closure_y(&y);
195    }
196
197    // verify closure for the log link.
198    #[test]
199    fn log_closure() {
200        use crate::link::TestLink;
201        use link::Log;
202        let mu_test_vals = array![1e-8, 0.01, 0.1, 0.3, 0.9, 1.8, 4.2, 148.];
203        Log::check_closure_y(&mu_test_vals);
204        let lin_test_vals = array![1e-8, 0.002, 0.5, 2.4, 15., 120.];
205        Log::check_closure(&lin_test_vals);
206    }
207
208    #[test]
209    fn log_nat_par() {
210        use crate::link::TestLink;
211        use link::Log;
212        // nat_param(ω) = -exp(-ω) = g_0(g^{-1}(ω)) = NegRec(exp(ω)) = -1/exp(ω)
213        let lin_test_vals = array![-10., -2., -0.5, 0.0, 0.5, 2., 10.];
214        Log::check_nat_par::<Gamma<link::NegRec>>(&lin_test_vals);
215        Log::check_nat_par_d(&lin_test_vals);
216    }
217}