Skip to main content

shap_rs/
link.rs

1use crate::{Result, ShapError};
2use serde::{Deserialize, Serialize};
3
4/// Output-space transform used while enforcing SHAP local accuracy.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
6pub enum Link {
7    #[default]
8    Identity,
9    Logit,
10}
11impl Link {
12    pub fn forward(self, value: f64) -> Result<f64> {
13        match self {
14            Self::Identity => Ok(value),
15            Self::Logit if value > 0.0 && value < 1.0 => Ok((value / (1.0 - value)).ln()),
16            Self::Logit => Err(ShapError::NumericalError(
17                "logit link requires a value strictly between zero and one".into(),
18            )),
19        }
20    }
21    pub fn inverse(self, value: f64) -> f64 {
22        match self {
23            Self::Identity => value,
24            Self::Logit => {
25                if value >= 0.0 {
26                    1.0 / (1.0 + (-value).exp())
27                } else {
28                    let e = value.exp();
29                    e / (1.0 + e)
30                }
31            }
32        }
33    }
34}