-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlocal.py
More file actions
371 lines (312 loc) · 15.1 KB
/
local.py
File metadata and controls
371 lines (312 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
from __future__ import annotations
import numpy as np
from typing import Tuple
from dte_adj.stratified import (
SimpleStratifiedDistributionEstimator,
AdjustedStratifiedDistributionEstimator,
)
from dte_adj.util import ArrayLike, compute_ldte, compute_lpte, _convert_to_ndarray
class SimpleLocalDistributionEstimator(SimpleStratifiedDistributionEstimator):
"""
A class for computing Local Distribution Treatment Effects (LDTE) and Local Probability
Treatment Effects (LPTE) using simple empirical estimation.
This estimator computes treatment effects that are weighted by treatment propensity
within each stratum, providing estimates that are locally robust to treatment assignment
heterogeneity across strata. It uses empirical methods without ML adjustment.
"""
def __init__(self):
"""
Initializes the SimpleLocalDistributionEstimator.
Returns:
SimpleLocalDistributionEstimator: An instance of the estimator.
"""
super().__init__()
def fit(
self,
covariates: ArrayLike,
treatment_arms: ArrayLike,
treatment_indicator: ArrayLike,
outcomes: ArrayLike,
strata: ArrayLike,
) -> SimpleLocalDistributionEstimator:
"""
Train the SimpleLocalDistributionEstimator.
Args:
covariates: Pre-treatment covariates.
treatment_arms: Treatment assignment variable (Z).
treatment_indicator: Treatment indicator variable (D).
outcomes: Scalar-valued observed outcome.
strata: Stratum indicators.
Returns:
SimpleLocalDistributionEstimator: The fitted estimator.
"""
treatment_indicator = _convert_to_ndarray(treatment_indicator)
super().fit(covariates, treatment_arms, outcomes, strata)
self.treatment_indicator = treatment_indicator
return self
def predict_ldte(
self,
target_treatment_arm: int,
control_treatment_arm: int,
locations: np.ndarray,
alpha: float = 0.05,
verbose: bool = True,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Compute Local Distribution Treatment Effects (LDTE).
LDTE measures the difference in cumulative distribution functions between treatment groups
weighted by treatment propensity within each stratum. This provides estimates that are
locally robust to treatment assignment heterogeneity across strata.
Args:
target_treatment_arm (int): The index of the treatment arm of the treatment group.
control_treatment_arm (int): The index of the treatment arm of the control group.
locations (np.ndarray): Scalar values to be used for computing the cumulative distribution.
alpha (float, optional): Significance level of the confidence bound. Defaults to 0.05.
verbose (bool, optional): Whether to display a progress bar. Defaults to True.
Returns:
Tuple[np.ndarray, np.ndarray, np.ndarray]: A tuple containing:
- Expected LDTEs (np.ndarray): Local treatment effect estimates at each location
- Lower bounds (np.ndarray): Lower confidence interval bounds
- Upper bounds (np.ndarray): Upper confidence interval bounds
Example:
.. code-block:: python
import numpy as np
from sklearn.linear_model import LogisticRegression
from dte_adj import AdjustedLocalDistributionEstimator
# Generate sample data with strata
np.random.seed(42)
X = np.random.randn(1000, 5)
strata = np.random.choice([0, 1], size=1000) # Binary strata
D = np.random.binomial(1, 0.3 + 0.4 * strata, 1000) # Treatment depends on strata
Y = X[:, 0] + 2 * D + strata + np.random.randn(1000)
# Fit local estimator
base_model = LogisticRegression()
estimator = AdjustedLocalDistributionEstimator(base_model)
estimator.fit(X, D, D, Y, strata) # treatment_arms = treatment_indicator for binary case
# Compute LDTE
locations = np.linspace(Y.min(), Y.max(), 20)
ldte, lower, upper = estimator.predict_ldte(
target_treatment_arm=1,
control_treatment_arm=0,
locations=locations
)
print(f"LDTE shape: {ldte.shape}") # Should match locations.shape
print(f"Average LDTE: {ldte.mean():.3f}")
"""
return compute_ldte(
self,
target_treatment_arm,
control_treatment_arm,
locations,
alpha,
verbose,
)
def predict_lpte(
self,
target_treatment_arm: int,
control_treatment_arm: int,
locations: np.ndarray,
alpha: float = 0.05,
verbose: bool = True,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Compute Local Probability Treatment Effects (LPTE).
LPTE measures the difference in probability mass between treatment groups for intervals
defined by consecutive location pairs, weighted by treatment propensity within each stratum.
This provides locally robust estimates of treatment effects on interval probabilities.
Args:
target_treatment_arm (int): The index of the treatment arm of the treatment group.
control_treatment_arm (int): The index of the treatment arm of the control group.
locations (np.ndarray): Scalar values defining interval boundaries for probability computation.
For each interval (locations[i], locations[i+1]], the LPTE is computed.
alpha (float, optional): Significance level of the confidence bound. Defaults to 0.05.
verbose (bool, optional): Whether to display a progress bar. Defaults to True.
Returns:
Tuple[np.ndarray, np.ndarray, np.ndarray]: A tuple containing:
- Expected LPTEs (np.ndarray): Local treatment effect estimates for each interval,
shape (len(locations)-1,)
- Lower bounds (np.ndarray): Lower confidence interval bounds
- Upper bounds (np.ndarray): Upper confidence interval bounds
Example:
.. code-block:: python
import numpy as np
from dte_adj import SimpleLocalDistributionEstimator
# Generate sample data with strata
np.random.seed(42)
X = np.random.randn(1000, 5)
strata = np.random.choice([0, 1], size=1000) # Binary strata
Z = np.random.binomial(1, 0.5, 1000) # Treatment assignment
D = np.random.binomial(1, 0.3 + 0.4 * Z, 1000) # Treatment receipt
Y = X[:, 0] + 2 * D + strata + np.random.randn(1000)
# Fit local estimator
estimator = SimpleLocalDistributionEstimator()
estimator.fit(X, Z, D, Y, strata)
# Define interval boundaries
locations = np.array([-2, -1, 0, 1, 2]) # Creates intervals: (-2,-1], (-1,0], (0,1], (1,2]
# Compute LPTE
lpte, lower, upper = estimator.predict_lpte(
target_treatment_arm=1,
control_treatment_arm=0,
locations=locations
)
print(f"LPTE shape: {lpte.shape}") # Should be (4,) for 4 intervals
print(f"Interval effects: {lpte}")
"""
return compute_lpte(
self,
target_treatment_arm,
control_treatment_arm,
locations,
alpha,
verbose,
)
class AdjustedLocalDistributionEstimator(AdjustedStratifiedDistributionEstimator):
"""
A class for computing Local Distribution Treatment Effects (LDTE) and Local Probability
Treatment Effects (LPTE) using machine learning adjustment.
This estimator combines the benefits of ML adjustment with local treatment effect estimation,
providing precise estimates of treatment effects that are weighted by treatment propensity
within each stratum. It uses cross-fitting to avoid overfitting issues.
"""
def fit(
self,
covariates: ArrayLike,
treatment_arms: ArrayLike,
treatment_indicator: ArrayLike,
outcomes: ArrayLike,
strata: ArrayLike,
) -> AdjustedLocalDistributionEstimator:
"""
Train the AdjustedLocalDistributionEstimator.
Args:
covariates: Pre-treatment covariates.
treatment_arms: Treatment assignment variable (Z).
treatment_indicator: Treatment indicator variable (D).
outcomes: Scalar-valued observed outcome.
strata: Stratum indicators.
Returns:
AdjustedLocalDistributionEstimator: The fitted estimator.
"""
treatment_indicator = _convert_to_ndarray(treatment_indicator)
super().fit(covariates, treatment_arms, outcomes, strata)
self.treatment_indicator = treatment_indicator
return self
def predict_ldte(
self,
target_treatment_arm: int,
control_treatment_arm: int,
locations: np.ndarray,
alpha: float = 0.05,
verbose: bool = True,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Compute Local Distribution Treatment Effects (LDTE) using ML adjustment.
This method combines machine learning adjustment with local treatment effect estimation
to provide precise, locally robust estimates of distributional treatment effects.
Args:
target_treatment_arm (int): The index of the treatment arm of the treatment group.
control_treatment_arm (int): The index of the treatment arm of the control group.
locations (np.ndarray): Scalar values to be used for computing the cumulative distribution.
alpha (float, optional): Significance level of the confidence bound. Defaults to 0.05.
verbose (bool, optional): Whether to display a progress bar. Defaults to True.
Returns:
Tuple[np.ndarray, np.ndarray, np.ndarray]: A tuple containing:
- Expected LDTEs (np.ndarray): Local treatment effect estimates at each location
- Lower bounds (np.ndarray): Lower confidence interval bounds
- Upper bounds (np.ndarray): Upper confidence interval bounds
Example:
.. code-block:: python
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from dte_adj import AdjustedLocalDistributionEstimator
# Generate confounded data with strata
np.random.seed(42)
X = np.random.randn(1000, 5)
strata = np.random.choice([0, 1], size=1000)
# Treatment assignment depends on covariates
Z_prob = 1 / (1 + np.exp(-(X[:, 0] + X[:, 1] + strata)))
Z = np.random.binomial(1, Z_prob, 1000)
D = np.random.binomial(1, 0.3 + 0.4 * Z, 1000)
Y = X.sum(axis=1) + 2 * D + strata + np.random.randn(1000)
# Fit adjusted local estimator
base_model = RandomForestClassifier(n_estimators=100)
estimator = AdjustedLocalDistributionEstimator(base_model, folds=3)
estimator.fit(X, Z, D, Y, strata)
# Compute LDTE with ML adjustment
locations = np.linspace(Y.min(), Y.max(), 20)
ldte, lower, upper = estimator.predict_ldte(
target_treatment_arm=1,
control_treatment_arm=0,
locations=locations
)
print(f"Adjusted LDTE: {ldte.mean():.3f}")
"""
return compute_ldte(
self,
target_treatment_arm,
control_treatment_arm,
locations,
alpha,
verbose,
)
def predict_lpte(
self,
target_treatment_arm: int,
control_treatment_arm: int,
locations: np.ndarray,
alpha: float = 0.05,
verbose: bool = True,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Compute Local Probability Treatment Effects (LPTE) using ML adjustment.
This method combines machine learning adjustment with local treatment effect estimation
to provide precise estimates of treatment effects on interval probabilities.
Args:
target_treatment_arm (int): The index of the treatment arm of the treatment group.
control_treatment_arm (int): The index of the treatment arm of the control group.
locations (np.ndarray): Scalar values defining interval boundaries for probability computation.
For each interval (locations[i], locations[i+1]], the LPTE is computed.
alpha (float, optional): Significance level of the confidence bound. Defaults to 0.05.
verbose (bool, optional): Whether to display a progress bar. Defaults to True.
Returns:
Tuple[np.ndarray, np.ndarray, np.ndarray]: A tuple containing:
- Expected LPTEs (np.ndarray): Local treatment effect estimates for each interval,
shape (len(locations)-1,)
- Lower bounds (np.ndarray): Lower confidence interval bounds
- Upper bounds (np.ndarray): Upper confidence interval bounds
Example:
.. code-block:: python
import numpy as np
from sklearn.linear_model import LogisticRegression
from dte_adj import AdjustedLocalDistributionEstimator
# Generate confounded data with strata
np.random.seed(42)
X = np.random.randn(1000, 5)
strata = np.random.choice([0, 1], size=1000)
# Treatment assignment depends on covariates
Z_prob = 1 / (1 + np.exp(-(X[:, 0] + strata)))
Z = np.random.binomial(1, Z_prob, 1000)
D = np.random.binomial(1, 0.3 + 0.4 * Z, 1000)
Y = X.sum(axis=1) + 2 * D + strata + np.random.randn(1000)
# Fit adjusted local estimator
base_model = LogisticRegression()
estimator = AdjustedLocalDistributionEstimator(base_model, folds=3)
estimator.fit(X, Z, D, Y, strata)
# Define interval boundaries
locations = np.array([-2, -1, 0, 1, 2])
# Compute LPTE with ML adjustment
lpte, lower, upper = estimator.predict_lpte(
target_treatment_arm=1,
control_treatment_arm=0,
locations=locations
)
print(f"Adjusted LPTE: {lpte}")
"""
return compute_lpte(
self,
target_treatment_arm,
control_treatment_arm,
locations,
alpha,
verbose,
)