-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdr_crn.py
379 lines (298 loc) · 12.6 KB
/
dr_crn.py
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
import numpy as np
import torch
import torch.nn as nn
from global_config import DEVICE
def mmd2_rbf(Xc, Xt, sig):
"""
https://github.com/clinicalml/cfrnet/blob/master/cfr/cfr_net.py
Computes the l2-RBF MMD for X given t
"""
p = 0.5
Kcc = torch.exp(-pdist2sq(Xc, Xc) / (sig ** 2))
Kct = torch.exp(-pdist2sq(Xc, Xt) / (sig ** 2))
Ktt = torch.exp(-pdist2sq(Xt, Xt) / (sig ** 2))
m = Xc.shape[0] * 1.0
n = Xt.shape[0] * 1.0
if m < 2 or n < 2:
return 0.0
mmd = ((1.0 - p) ** 2) / (m * (m - 1.0)) * (torch.sum(Kcc) - m)
mmd = mmd + (p ** 2) / (n * (n - 1.0)) * (torch.sum(Ktt) - n)
mmd = mmd - 2.0 * p * (1.0 - p) / (m * n) * torch.sum(Kct)
mmd = 4.0 * mmd
return mmd
def pdist2sq(X, Y):
""" Computes the squared Euclidean distance between all pairs x in X, y in Y """
C = -2 * torch.matmul(X, Y.T)
# print('X', X.shape)
nx = torch.sum(X ** 2, dim=1).unsqueeze(1)
ny = torch.sum(Y ** 2, dim=1).unsqueeze(1)
D = (C + ny.T) + nx
return D
class TarNet(nn.Module):
def __init__(self, n_confounder, n_cause, n_outcome, n_hidden, mmd_sigma=0.0, lam_mmd=0.0, device=DEVICE):
super().__init__()
assert n_outcome == 1
self.n_treatment = int(np.power(2, n_cause))
self.mmd_sigma = mmd_sigma
self.lam_mmd = lam_mmd
self.encoder = nn.Sequential(
nn.Linear(n_confounder, n_hidden), nn.ReLU(), nn.Linear(n_hidden, n_hidden), nn.ReLU(),
).to(device)
heads = []
for i in range(self.n_treatment):
heads.append(nn.Sequential(nn.Linear(n_hidden, n_hidden), nn.ReLU(), nn.Linear(n_hidden, 1)).to(device))
self.heads = nn.ModuleList(heads)
def forward(self, input_mat): # pylint: disable=arguments-differ
# confounder, cause indicator
x = input_mat[:, :-1]
cause = input_mat[:, -1].unsqueeze(-1).to(torch.long)
cause_mat = torch.zeros(x.shape[0], self.n_treatment).to(x)
cause_mat.scatter_(1, cause, 1)
latent = self.encoder(x)
predictions = []
for i in range(self.n_treatment):
y_hat = self.heads[i](latent)
predictions.append(y_hat)
prediction = torch.cat(predictions, dim=-1)
prediction_selected = torch.sum(prediction * cause_mat, dim=1).unsqueeze(-1)
if self.lam_mmd == 0.0:
return prediction_selected
else:
# calculate mmd
cause_np = cause.squeeze().cpu().numpy()
uniques, counts = np.unique(cause_np, return_counts=True)
uniques = uniques[counts > 1]
if len(uniques) < 2:
print("uniques", uniques)
print("counts", counts)
return prediction_selected, 0
mmd = 0
for i in range(len(uniques)):
for j in range(i + 1, len(uniques)):
x1 = latent[cause.squeeze() == uniques[i]]
x2 = latent[cause.squeeze() == uniques[j]]
mmd = mmd + mmd2_rbf(x1, x2, self.mmd_sigma)
return prediction_selected, mmd
def loss(self, y_pred, y):
# use for mmd only
y_pred, mmd = y_pred
rmse = nn.MSELoss()
return rmse(y_pred, y) + self.lam_mmd * mmd
class DR_CRN(nn.Module):
def __init__(
self,
single_cause_index,
n_confounder,
n_cause,
n_outcome,
n_confounder_rep,
n_outcome_rep,
mmd_sigma,
lam_factual,
lam_propensity,
lam_mmd,
linear=False,
binary_outcome=False,
device=DEVICE,
):
super().__init__()
self.single_cause_index = single_cause_index
self.n_confounder = n_confounder
self.n_cause = n_cause
self.n_outcome = n_outcome
self.mmd_sigma = mmd_sigma
self.lam_factual = lam_factual
self.lam_propensity = lam_propensity
self.binary_outcome = binary_outcome
self.lam_mmd = lam_mmd
n_input = n_confounder + n_cause - 1
self.n_x = n_confounder + n_cause
# two representation networks
if linear:
self.confounder_rep_net = nn.Sequential(nn.Linear(n_input, n_confounder_rep),).to(device)
self.outcome_rep_net = nn.Sequential(nn.Linear(n_input, n_outcome_rep),).to(device)
else:
self.confounder_rep_net = nn.Sequential(
nn.Linear(n_input, n_input + 1), nn.ReLU(), nn.Linear(n_input + 1, n_confounder_rep),
).to(device)
self.outcome_rep_net = nn.Sequential(
nn.Linear(n_input, n_input + 1), nn.ReLU(), nn.Linear(n_input + 1, n_outcome_rep),
).to(device)
# propensity network
if linear:
self.propensity_net = nn.Sequential(nn.Linear(n_confounder_rep, 2), nn.LogSoftmax(dim=-1)).to(device)
else:
self.propensity_net = nn.Sequential(
nn.Linear(n_confounder_rep, n_confounder_rep + 1),
nn.ReLU(),
nn.Linear(n_confounder_rep + 1, 2),
nn.LogSoftmax(dim=-1),
).to(device)
# outcome regression network
if not self.binary_outcome:
if linear:
self.outcome_net0 = nn.Sequential(nn.Linear(n_confounder_rep + n_outcome_rep, n_outcome),).to(device)
self.outcome_net1 = nn.Sequential(nn.Linear(n_confounder_rep + n_outcome_rep, n_outcome),).to(device)
else:
self.outcome_net0 = nn.Sequential(
nn.Linear(n_confounder_rep + n_outcome_rep, n_confounder_rep + n_outcome_rep + 1),
nn.ReLU(),
nn.Linear(n_confounder_rep + n_outcome_rep + 1, n_outcome),
).to(device)
self.outcome_net1 = nn.Sequential(
nn.Linear(n_confounder_rep + n_outcome_rep, n_confounder_rep + n_outcome_rep + 1),
nn.ReLU(),
nn.Linear(n_confounder_rep + n_outcome_rep + 1, n_outcome),
).to(device)
else:
if linear:
pass
else:
# probability
self.outcome_net0 = nn.Sequential(
nn.Linear(n_confounder_rep + n_outcome_rep, n_outcome), nn.Sigmoid()
).to(device)
self.outcome_net1 = nn.Sequential(
nn.Linear(n_confounder_rep + n_outcome_rep, n_outcome), nn.Sigmoid()
).to(device)
def forward(self, x): # pylint: disable=arguments-differ
# slice single cause
single_cause = x[:, self.single_cause_index : (self.single_cause_index + 1)]
# print('single_cause', single_cause.shape)
if self.single_cause_index == 0:
all_confounders = x[:, 1:]
elif self.single_cause_index == self.n_x - 1 or self.single_cause_index == -1:
all_confounders = x[:, :-1]
else:
all_confounders = torch.cat(
[x[:, : self.single_cause_index], x[:, (self.single_cause_index + 1) :]], dim=-1
)
assert all_confounders.shape[1] == self.n_x - 1
# get representations
confounder_rep = self.confounder_rep_net(all_confounders)
outcome_rep = self.outcome_rep_net(all_confounders)
# print('confounder_rep', confounder_rep.shape)
# print('outcome_rep', outcome_rep.shape)
combined_rep = torch.cat([confounder_rep, outcome_rep], dim=-1)
treated_mask = single_cause == 1.0
treated_label = treated_mask.to(torch.long)
# treated_mask = torch.cat([treated_mask] * confounder_rep.shape[1], dim=1)
rep_treated = confounder_rep[treated_mask.squeeze()]
rep_control = confounder_rep[~treated_mask.squeeze()]
log_propensity = self.propensity_net(confounder_rep)
outcome1 = self.outcome_net1(combined_rep)
outcome0 = self.outcome_net0(combined_rep)
outcome = outcome1 * single_cause + outcome0 * (1 - single_cause)
mmd = mmd2_rbf(rep_treated, rep_control, self.mmd_sigma)
return outcome, log_propensity, mmd, treated_label
def loss(self, y_pred, y):
# y_pred is the output of forward
# print('y_pred', len(y_pred))
y_hat, log_propensity, mmd, treated_label = y_pred
# factual loss
if not self.binary_outcome:
rmse = nn.MSELoss()
# print('y_hat', y_hat.shape)
# print('y', y.shape)
error = torch.sqrt(rmse(y_hat, y))
else:
neg_y_hat = 1.0 - y_hat
# N, 2, D_out
y_hat_2d = torch.cat([y_hat[:, None, :], neg_y_hat[:, None, :]], dim=1)
y_hat_2d = torch.log(y_hat_2d + 1e-9)
outcome_nll_loss = nn.NLLLoss()
# N, D_out
y = y.to(torch.long)
error = outcome_nll_loss(y_hat_2d, y)
# propensity loss
nll_loss = nn.NLLLoss()
nll = nll_loss(log_propensity, treated_label.squeeze())
loss = error * self.lam_factual + nll * self.lam_propensity + mmd * self.lam_mmd
# print('error', error.item())
# print('nll', nll.item())
# print('mmd', mmd.item())
return loss
class DR_CRN_Multicause(nn.Module):
def __init__(
self,
n_confounder,
n_cause,
n_outcome,
n_confounder_rep,
n_outcome_rep,
mmd_sigma=0.0,
lam_mmd=0.0,
device=DEVICE,
):
super().__init__()
assert n_outcome == 1
self.n_treatment = int(np.power(2, n_cause))
self.mmd_sigma = mmd_sigma
self.lam_mmd = lam_mmd
n_input = n_confounder
self.confounder_rep_net = nn.Sequential(
nn.Linear(n_input, n_input + 1), nn.ReLU(), nn.Linear(n_input + 1, n_confounder_rep),
).to(device)
self.outcome_rep_net = nn.Sequential(
nn.Linear(n_input, n_input + 1), nn.ReLU(), nn.Linear(n_input + 1, n_outcome_rep),
).to(device)
self.propensity_net = nn.Sequential(
nn.Linear(n_confounder_rep, n_confounder_rep + 1),
nn.ReLU(),
nn.Linear(n_confounder_rep + 1, self.n_treatment),
nn.LogSoftmax(dim=-1),
).to(device)
heads = []
for i in range(self.n_treatment):
heads.append(
nn.Sequential(
# nn.Linear(n_outcome_rep + n_confounder_rep, n_outcome_rep + n_confounder_rep + 1),
# nn.ReLU(),
nn.Linear(n_outcome_rep + n_confounder_rep, 1)
).to(device)
)
self.heads = nn.ModuleList(heads)
def forward(self, input_mat): # pylint: disable=arguments-differ
# confounder, cause indicator
x = input_mat[:, :-1]
cause = input_mat[:, -1].unsqueeze(-1).to(torch.long)
cause_mat = torch.zeros(x.shape[0], self.n_treatment).to(x)
cause_mat.scatter_(1, cause, 1)
# get representations
confounder_rep = self.confounder_rep_net(x)
outcome_rep = self.outcome_rep_net(x)
combined_rep = torch.cat([confounder_rep, outcome_rep], dim=-1)
predictions = []
for i in range(self.n_treatment):
y_hat = self.heads[i](combined_rep)
predictions.append(y_hat)
prediction = torch.cat(predictions, dim=-1)
prediction_selected = torch.sum(prediction * cause_mat, dim=1).unsqueeze(-1)
log_propensity = self.propensity_net(confounder_rep)
mmd = 0
if self.lam_mmd != 0.0:
# calculate mmd
cause_np = cause.squeeze().cpu().numpy()
uniques, counts = np.unique(cause_np, return_counts=True)
uniques = uniques[counts > 1]
if len(uniques) < 2:
print("uniques", uniques)
print("counts", counts)
return prediction_selected, 0
for i in range(len(uniques)):
for j in range(i + 1, len(uniques)):
x1 = confounder_rep[cause.squeeze() == uniques[i]]
x2 = confounder_rep[cause.squeeze() == uniques[j]]
mmd = mmd + mmd2_rbf(x1, x2, self.mmd_sigma)
return prediction_selected, log_propensity, mmd, cause
def loss(self, y_pred, y):
# y_pred is the output of forward
y_hat, log_propensity, mmd, treated_label = y_pred
# factual loss
rmse = nn.MSELoss()
error = torch.sqrt(rmse(y_hat, y))
# propensity loss
nll_loss = nn.NLLLoss()
nll = nll_loss(log_propensity, treated_label.squeeze())
loss = error + nll + mmd * self.lam_mmd
return loss