Skip to main content

dml_core/model/
plr.rs

1//! Partially linear regression (PLR):
2//!
3//! ```text
4//! Y = θ·D + g(X) + ε,   E[ε | D, X] = 0
5//! D = m(X) + v,         E[v | X] = 0
6//! ```
7
8use ndarray::Array1;
9
10use super::{
11    dml_model_api, CateSignal, LinearScoreModel, NuisanceTarget, ScoreEstimate, ScoreInput,
12};
13use crate::crossfit::{cross_fit_predict, Fold, SampleSplitting};
14use crate::error::{DmlError, Result};
15use crate::learner::Regressor;
16use crate::score::LinearScore;
17use crate::sensitivity::{Nu2Parts, SensitivityParts};
18
19/// Orthogonal score used by [`Plr`].
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21pub enum PlrScore {
22    /// `ψ = (Y − ℓ(X) − θ(D − m(X)))·(D − m(X))` with `ℓ(X) = E[Y | X]`.
23    #[default]
24    PartiallingOut,
25    /// `ψ = (Y − θD − g(X))·(D − m(X))`, with `g` fitted on `Y − θ̃D` for a
26    /// preliminary partialling-out estimate `θ̃`.
27    IvType,
28}
29
30/// PLR estimator: `ml_l` learns `E[Y | X]`, `ml_m` learns `E[D | X]`, and
31/// the optional `ml_g` learns `g(X)` for the IV-type score.
32pub struct Plr {
33    ml_l: Box<dyn Regressor>,
34    ml_m: Box<dyn Regressor>,
35    ml_g: Option<Box<dyn Regressor>>,
36    score: PlrScore,
37    splitting: SampleSplitting,
38}
39
40impl Plr {
41    pub fn new(ml_l: impl Regressor + 'static, ml_m: impl Regressor + 'static) -> Self {
42        Self::from_boxed(Box::new(ml_l), Box::new(ml_m))
43    }
44
45    /// Like [`Plr::new`] for learners that are already boxed trait objects.
46    pub fn from_boxed(ml_l: Box<dyn Regressor>, ml_m: Box<dyn Regressor>) -> Self {
47        Self {
48            ml_l,
49            ml_m,
50            ml_g: None,
51            score: PlrScore::default(),
52            splitting: SampleSplitting::default(),
53        }
54    }
55
56    pub fn score(mut self, score: PlrScore) -> Self {
57        self.score = score;
58        self
59    }
60
61    /// Learner for `g(X)` in the IV-type score (default: a fresh copy of `ml_l`).
62    pub fn ml_g(mut self, ml_g: impl Regressor + 'static) -> Self {
63        self.ml_g = Some(Box::new(ml_g));
64        self
65    }
66
67    pub fn ml_g_boxed(mut self, ml_g: Box<dyn Regressor>) -> Self {
68        self.ml_g = Some(ml_g);
69        self
70    }
71
72    dml_model_api!();
73}
74
75impl LinearScoreModel for Plr {
76    fn name(&self) -> String {
77        match self.score {
78            PlrScore::PartiallingOut => "PLR (partialling out)".into(),
79            PlrScore::IvType => "PLR (IV-type)".into(),
80        }
81    }
82
83    fn estimate_score(&self, input: &ScoreInput<'_>, folds: &[Fold]) -> Result<ScoreEstimate> {
84        let ScoreInput { y, d, x, .. } = *input;
85        let l_hat = cross_fit_predict(self.ml_l.as_ref(), x, y, folds)?;
86        let m_hat = cross_fit_predict(self.ml_m.as_ref(), x, d, folds)?;
87        let v: Array1<f64> = &d - &m_hat;
88        if v.dot(&v) <= f64::EPSILON * d.dot(&d).max(1.0) {
89            return Err(DmlError::InvalidArgument(
90                "treatment residuals are zero: D is fully explained by X".into(),
91            ));
92        }
93        let u: Array1<f64> = &y - &l_hat;
94
95        match self.score {
96            PlrScore::PartiallingOut => {
97                // Outcome residual y − ℓ̂ − θ(d − m̂); ν² = 1 / mean((d − m̂)²).
98                let parts = SensitivityParts {
99                    outcome_residual: u.clone(),
100                    theta_factor: Some(v.clone()),
101                    riesz: Array1::zeros(v.len()),
102                    nu2: Nu2Parts::InverseMeanSquare(v.clone()),
103                };
104                Ok(ScoreEstimate::new(
105                    LinearScore::new(-(&v * &v), &v * &u)?,
106                    vec![("ml_l", l_hat), ("ml_m", m_hat)],
107                )
108                .with_sensitivity(parts)
109                .with_targets(vec![
110                    NuisanceTarget::regression("ml_l", y.to_owned()),
111                    NuisanceTarget::regression("ml_m", d.to_owned()),
112                ])
113                // CATE: regress y − ℓ̂ on the basis scaled by d − m̂ (as DoubleML).
114                .with_cate_signal(CateSignal {
115                    signal: u,
116                    theta_factor: None,
117                    basis_scale: Some(v),
118                    is_effect: false,
119                }))
120            }
121            PlrScore::IvType => {
122                let theta_init = u.dot(&v) / v.dot(&v);
123                let target: Array1<f64> = &y - &(theta_init * &d);
124                let fresh_l;
125                let ml_g = match &self.ml_g {
126                    Some(g) => g.as_ref(),
127                    None => {
128                        fresh_l = self.ml_l.fresh();
129                        fresh_l.as_ref()
130                    }
131                };
132                let g_hat = cross_fit_predict(ml_g, x, target.view(), folds)?;
133                let resid_g: Array1<f64> = &y - &g_hat;
134                // Outcome residual y − ĝ − θd.
135                let parts = SensitivityParts {
136                    outcome_residual: resid_g.clone(),
137                    theta_factor: Some(d.to_owned()),
138                    riesz: Array1::zeros(v.len()),
139                    nu2: Nu2Parts::InverseMeanSquare(v.clone()),
140                };
141                // CATE: regress y − ĝ − θ·m̂ on the basis scaled by d − m̂ (as DoubleML).
142                let cate = CateSignal {
143                    signal: resid_g.clone(),
144                    theta_factor: Some(m_hat.clone()),
145                    basis_scale: Some(v.clone()),
146                    is_effect: false,
147                };
148                Ok(ScoreEstimate::new(
149                    LinearScore::new(-(&v * &d), &v * &resid_g)?,
150                    vec![("ml_l", l_hat), ("ml_m", m_hat), ("ml_g", g_hat)],
151                )
152                .with_sensitivity(parts)
153                .with_targets(vec![
154                    NuisanceTarget::regression("ml_l", y.to_owned()),
155                    NuisanceTarget::regression("ml_m", d.to_owned()),
156                    NuisanceTarget::regression("ml_g", target),
157                ])
158                .with_cate_signal(cate))
159            }
160        }
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167    use crate::data::DmlData;
168    use crate::learner::Ols;
169    use ndarray::{Array1, Array2};
170
171    fn toy_data() -> DmlData {
172        let n = 60;
173        let x = Array2::from_shape_fn((n, 2), |(i, j)| ((i * 7 + j * 3) % 11) as f64);
174        let d: Array1<f64> = (0..n)
175            .map(|i| 0.3 * x[[i, 0]] + ((i * 13) % 5) as f64 - 2.0)
176            .collect();
177        let y: Array1<f64> = (0..n)
178            .map(|i| 0.5 * d[i] + x[[i, 1]] + ((i * 17) % 3) as f64 - 1.0)
179            .collect();
180        DmlData::new(y, d, x).unwrap()
181    }
182
183    #[test]
184    fn coef_matches_residual_formula() {
185        let data = toy_data();
186        let fit = Plr::new(Ols::new(), Ols::new()).seed(3).fit(&data).unwrap();
187        let u = &data.y() - &fit.prediction("ml_l", 0, 0).unwrap();
188        let v = &data.treatment(0) - &fit.prediction("ml_m", 0, 0).unwrap();
189        assert!((fit.coef()[0] - u.dot(&v) / v.dot(&v)).abs() < 1e-12);
190        // The score is zero on average at the DML2 solution.
191        assert!(fit.psi().sum().abs() < 1e-10);
192    }
193
194    #[test]
195    fn iv_type_with_linear_learners_is_close_to_partialling_out() {
196        let data = toy_data();
197        let po = Plr::new(Ols::new(), Ols::new()).fit(&data).unwrap();
198        let iv = Plr::new(Ols::new(), Ols::new())
199            .score(PlrScore::IvType)
200            .fit(&data)
201            .unwrap();
202        assert!(iv.prediction("ml_g", 0, 0).is_some());
203        assert!((po.coef()[0] - iv.coef()[0]).abs() < 0.05);
204    }
205
206    #[test]
207    fn rejects_treatment_explained_by_x() {
208        let x = Array2::from_shape_fn((20, 1), |(i, _)| i as f64);
209        let d = x.column(0).mapv(|v| 2.0 * v + 1.0);
210        let y = d.mapv(|v| v * 0.5);
211        let data = DmlData::new(y, d, x).unwrap();
212        assert!(Plr::new(Ols::new(), Ols::new()).fit(&data).is_err());
213    }
214}