-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstratified.py
More file actions
420 lines (376 loc) · 18.3 KB
/
stratified.py
File metadata and controls
420 lines (376 loc) · 18.3 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
from __future__ import annotations
import numpy as np
from typing import Tuple, Any
from copy import deepcopy
from tqdm.auto import tqdm
from dte_adj.base import DistributionEstimatorBase
from dte_adj.util import ArrayLike, _convert_to_ndarray
class SimpleStratifiedDistributionEstimator(DistributionEstimatorBase):
"""A class is for estimating the empirical distribution function and computing the Distributional parameters for CAR."""
def fit(
self,
covariates: ArrayLike,
treatment_arms: ArrayLike,
outcomes: ArrayLike,
strata: ArrayLike,
) -> DistributionEstimatorBase:
"""
Train the DistributionEstimatorBase.
Args:
covariates: Pre-treatment covariates.
treatment_arms: The index of the treatment arm.
outcomes: Scalar-valued observed outcome.
strata: Stratum indicators.
Returns:
DistributionEstimatorBase: The fitted estimator.
"""
covariates = _convert_to_ndarray(covariates)
treatment_arms = _convert_to_ndarray(treatment_arms)
outcomes = _convert_to_ndarray(outcomes)
strata = _convert_to_ndarray(strata)
if covariates.shape[0] != treatment_arms.shape[0]:
raise ValueError("The shape of covariates and treatment_arm should be same")
if covariates.shape[0] != outcomes.shape[0]:
raise ValueError("The shape of covariates and outcome should be same")
self.covariates = covariates
self.treatment_arms = treatment_arms
self.outcomes = outcomes
self.strata = strata
return self
def _compute_cumulative_distribution(
self,
target_treatment_arm: int,
locations: np.ndarray,
covariates: np.ndarray,
treatment_arms: np.ndarray,
outcomes: np.array,
verbose: bool = False,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Compute the cumulative distribution values.
Args:
target_treatment_arm (int): The index of the treatment arm.
locations (np.ndarray): Scalar values to be used for computing the cumulative distribution.
covariates: (np.ndarray): An array of covariates variables in the observed data.
treatment_arm (np.ndarray): An array of treatment arms in the observed data.
outcomes (np.ndarray): An array of outcomes in the observed data
verbose (bool): Whether to display a progress bar.
Returns:
Tuple of numpy arrays:
- np.ndarray: Unconditional cumulative distribution values.
- np.ndarray: Adjusted cumulative distribution for each observation.
- np.ndarray: Conditional cumulative distribution for each observation.
"""
n_records = outcomes.shape[0]
n_loc = locations.shape[0]
prediction = np.zeros((n_records, n_loc))
treatment_mask = treatment_arms == target_treatment_arm
strata = self.strata
s_list = np.unique(strata)
w_s = {}
for s in s_list:
s_mask = strata == s
w_s[s] = (s_mask & treatment_mask).sum() / s_mask.sum()
for j in range(n_records):
s = strata[j]
prediction[j] = (outcomes[j] <= locations) / w_s[s] * treatment_mask[j]
unconditional_pred = {s: prediction[s == strata].mean(axis=0) for s in s_list}
conditional_prediction = np.array([unconditional_pred[s] for s in strata])
weights = np.array([w_s[s] for s in strata])[:, np.newaxis]
prediction = (
(outcomes[:, np.newaxis] <= locations) - conditional_prediction
) / weights * treatment_mask[:, np.newaxis] + conditional_prediction
return prediction.mean(axis=0), prediction, conditional_prediction
def _compute_interval_probability(
self,
target_treatment_arm: int,
locations: np.ndarray,
covariates: np.ndarray,
treatment_arms: np.ndarray,
outcomes: np.array,
verbose: bool = False,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Compute the interval probabilities.
Args:
target_treatment_arm (int): The index of the treatment arm.
locations (np.ndarray): Scalar values to be used for computing the interval probabilities.
covariates: (np.ndarray): An array of covariates variables in the observed data.
treatment_arm (np.ndarray): An array of treatment arms in the observed data.
outcomes (np.ndarray): An array of outcomes in the observed data
verbose (bool): Whether to display a progress bar.
Returns:
Tuple of numpy arrays:
- np.ndarray: Estimated unconditional interval probabilities.
- np.ndarray: Adjusted for each observation.
- np.ndarray: Conditional for each observation.
"""
n_records = outcomes.shape[0]
n_loc = locations.shape[0]
prediction = np.zeros((n_records, n_loc))
treatment_mask = treatment_arms == target_treatment_arm
strata = self.strata
s_list = np.unique(strata)
w_s = {}
for s in s_list:
s_mask = strata == s
w_s[s] = (s_mask & treatment_mask).sum() / s_mask.sum()
for i, outcome in enumerate(locations):
for j in range(n_records):
s = strata[j]
prediction[j, i] = (outcomes[j] <= outcome) / w_s[s] * treatment_mask[j]
unconditional_pred = {s: prediction[s == strata].mean(axis=0) for s in s_list}
conditional_prediction = np.array([unconditional_pred[s] for s in strata])
weights = np.array([w_s[s] for s in strata])[:, np.newaxis]
prediction = (
(outcomes[:, np.newaxis] <= locations) - conditional_prediction
) / weights * treatment_mask[:, np.newaxis] + conditional_prediction
cdf = prediction.mean(axis=0)
return (
cdf[1:] - cdf[:-1],
prediction[:, 1:] - prediction[:, :-1],
conditional_prediction[:, 1:] - conditional_prediction[:, :-1],
)
class AdjustedStratifiedDistributionEstimator(DistributionEstimatorBase):
"""A class is for estimating the adjusted distribution function and computing the Distributional parameters for CAR."""
def __init__(self, base_model: Any, folds=3, is_multi_task=False):
"""
Initializes the AdjustedDistributionEstimator.
Args:
base_model (scikit-learn estimator): The base model implementing used for conditional distribution function estimators. The model should implement fit(data, targets) and predict_proba(data).
folds (int): The number of folds for cross-fitting.
is_multi_task(bool): Whether to use multi-task learning. If True, your base model needs to support multi-task prediction (n_samples, n_features) -> (n_samples, n_targets).
Returns:
AdjustedDistributionEstimator: An instance of the estimator.
"""
if (not hasattr(base_model, "predict")) and (
not hasattr(base_model, "predict_proba")
):
raise ValueError(
"Base model should implement either predict_proba or predict"
)
self.base_model = base_model
self.folds = folds
self.is_multi_task = is_multi_task
super().__init__()
def fit(
self,
covariates: ArrayLike,
treatment_arms: ArrayLike,
outcomes: ArrayLike,
strata: ArrayLike,
) -> DistributionEstimatorBase:
"""
Train the DistributionEstimatorBase.
Args:
covariates: Pre-treatment covariates.
treatment_arms: The index of the treatment arm.
outcomes: Scalar-valued observed outcome.
strata: Stratum indicators.
Returns:
DistributionEstimatorBase: The fitted estimator.
"""
covariates = _convert_to_ndarray(covariates)
treatment_arms = _convert_to_ndarray(treatment_arms)
outcomes = _convert_to_ndarray(outcomes)
strata = _convert_to_ndarray(strata)
if covariates.shape[0] != treatment_arms.shape[0]:
raise ValueError("The shape of covariates and treatment_arm should be same")
if covariates.shape[0] != outcomes.shape[0]:
raise ValueError("The shape of covariates and outcome should be same")
self.covariates = covariates
self.treatment_arms = treatment_arms
self.outcomes = outcomes
self.strata = strata
return self
def _compute_cumulative_distribution(
self,
target_treatment_arm: int,
locations: np.ndarray,
covariates: np.ndarray,
treatment_arms: np.ndarray,
outcomes: np.array,
verbose: bool = False,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Compute the cumulative distribution values.
Args:
target_treatment_arm (int): The index of the treatment arm.
locations (np.ndarray): Scalar values to be used for computing the cumulative distribution.
covariates: (np.ndarray): An array of covariates variables in the observed data.
treatment_arm (np.ndarray): An array of treatment arms in the observed data.
outcomes (np.ndarray): An array of outcomes in the observed data
verbose (bool): Whether to display a progress bar.
Returns:
Tuple of numpy arrays:
- np.ndarray: Unconditional cumulative distribution values.
- np.ndarray: Adjusted cumulative distribution for each observation.
- np.ndarray: Conditional cumulative distribution for each observation.
"""
n_records = outcomes.shape[0]
n_loc = locations.shape[0]
superset_prediction = np.zeros((n_records, n_loc))
prediction = np.zeros((n_records, n_loc))
treatment_mask = treatment_arms == target_treatment_arm
folds = np.random.randint(self.folds, size=n_records)
strata = self.strata
s_list = np.unique(strata)
if self.is_multi_task:
binomial = (outcomes.reshape(-1, 1) <= locations) * 1 # (n_records, n_loc)
fold_iter = range(self.folds)
if verbose:
fold_iter = tqdm(fold_iter, desc="Cross-fitting (multi-task)")
for fold in fold_iter:
fold_mask = (folds != fold) & treatment_mask
for s in s_list:
s_mask = strata == s
weight = (s_mask & treatment_mask).sum() / s_mask.sum()
superset_mask = (folds == fold) & s_mask
subset_train_mask = (folds != fold) & s_mask & treatment_mask
covariates_train = covariates[subset_train_mask]
binomial_train = binomial[subset_train_mask]
if len(np.unique(binomial_train)) > 1:
self.model = deepcopy(self.base_model)
self.model.fit(covariates_train, binomial_train)
pred = self._compute_model_prediction(
self.model, covariates[superset_mask]
)
prediction[superset_mask] = (
pred
+ treatment_mask[superset_mask].reshape(-1, 1)
* (binomial[superset_mask] - pred)
/ weight
)
superset_prediction[superset_mask] = pred
else:
loc_iter = enumerate(locations)
if verbose:
loc_iter = tqdm(loc_iter, total=len(locations), desc="Computing CDF")
for i, location in loc_iter:
binomial = (outcomes <= location) * 1 # (n_records)
for fold in range(self.folds):
fold_mask = (folds != fold) & treatment_mask
covariates_train = covariates[fold_mask]
binomial_train = binomial[fold_mask]
# Pool the records across strata and train the model
if len(np.unique(binomial_train)) > 1:
self.model = deepcopy(self.base_model)
self.model.fit(covariates_train, binomial_train)
for s in s_list:
s_mask = strata == s
weight = (s_mask & treatment_mask).sum() / s_mask.sum()
superset_mask = (folds == fold) & s_mask
subset_train_mask = (folds != fold) & s_mask & treatment_mask
covariates_train = covariates[subset_train_mask]
binomial_train = binomial[subset_train_mask]
# TODO: revisit the logic here
if len(np.unique(binomial_train)) > 1:
# self.model = deepcopy(self.base_model)
# self.model.fit(covariates_train, binomial_train)
pass
else:
pred = binomial_train[0]
superset_prediction[superset_mask, i] = pred
prediction[superset_mask, i] = (
pred
+ treatment_mask[superset_mask]
* (binomial[superset_mask] - pred)
/ weight
)
continue
pred = self._compute_model_prediction(
self.model, covariates[superset_mask]
)
prediction[superset_mask, i] = (
pred
+ treatment_mask[superset_mask]
* (binomial[superset_mask] - pred)
/ weight
)
superset_prediction[superset_mask, i] = pred
return prediction.mean(axis=0), prediction, superset_prediction
def _compute_interval_probability(
self,
target_treatment_arm: int,
locations: np.ndarray,
covariates: np.ndarray,
treatment_arms: np.ndarray,
outcomes: np.array,
verbose: bool = False,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Compute the interval probabilities.
Args:
target_treatment_arm (int): The index of the treatment arm.
locations (np.ndarray): Scalar values to be used for computing the cumulative distribution.
covariates: (np.ndarray): An array of covariates variables in the observed data.
treatment_arm (np.ndarray): An array of treatment arms in the observed data.
outcomes (np.ndarray): An array of outcomes in the observed data
verbose (bool): Whether to display a progress bar.
Returns:
Tuple of numpy arrays:
- np.ndarray: Unconditional interval probabilities.
- np.ndarray: Adjusted interval probabilities for each observation.
- np.ndarray: Conditional interval probabilities for each observation.
"""
n_records = outcomes.shape[0]
n_loc = locations.shape[0]
superset_prediction = np.zeros((n_records, n_loc - 1))
prediction = np.zeros((n_records, n_loc - 1))
treatment_mask = treatment_arms == target_treatment_arm
folds = np.random.randint(self.folds, size=n_records)
strata = self.strata
s_list = np.unique(strata)
binominals = (outcomes[:, np.newaxis] <= locations) * 1 # (n_records, n_loc)
interval_iter = range(len(locations) - 1)
if verbose:
interval_iter = tqdm(interval_iter, desc="Computing interval prob.")
for i in interval_iter:
binomial = binominals[:, i + 1] - binominals[:, i]
for fold in range(self.folds):
fold_mask = (folds != fold) & treatment_mask
covariates_train = covariates[fold_mask]
binomial_train = binomial[fold_mask]
if len(np.unique(binomial_train)) > 1:
self.model = deepcopy(self.base_model)
self.model.fit(covariates_train, binomial_train)
for s in s_list:
s_mask = strata == s
weight = (s_mask & treatment_mask).sum() / s_mask.sum()
superset_mask = (folds == fold) & s_mask
subset_train_mask = (folds != fold) & s_mask & treatment_mask
covariates_train = covariates[subset_train_mask]
binomial_train = binomial[subset_train_mask]
if len(np.unique(binomial_train)) == 1:
pred = binomial_train[0]
superset_prediction[superset_mask, i] = pred
prediction[superset_mask, i] = (
pred
+ treatment_mask[superset_mask]
* (binomial[superset_mask] - pred)
/ weight
)
continue
pred = self._compute_model_prediction(
self.model, covariates[superset_mask]
)
prediction[superset_mask, i] = (
pred
+ treatment_mask[superset_mask]
* (binomial[superset_mask] - pred)
/ weight
)
superset_prediction[superset_mask, i] = pred
return prediction.mean(axis=0), prediction, superset_prediction
def _compute_model_prediction(self, model, covariates: np.ndarray) -> np.ndarray:
if hasattr(model, "predict_proba"):
if self.is_multi_task:
# suppose the shape of prediction is (n_records, n_locations)
return model.predict_proba(covariates)
probabilities = model.predict_proba(covariates)
if probabilities.ndim == 1:
# when the shape of prediction is (n_records)
return probabilities
# when the shape of prediction is (n_records, 2)
return probabilities[:, 1]
else:
return model.predict(covariates)