-
Notifications
You must be signed in to change notification settings - Fork 2
/
01.train_deep_and_wide.py
393 lines (353 loc) · 14.3 KB
/
01.train_deep_and_wide.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import gc
import importlib
import os
from routine.utilities import generate_CSV, df_to_dataloader, generate_feature_columns
from routine.data_generation import generate_data
from routine.models import build_wide_model, build_deep_model, build_wide_and_deep_model, \
build_bayesian_model, evaluate_bandit
from os.path import exists
from pprint import pprint
import tensorflow as tf
import sys
import numpy as np
import pandas as pd
data_regenerate = False
if data_regenerate:
obs_df, user_df, camp_df = generate_data(
num_users=1000,
num_campaigns=100,
samples_per_campaign=10000,
num_cohort=10,
cohort_variances=np.linspace(0.05, 0.6, 10),
fh_cohort=True,
response_sig_a=10,
even_cohort=True,
cross_response=False,
magnify_hf=1
)
else:
obs_df = pd.read_csv('./observation_odd.csv')
INPUT_DATA_PATH = './deep_and_wide/NN_Inputs/input_data'
if not os.path.isdir(INPUT_DATA_PATH):
os.makedirs(INPUT_DATA_PATH)
#%% Creating the training, validation and testing data for the model
train_path = INPUT_DATA_PATH + "/train.csv"
val_path = INPUT_DATA_PATH + "/val.csv"
test_path = INPUT_DATA_PATH + "/test.csv"
re_create = True
if re_create:
generate_CSV(obs_df,
train_path,
val_path,
test_path,
verbose=True)
#%% Preparing dataset for evaluation
batch_size = 100
n_epochs = 100
feature_columns = ["user_id", "camp_id", "cohort",
"user_f0", "user_f1", "user_fh",
"camp_f0", "camp_f1", "camp_fh"]
target_column = "response"
train_dl = df_to_dataloader(train_path,
feature_columns,
target_column,
batch_size=batch_size)
val_dl = df_to_dataloader(val_path,
feature_columns,
target_column,
batch_size=batch_size)
test_dl = df_to_dataloader(test_path,
feature_columns,
target_column,
shuffle=False,
batch_size=batch_size)
print("[INFO] Train dataloader:")
pprint(train_dl)
print("[INFO] Val dataloader:")
pprint(val_dl)
print("[INFO] Test dataloader:")
pprint(test_dl)
#%% Creating TF feature columns
feature_column_dict, feature_column_input_dict = generate_feature_columns()
# defining the input to be fed into each model
inputs = {**feature_column_input_dict["numeric"], **feature_column_input_dict["embedding"]}
#%% Models
models_dir = './deep_and_wide/NN_checkpoint'
if not os.path.isdir(models_dir):
os.makedirs(models_dir)
# create the folders to save the checkpoints
wmodel_dir = models_dir + '/Wide'
dmodel_dir = models_dir + '/Deep'
wdmodel_dir = models_dir + '/W&D'
bayesian_dir = models_dir + '/Bayesian'
os.makedirs(wmodel_dir, exist_ok=True)
os.makedirs(dmodel_dir, exist_ok=True)
os.makedirs(wdmodel_dir, exist_ok=True)
os.makedirs(bayesian_dir, exist_ok=True)
# setting the hyperparameters
lr = 1e-3
gc.collect()
#%% Wide only model
wmodel, wmodel_path, w_es, w_mc = build_wide_model(feature_column_dict,
inputs,
wmodel_dir=wmodel_dir)
wmodel.summary() # To display the architecture
#%% Training already done - Just load the model!
again_training = True
if again_training:
# create callback for model saving
w_m = tf.keras.callbacks.ModelCheckpoint(
filepath=wmodel_path,
monitor='val_loss',
verbose=1,
save_best_only=True,
mode='min')
H = wmodel.fit(train_dl,
batch_size=batch_size,
epochs=n_epochs,
validation_data=val_dl,
shuffle=False,
validation_batch_size=batch_size,
callbacks=[w_es, w_mc, w_m])
else:
wmodel = tf.keras.models.load_model(wmodel_path)
#%% Generate the predictions
eval_wmodel_train = wmodel.evaluate(train_dl)
eval_wmodel_val = wmodel.evaluate(val_dl)
eval_wmodel_test = wmodel.evaluate(test_dl)
# Print the results
print("\n[INFO] On Training Set:")
print(eval_wmodel_train)
print("\n[INFO] On Validation Set:")
print(eval_wmodel_val)
print("\n[INFO] On Test Set:")
print(eval_wmodel_test)
# Deep only model
#%% With only embeddings
dmodel_1_emb, dmodel_1_emb_path, d1_es, d1_mc = build_deep_model(feature_column_dict["embedding"],
inputs,
dmodel_dir,
name="dmodel_1_emb.h5",
ckpt_name="dmodel_1_emb_checkpoint.h5")
dmodel_1_emb.summary() # To display the architecture
#%% Training already done - Just load the model!
again_training = True
if again_training:
# create callback for model saving
d1_m = tf.keras.callbacks.ModelCheckpoint(
filepath=dmodel_1_emb_path,
monitor='val_loss',
verbose=1,
save_best_only=True,
mode='min')
H1 = dmodel_1_emb.fit(train_dl,
batch_size=batch_size,
epochs=n_epochs,
validation_data=val_dl,
shuffle=False,
validation_batch_size=batch_size,
callbacks=[d1_es, d1_mc, d1_m])
else:
dmodel_1_emb = tf.keras.models.load_model(dmodel_1_emb_path)
#%% Generate predictions on train, val & test set
eval_dmodel_1_emb_train = dmodel_1_emb.evaluate(train_dl, batch_size=batch_size)
eval_dmodel_1_emb_val = dmodel_1_emb.evaluate(val_dl, batch_size=batch_size)
eval_dmodel_1_emb_test = dmodel_1_emb.evaluate(test_dl, batch_size=batch_size)
# Print the results
print("\n[INFO] On Training Set:")
print(eval_dmodel_1_emb_train)
print("\n[INFO] On Validation Set:")
print(eval_dmodel_1_emb_val)
print("\n[INFO] On Test Set:")
print(eval_dmodel_1_emb_test)
#%% With only numeric features
dmodel_2_num, dmodel_2_num_path, d2_es, d2_mc = build_deep_model(feature_column_dict["numeric"],
inputs,
dmodel_dir,
name="dmodel_2_num.h5",
ckpt_name="dmodel_2_num_checkpoint.h5")
dmodel_2_num.summary()
#%% Training already done - Just load the model!
again_training = True
if again_training:
# create callback for model saving
d2_m = tf.keras.callbacks.ModelCheckpoint(
filepath=dmodel_2_num_path,
monitor='val_loss',
verbose=1,
save_best_only=True,
mode='min')
H2 = dmodel_2_num.fit(train_dl,
batch_size=batch_size,
epochs=n_epochs,
validation_data=val_dl,
shuffle=False,
validation_batch_size=batch_size,
callbacks=[d2_es, d2_mc, d2_m])
else:
dmodel_2_num = tf.keras.models.load_model(dmodel_2_num_path)
#%% Generate predictions on train, val & test set
eval_dmodel_2_num_train = dmodel_2_num.evaluate(train_dl, batch_size=batch_size)
eval_dmodel_2_num_val = dmodel_2_num.evaluate(val_dl, batch_size=batch_size)
eval_dmodel_2_num_test = dmodel_2_num.evaluate(test_dl, batch_size=batch_size)
# Print the results
print("\n[INFO] On Training Set:")
print(eval_dmodel_2_num_train)
print("\n[INFO] On Validation Set:")
print(eval_dmodel_2_num_val)
print("\n[INFO] On Test Set:")
print(eval_dmodel_2_num_test)
#%% With embeddings and numeric features
dmodel_3_num_emb, dmodel_3_num_emb_path, d3_es, d3_mc = build_deep_model(feature_column_dict,
inputs,
dmodel_dir,
name="dmodel_3_num_emb.h5",
ckpt_name="dmodel_3_num_emb_checkpoint.h5")
dmodel_3_num_emb.summary()
#%% Training already done - Just load the model!
again_training = True
if again_training:
# create callback for model saving
d3_m = tf.keras.callbacks.ModelCheckpoint(
filepath=dmodel_3_num_emb_path,
monitor='val_loss',
verbose=1,
save_best_only=True,
mode='min')
H3 = dmodel_3_num_emb.fit(train_dl,
batch_size=batch_size,
epochs=n_epochs,
validation_data=val_dl,
shuffle=False,
validation_batch_size=batch_size,
callbacks=[d3_es, d3_mc, d3_m])
else:
dmodel_3_num_emb = tf.keras.models.load_model(dmodel_3_num_emb_path)
#%% Generate predictions on train, val & test set
eval_dmodel_3_num_emb_train = dmodel_3_num_emb.evaluate(train_dl, batch_size=batch_size)
eval_dmodel_3_num_emb_val = dmodel_3_num_emb.evaluate(val_dl, batch_size=batch_size)
eval_dmodel_3_num_emb_test = dmodel_3_num_emb.evaluate(test_dl, batch_size=batch_size)
# Print the results
print("\n[INFO] On Training Set:")
print(eval_dmodel_3_num_emb_train)
print("\n[INFO] On Validation Set:")
print(eval_dmodel_3_num_emb_val)
print("\n[INFO] On Test Set:")
print(eval_dmodel_3_num_emb_test)
#%% With normal and hidden numeric features
# Get the new feature column and input dicts
feature_column_dict_hidden, feature_column_input_dict_hidden = generate_feature_columns(hidden_include=True)
inputs_hidden = {**feature_column_input_dict_hidden["numeric"], **feature_column_input_dict_hidden["embedding"]}
dmodel_4_hid, dmodel_4_hid_path, d4_es, d4_mc = build_deep_model(feature_column_dict_hidden,
inputs_hidden,
dmodel_dir,
name="dmodel_4_hid.h5",
ckpt_name="dmodel_4_hid_checkpoint.h5")
dmodel_4_hid.summary()
#%% Training already done - Just load the model!
again_training = True
if again_training:
# create callback for model saving
d4_m = tf.keras.callbacks.ModelCheckpoint(
filepath=dmodel_4_hid_path,
monitor='val_loss',
verbose=1,
save_best_only=True,
mode='min')
H4 = dmodel_4_hid.fit(train_dl,
batch_size=batch_size,
epochs=n_epochs,
validation_data=val_dl,
shuffle=False,
validation_batch_size=batch_size,
callbacks=[d4_es, d4_mc, d4_m])
else:
dmodel_4_hid = tf.keras.models.load_model(dmodel_4_hid_path)
#%% Generate predictions on train, val & test set
eval_dmodel_4_hid_train = dmodel_4_hid.evaluate(train_dl, batch_size=batch_size)
eval_dmodel_4_hid_val = dmodel_4_hid.evaluate(val_dl, batch_size=batch_size)
eval_dmodel_4_hid_test = dmodel_4_hid.evaluate(test_dl, batch_size=batch_size)
# Print the results
print("\n[INFO] On Training Set:")
print(eval_dmodel_4_hid_train)
print("\n[INFO] On Validation Set:")
print(eval_dmodel_4_hid_val)
print("\n[INFO] On Test Set:")
print(eval_dmodel_4_hid_test)
#%% Wide & deep model
wdmodel, wdmodel_path, wd_es, wd_mc = build_wide_and_deep_model(feature_column_dict,
inputs,
wdmodel_dir=wdmodel_dir)
wdmodel.summary() # To display the architecture
#%% Training already done - Just load the model!
again_training = True
if again_training:
# create callback for model saving
wd_m = tf.keras.callbacks.ModelCheckpoint(
filepath=wdmodel_path,
monitor='val_loss',
verbose=1,
save_best_only=True,
mode='min')
H = wdmodel.fit(train_dl,
batch_size=batch_size,
epochs=n_epochs,
validation_data=val_dl,
shuffle=False,
validation_batch_size=batch_size,
callbacks=[wd_es, wd_mc, wd_m])
else:
wdmodel = tf.keras.models.load_model(wdmodel_path)
#%% Generate predictions on train, val & test set
eval_wdmodel_train = wdmodel.evaluate(train_dl, batch_size=batch_size)
eval_wdmodel_val = wdmodel.evaluate(val_dl, batch_size=batch_size)
eval_wdmodel_test = wdmodel.evaluate(test_dl, batch_size=batch_size)
# Print the results
print("\n[INFO] On Training Set:")
print(eval_wdmodel_train)
print("\n[INFO] On Validation Set:")
print(eval_wdmodel_val)
print("\n[INFO] On Test Set:")
print(eval_wdmodel_test)
#%% Bayesian Wide & deep model
bmodel, bmodel_path, b_es, b_mc = build_bayesian_model(feature_column_dict,
inputs,
bayesian_dir)
bmodel.summary() # To display the architecture
#%% Training already done - Just load the model!
again_training = True
if again_training:
# create callback for model saving
b_m = tf.keras.callbacks.ModelCheckpoint(
filepath=bmodel_path,
monitor='val_loss',
verbose=1,
save_best_only=True,
mode='min')
H = bmodel.fit(train_dl,
batch_size=batch_size,
epochs=n_epochs,
validation_data=val_dl,
shuffle=False,
validation_batch_size=batch_size,
callbacks=[b_es, b_mc, b_m])
else:
bmodel = tf.keras.models.load_model(bmodel_path)
#%% Generate predictions on train, val & test set
ts_train, ucb_train = evaluate_bandit(bmodel, train_dl)
ts_val, ucb_val = evaluate_bandit(bmodel, val_dl)
ts_test, ucb_test = evaluate_bandit(bmodel, test_dl)
# Print the results
print("\nUCB\n[INFO] On Training Set:")
print(ucb_train)
print("\n[INFO] On Validation Set:")
print(ucb_val)
print("\n[INFO] On Test Set:")
print(ucb_test)
# Print the results
print("\nThompson Sampling\n[INFO] On Training Set:")
print(ts_train)
print("\n[INFO] On Validation Set:")
print(ts_val)
print("\n[INFO] On Test Set:")
print(ts_test)