-
Notifications
You must be signed in to change notification settings - Fork 16
/
ganite.py
272 lines (204 loc) · 8.95 KB
/
ganite.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
"""GANITE Codebase.
Reference: Jinsung Yoon, James Jordon, Mihaela van der Schaar,
"GANITE: Estimation of Individualized Treatment Effects using Generative Adversarial Nets",
International Conference on Learning Representations (ICLR), 2018.
Paper link: https://openreview.net/forum?id=ByKWUeWA-
Last updated Date: April 25th 2020
Code author: Jinsung Yoon ([email protected])
-----------------------------
ganite.py
Note: GANITE module.
"""
# Necessary packages
import tensorflow as tf
import numpy as np
from utils import xavier_init, batch_generator
def ganite (train_x, train_t, train_y, test_x, parameters):
"""GANITE module.
Args:
- train_x: features in training data
- train_t: treatments in training data
- train_y: observed outcomes in training data
- test_x: features in testing data
- parameters: GANITE network parameters
- h_dim: hidden dimensions
- batch_size: the number of samples in each batch
- iterations: the number of iterations for training
- alpha: hyper-parameter to adjust the loss importance
Returns:
- test_y_hat: estimated potential outcome for testing set
"""
# Parameters
h_dim = parameters['h_dim']
batch_size = parameters['batch_size']
iterations = parameters['iteration']
alpha = parameters['alpha']
no, dim = train_x.shape
# Reset graph
tf.reset_default_graph()
## 1. Placeholder
# 1.1. Feature (X)
X = tf.placeholder(tf.float32, shape = [None, dim])
# 1.2. Treatment (T)
T = tf.placeholder(tf.float32, shape = [None, 1])
# 1.3. Outcome (Y)
Y = tf.placeholder(tf.float32, shape = [None, 1])
## 2. Variables
# 2.1 Generator
G_W1 = tf.Variable(xavier_init([(dim+2), h_dim])) # Inputs: X + Treatment + Factual outcome
G_b1 = tf.Variable(tf.zeros(shape = [h_dim]))
G_W2 = tf.Variable(xavier_init([h_dim, h_dim]))
G_b2 = tf.Variable(tf.zeros(shape = [h_dim]))
# Multi-task outputs for increasing the flexibility of the generator
G_W31 = tf.Variable(xavier_init([h_dim, h_dim]))
G_b31 = tf.Variable(tf.zeros(shape = [h_dim]))
G_W32 = tf.Variable(xavier_init([h_dim, 1]))
G_b32 = tf.Variable(tf.zeros(shape = [1])) # Output: Estimated outcome when t = 0
G_W41 = tf.Variable(xavier_init([h_dim, h_dim]))
G_b41 = tf.Variable(tf.zeros(shape = [h_dim]))
G_W42 = tf.Variable(xavier_init([h_dim, 1]))
G_b42 = tf.Variable(tf.zeros(shape = [1])) # Output: Estimated outcome when t = 1
# Generator variables
theta_G = [G_W1, G_W2, G_W31, G_W32, G_W41, G_W42, G_b1, G_b2, G_b31, G_b32, G_b41, G_b42]
# 2.2 Discriminator
D_W1 = tf.Variable(xavier_init([(dim+2), h_dim])) # Inputs: X + Factual outcomes + Estimated counterfactual outcomes
D_b1 = tf.Variable(tf.zeros(shape = [h_dim]))
D_W2 = tf.Variable(xavier_init([h_dim, h_dim]))
D_b2 = tf.Variable(tf.zeros(shape = [h_dim]))
D_W3 = tf.Variable(xavier_init([h_dim, 1]))
D_b3 = tf.Variable(tf.zeros(shape = [1]))
# Discriminator variables
theta_D = [D_W1, D_W2, D_W3, D_b1, D_b2, D_b3]
# 2.3 Inference network
I_W1 = tf.Variable(xavier_init([(dim), h_dim])) # Inputs: X
I_b1 = tf.Variable(tf.zeros(shape = [h_dim]))
I_W2 = tf.Variable(xavier_init([h_dim, h_dim]))
I_b2 = tf.Variable(tf.zeros(shape = [h_dim]))
# Multi-task outputs for increasing the flexibility of the inference network
I_W31 = tf.Variable(xavier_init([h_dim, h_dim]))
I_b31 = tf.Variable(tf.zeros(shape = [h_dim]))
I_W32 = tf.Variable(xavier_init([h_dim, 1]))
I_b32 = tf.Variable(tf.zeros(shape = [1])) # Output: Estimated outcome when t = 0
I_W41 = tf.Variable(xavier_init([h_dim, h_dim]))
I_b41 = tf.Variable(tf.zeros(shape = [h_dim]))
I_W42 = tf.Variable(xavier_init([h_dim, 1]))
I_b42 = tf.Variable(tf.zeros(shape = [1])) # Output: Estimated outcome when t = 1
# Inference network variables
theta_I = [I_W1, I_W2, I_W31, I_W32, I_W41, I_W42, I_b1, I_b2, I_b31, I_b32, I_b41, I_b42]
## 3. Definitions of generator, discriminator and inference networks
# 3.1 Generator
def generator(x, t, y):
"""Generator function.
Args:
- x: features
- t: treatments
- y: observed labels
Returns:
- G_logit: estimated potential outcomes
"""
# Concatenate feature, treatments, and observed labels as input
inputs = tf.concat(axis = 1, values = [x,t,y])
G_h1 = tf.nn.relu(tf.matmul(inputs, G_W1) + G_b1)
G_h2 = tf.nn.relu(tf.matmul(G_h1, G_W2) + G_b2)
# Estimated outcome if t = 0
G_h31 = tf.nn.relu(tf.matmul(G_h2, G_W31) + G_b31)
G_logit1 = tf.matmul(G_h31, G_W32) + G_b32
# Estimated outcome if t = 1
G_h41 = tf.nn.relu(tf.matmul(G_h2, G_W41) + G_b41)
G_logit2 = tf.matmul(G_h41, G_W42) + G_b42
G_logit = tf.concat(axis = 1, values = [G_logit1, G_logit2])
return G_logit
# 3.2. Discriminator
def discriminator(x, t, y, hat_y):
"""Discriminator function.
Args:
- x: features
- t: treatments
- y: observed labels
- hat_y: estimated counterfactuals
Returns:
- D_logit: estimated potential outcomes
"""
# Concatenate factual & counterfactual outcomes
input0 = (1.-t) * y + t * tf.reshape(hat_y[:,0], [-1,1]) # if t = 0
input1 = t * y + (1.-t) * tf.reshape(hat_y[:,1], [-1,1]) # if t = 1
inputs = tf.concat(axis = 1, values = [x, input0,input1])
D_h1 = tf.nn.relu(tf.matmul(inputs, D_W1) + D_b1)
D_h2 = tf.nn.relu(tf.matmul(D_h1, D_W2) + D_b2)
D_logit = tf.matmul(D_h2, D_W3) + D_b3
return D_logit
# 3.3. Inference Nets
def inference(x):
"""Inference function.
Args:
- x: features
Returns:
- I_logit: estimated potential outcomes
"""
I_h1 = tf.nn.relu(tf.matmul(x, I_W1) + I_b1)
I_h2 = tf.nn.relu(tf.matmul(I_h1, I_W2) + I_b2)
# Estimated outcome if t = 0
I_h31 = tf.nn.relu(tf.matmul(I_h2, I_W31) + I_b31)
I_logit1 = tf.matmul(I_h31, I_W32) + I_b32
# Estimated outcome if t = 1
I_h41 = tf.nn.relu(tf.matmul(I_h2, I_W41) + I_b41)
I_logit2 = tf.matmul(I_h41, I_W42) + I_b42
I_logit = tf.concat(axis = 1, values = [I_logit1, I_logit2])
return I_logit
## Structure
# 1. Generator
Y_tilde_logit = generator(X, T, Y)
Y_tilde = tf.nn.sigmoid(Y_tilde_logit)
# 2. Discriminator
D_logit = discriminator(X,T,Y,Y_tilde)
# 3. Inference network
Y_hat_logit = inference(X)
Y_hat = tf.nn.sigmoid(Y_hat_logit)
## Loss functions
# 1. Discriminator loss
D_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels = T, logits = D_logit ))
# 2. Generator loss
G_loss_GAN = -D_loss
G_loss_Factual = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(
labels = Y, logits = (T * tf.reshape(Y_tilde_logit[:,1],[-1,1]) + \
(1. - T) * tf.reshape(Y_tilde_logit[:,0],[-1,1]) )))
G_loss = G_loss_Factual + alpha * G_loss_GAN
# 3. Inference loss
I_loss1 = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(
labels = (T) * Y + (1-T) * tf.reshape(Y_tilde[:,1],[-1,1]), logits = tf.reshape(Y_hat_logit[:,1],[-1,1]) ))
I_loss2 = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(
labels = (1-T) * Y + (T) * tf.reshape(Y_tilde[:,0],[-1,1]), logits = tf.reshape(Y_hat_logit[:,0],[-1,1]) ))
I_loss = I_loss1 + I_loss2
## Solver
G_solver = tf.train.AdamOptimizer().minimize(G_loss, var_list=theta_G)
D_solver = tf.train.AdamOptimizer().minimize(D_loss, var_list=theta_D)
I_solver = tf.train.AdamOptimizer().minimize(I_loss, var_list=theta_I)
## GANITE training
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print('Start training Generator and Discriminator')
# 1. Train Generator and Discriminator
for it in range(iterations):
for _ in range(2):
# Discriminator training
X_mb, T_mb, Y_mb = batch_generator(train_x, train_t, train_y, batch_size)
_, D_loss_curr = sess.run([D_solver, D_loss], feed_dict = {X: X_mb, T: T_mb, Y: Y_mb})
# Generator traininig
X_mb, T_mb, Y_mb = batch_generator(train_x, train_t, train_y, batch_size)
_, G_loss_curr = sess.run([G_solver, G_loss], feed_dict = {X: X_mb, T: T_mb, Y: Y_mb})
# Check point
if it % 1000 == 0:
print('Iteration: ' + str(it) + '/' + str(iterations) + ', D loss: ' + \
str(np.round(D_loss_curr, 4)) + ', G loss: ' + str(np.round(G_loss_curr, 4)))
print('Start training Inference network')
# 2. Train Inference network
for it in range(iterations):
X_mb, T_mb, Y_mb = batch_generator(train_x, train_t, train_y, batch_size)
_, I_loss_curr = sess.run([I_solver, I_loss], feed_dict = {X: X_mb, T: T_mb, Y: Y_mb})
# Check point
if it % 1000 == 0:
print('Iteration: ' + str(it) + '/' + str(iterations) +
', I loss: ' + str(np.round(I_loss_curr, 4)))
## Generate the potential outcomes
test_y_hat = sess.run(Y_hat, feed_dict = {X: test_x})
return test_y_hat