-
Notifications
You must be signed in to change notification settings - Fork 5
/
run.py
6554 lines (5468 loc) · 240 KB
/
run.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
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow_probability as tfp
tfd = tfp.distributions
from tensorflow.keras.preprocessing.sequence import pad_sequences
import cvxpy as cp
import numpy as np
import pandas as pd
from itertools import chain
from bisect import bisect_right, bisect_left
from multiprocessing import Pool
import matplotlib.pyplot as plt
import properscoring as ps
from operator import itemgetter
import models
import utils
import os
import sys
import time
from nltk.translate.bleu_score import sentence_bleu, corpus_bleu
from utils import IntensityHomogenuosPoisson, generate_sample
from utils import get_time_features
from utils import add_metrics_to_dict
from utils import write_arr_to_file
from utils import write_pe_metrics_to_file
from utils import write_opt_losses_to_file
#from transformer_helpers import Utils
import transformer_utils
train_gap_metric_mae = tf.keras.metrics.MeanAbsoluteError()
train_gap_metric_mse = tf.keras.metrics.MeanSquaredError()
dev_gap_metric_mae = tf.keras.metrics.MeanAbsoluteError()
dev_gap_metric_mse = tf.keras.metrics.MeanSquaredError()
test_gap_metric_mae = tf.keras.metrics.MeanAbsoluteError()
test_gap_metric_mse = tf.keras.metrics.MeanSquaredError()
types_metric = tf.keras.metrics.SparseCategoricalAccuracy()
#dev_types_metric = tf.keras.metrics.SparseCategoricalAccuracy()
#test_types_metric = tf.keras.metrics.SparseCategoricalAccuracy()
ETH = 10.0
one_by = tf.math.reciprocal_no_nan
flatten = lambda l: [item for sublist in l for item in sublist]
#####################################################
# Loss Functions #
#####################################################
class NegativeLogLikelihood(tf.keras.losses.Loss):
def __init__(self, D, WT,
reduction=keras.losses.Reduction.AUTO,
name='negative_log_likelihood'):
super(NegativeLogLikelihood, self).__init__(reduction=reduction,
name=name)
self.D = D
self.WT = WT
def call(self, gaps_true, gaps_pred):
log_lambda_ = (self.D + (gaps_true * self.WT))
lambda_ = tf.exp(tf.minimum(ETH, log_lambda_), name='lambda_')
log_f_star = (log_lambda_
+ one_by(self.WT) * tf.exp(tf.minimum(ETH, self.D))
- one_by(self.WT) * lambda_)
return -log_f_star
class MeanSquareLoss(tf.keras.losses.Loss):
def __init__(self,
reduction=keras.losses.Reduction.AUTO,
name='mean_square_likelihood'):
super(MeanSquareLoss, self).__init__(reduction=reduction,
name=name)
def call(self, gaps_true, gaps_pred):
error = gaps_true - gaps_pred
return tf.reduce_mean(error * error)
class Gaussian_MSE(tf.keras.losses.Loss):
def __init__(self, D, WT,
reduction=keras.losses.Reduction.AUTO,
name='mean_square_guassian'):
super(Gaussian_MSE, self).__init__(reduction=reduction,
name=name)
self.out_mean = D
self.out_stddev = WT
def call(self, gaps_true, gaps_pred):
gaussian_distribution = tfp.distributions.Normal(
self.out_mean, self.out_stddev, validate_args=False, allow_nan_stats=True,
name='Normal'
)
loss = -tf.reduce_mean(gaussian_distribution.log_prob(gaps_true))
return loss
#####################################################
# Run Models Function #
#####################################################
# RMTPP_VAR model
# Trains a separate model to predict the variance of the RMTPP predictions.
# Predicted variance is function of distance between predicted last encoder input
# and predicted timestamp. The model is trained to maximize the likelihood of
# the observed gaps.
def run_rmtpp_var(args, data, test_data, trained_rmtpp_model):
model = models.RMTPP_VAR(args.hidden_layer_size)
[train_dataset_gaps, nc_event_dev_in_gaps, nc_event_dev_out_gaps, train_norm_gaps] = data
[event_train_norma, event_train_normd] = train_norm_gaps
model_name = args.current_model
optimizer = keras.optimizers.Adam(args.learning_rate)
enc_len = args.enc_len
dev_data_gaps = nc_event_dev_in_gaps
os.makedirs('saved_models/training_'+model_name+'_'+args.current_dataset+'/', exist_ok=True)
checkpoint_path = "saved_models/training_"+model_name+"_"+args.current_dataset+"/cp_"+args.current_dataset+".ckpt"
best_dev_gap_mse = np.inf
best_dev_epoch = 0
train_losses = list()
for epoch in range(args.epochs):
print('Starting epoch', epoch)
step_train_loss = 0.0
step_cnt = 0
next_initial_state = None
for sm_step, (gaps_batch, _) in enumerate(train_dataset_gaps):
gaps_batch_in = gaps_batch[:, :int(enc_len/2)]
gaps_batch_out = gaps_batch[:, int(enc_len/2):]
with tf.GradientTape() as tape:
# TODO: Pass the correct initial state based on
# batch_size and stride etc..
gaps_pred = simulate_fixed_cnt(trained_rmtpp_model,
gaps_batch_in,
int(enc_len/2),
prev_hidden_state=next_initial_state)
model_inputs = tf.cumsum(gaps_pred, axis=1)
var_pred = model(model_inputs)
# Compute the loss for this minibatch.
import ipdb
ipdb.set_trace()
gap_loss_fn = Gaussian_MSE(gaps_pred, var_pred)
gap_loss = gap_loss_fn(gaps_batch_out, None)
loss = gap_loss
step_train_loss+=loss.numpy()
grads = tape.gradient(loss, model.trainable_weights)
optimizer.apply_gradients(zip(grads, model.trainable_weights))
train_gap_metric_mae(gaps_batch_out, gaps_pred)
train_gap_metric_mse(gaps_batch_out, gaps_pred)
train_gap_mae = train_gap_metric_mae.result()
train_gap_mse = train_gap_metric_mse.result()
train_gap_metric_mae.reset_states()
train_gap_metric_mse.reset_states()
# print(float(train_gap_mae), float(train_gap_mse))
print('Training loss (for one batch) at step %s: %s' %(sm_step, float(loss)))
step_cnt += 1
# Dev calculations
nc_event_dev_in_gaps = dev_data_gaps[:, :int(enc_len/2)]
nc_event_dev_out_gaps = dev_data_gaps[:, int(enc_len/2):]
dev_gaps_pred = simulate_fixed_cnt(trained_rmtpp_model,
nc_event_dev_in_gaps,
int(enc_len)/2,
prev_hidden_state=next)
model_dev_inputs = tf.cumsum(dev_gaps_pred, axis=1)
dev_var_pred = model(model_dev_inputs)
dev_loss_fn = Gaussian_MSE(dev_gaps_pred, dev_var_pred)
dev_loss = dev_loss_fn(nc_event_dev_out_gaps, None)
dev_gaps_pred_unnorm = utils.denormalize_avg(dev_gaps_pred,
event_train_norma, event_train_normd)
dev_gap_metric_mae(nc_event_dev_out_gaps, dev_gaps_pred_unnorm)
dev_gap_metric_mse(nc_event_dev_out_gaps, dev_gaps_pred_unnorm)
dev_gap_mae = dev_gap_metric_mae.result()
dev_gap_mse = dev_gap_metric_mse.result()
dev_gap_metric_mae.reset_states()
dev_gap_metric_mse.reset_states()
if best_dev_gap_mse > dev_gap_mse:
best_dev_gap_mse = dev_gap_mse
best_dev_epoch = epoch
print('Saving model at epoch', epoch)
model.save_weights(checkpoint_path)
step_train_loss /= step_cnt
print('Training loss after epoch %s: %s' %(epoch, float(step_train_loss)))
print('MAE and MSE of Dev data %s: %s' \
%(float(dev_gap_mae), float(dev_gap_mse)))
train_losses.append(step_train_loss)
plt.plot(range(len(train_losses)), train_losses)
plt.savefig(os.path.join(args.output_dir, 'train_'+args.current_model+'_'+args.current_dataset+'_loss.png'))
plt.close()
print("Loading best model from epoch", best_dev_epoch)
model.load_weights(checkpoint_path)
dev_gaps_pred, _, _, _, _ = model(nc_event_dev_in_gaps)
dev_gaps_pred_unnorm = utils.denormalize_avg(dev_gaps_pred,
event_train_norma, event_train_normd)
dev_gap_metric_mae(nc_event_dev_out_gaps, dev_gaps_pred_unnorm)
dev_gap_metric_mse(nc_event_dev_out_gaps, dev_gaps_pred_unnorm)
dev_gap_mae = dev_gap_metric_mae.result()
dev_gap_mse = dev_gap_metric_mse.result()
dev_gap_metric_mae.reset_states()
dev_gap_metric_mse.reset_states()
print('Best MAE and MSE of Dev data %s: %s' \
%(float(dev_gap_mae), float(dev_gap_mse)))
return model, None
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
# RMTPP model
def run_rmtpp(args, model, optimizer, data, var_data, NLL_loss,
rmtpp_epochs=10, use_var_model=False, comp_model=False,
rmtpp_type=None):
[train_dataset_gaps,
nc_event_dev_in_gaps, nc_event_dev_in_feats, nc_event_dev_in_types,
nc_event_dev_out_gaps, nc_event_dev_out_types,
train_norm_gaps] = data
[event_train_norma, event_train_normd] = train_norm_gaps
#[var_dataset_gaps, train_end_hr_bins_relative,
# train_data_in_time_end_bin,
# train_gap_in_bin_norm_a, train_gap_in_bin_norm_d] = var_data
model_name = args.current_model
os.makedirs(args.saved_models+'/training_'+model_name+'_'+args.current_dataset+'/', exist_ok=True)
checkpoint_path = "saved_models/training_"+model_name+"_"+args.current_dataset+"/cp_"+args.current_dataset+".ckpt"
best_dev_gap_mse = np.inf
best_dev_epoch = 0
enc_len = args.enc_len
comp_enc_len = args.comp_enc_len
batch_size = args.batch_size
stride_move = batch_size
dataset_name = args.current_dataset
if not comp_model:
if dataset_name in ['taxi', '911_traffic', '911_ems']:
stride_move = batch_size * args.stride_len
if stride_move > enc_len:
print("Training considering independent sequence")
stride_move = 0
if comp_model:
if stride_move > comp_enc_len:
print("Training considering independent sequence")
stride_move = 0
if args.extra_var_model and rmtpp_type=='mse':
hls = args.hidden_layer_size
num_grps = args.num_grps #TODO make it command line argument later
num_pos = args.num_pos
rmtpp_var_model = models.RMTPP_VAR(hls,
args.out_bin_sz, hls,
num_grps, hls,
num_pos, hls)
var_optimizer = keras.optimizers.Adam(args.learning_rate)
os.makedirs(args.saved_models+'/training_rmtpp_var_model_'+args.current_dataset+'/', exist_ok=True)
var_checkpoint_path = args.saved_models+"/training_rmtpp_var_model_"+args.current_dataset+"/cp_"+args.current_dataset+".ckpt"
best_dev_var_loss = np.inf
best_dev_var_epoch = 0
best_var_loss = np.inf
best_var_epoch = 0
else:
rmtpp_var_model = None
train_losses = list()
for epoch in range(args.epochs):
print('Starting epoch', epoch)
var_epoch_loss = 0.
step_train_loss = 0.0
step_cnt = 0
next_initial_state = None
st = time.time()
for sm_step, (gaps_batch_in, feats_batch_in, types_batch_in,
gaps_batch_out, feats_batch_out, types_batch_out) \
in enumerate(train_dataset_gaps):
with tf.GradientTape() as tape:
gaps_pred, types_logits_pred, D, WT, _ = model(
gaps_batch_in,
feats_batch_in,
types_batch_in)
# Compute the loss for this minibatch.
if use_var_model:
gap_loss_fn = Gaussian_MSE(D, WT)
elif NLL_loss:
gap_loss_fn = NegativeLogLikelihood(D, WT)
else:
gap_loss_fn = MeanSquareLoss()
type_loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
gap_loss = gap_loss_fn(gaps_batch_out, gaps_pred)
type_loss = type_loss_fn(types_batch_out-1, types_logits_pred)
loss = gap_loss + type_loss
step_train_loss+=loss.numpy()
grads = tape.gradient(loss, model.trainable_weights)
optimizer.apply_gradients(zip(grads, model.trainable_weights))
train_gap_metric_mae(gaps_batch_out, gaps_pred)
train_gap_metric_mse(gaps_batch_out, gaps_pred)
train_gap_mae = train_gap_metric_mae.result()
train_gap_mse = train_gap_metric_mse.result()
train_gap_metric_mae.reset_states()
train_gap_metric_mse.reset_states()
# print(float(train_gap_mae), float(train_gap_mse))
print('Training loss (for one batch) at step %s: %s, %s, %s' %(sm_step, float(loss), float(gap_loss), float(type_loss)))
step_cnt += 1
et = time.time()
print(model_name, 'time_reqd:', et-st)
# Dev calculations
dev_gaps_pred, dev_logits_pred, _, _, _ = model(nc_event_dev_in_gaps, nc_event_dev_in_feats, nc_event_dev_in_types)
dev_gaps_pred_unnorm = utils.denormalize_avg(dev_gaps_pred,
event_train_norma,
event_train_normd)
dev_gap_metric_mae(nc_event_dev_out_gaps, dev_gaps_pred_unnorm)
dev_gap_metric_mse(nc_event_dev_out_gaps, dev_gaps_pred_unnorm)
dev_gap_mae = dev_gap_metric_mae.result()
dev_gap_mse = dev_gap_metric_mse.result()
dev_gap_metric_mae.reset_states()
dev_gap_metric_mse.reset_states()
dev_types_acc = types_metric(nc_event_dev_out_types-1, dev_logits_pred)
types_metric.reset_states()
if best_dev_gap_mse > dev_gap_mse:
best_dev_gap_mse = dev_gap_mse
best_dev_epoch = epoch
print('Saving model at epoch', epoch)
model.save_weights(checkpoint_path)
step_train_loss /= step_cnt
print('Training loss after epoch %s: %s' %(epoch, float(step_train_loss)))
print('MAE and MSE of Dev data %s: %s' \
%(float(dev_gap_mae), float(dev_gap_mse)))
train_losses.append(step_train_loss)
if args.extra_var_model and rmtpp_type=='mse':# and epoch%5==0:
var_gaps_pred_lst, bin_ids_lst, grp_ids_lst, pos_ids_lst = [], [], [], []
for epoch in range(args.epochs+5):
var_epoch_loss = 0.
for sm_step, (var_gaps_batch_in, var_gaps_batch_out,
var_bch_in_time_end_bin, var_bch_end_hr_bins) \
in enumerate(var_dataset_gaps):
with tf.GradientTape() as var_tape:
if epoch==0:
var_gaps_pred, _, bin_ids, grp_ids, pos_ids \
= simulate_v2(model,
var_bch_in_time_end_bin,
var_gaps_batch_in,
var_bch_end_hr_bins.numpy(),
(train_gap_in_bin_norm_a,
train_gap_in_bin_norm_d),
(args.out_bin_sz, num_grps, num_pos),
var_gaps_batch_out.numpy(),
prev_hidden_state=None)
var_gaps_pred_lst.append(var_gaps_pred)
bin_ids_lst.append(bin_ids)
grp_ids_lst.append(grp_ids)
pos_ids_lst.append(pos_ids)
else:
var_gaps_pred = var_gaps_pred_lst[sm_step]
bin_ids = bin_ids_lst[sm_step]
grp_ids = grp_ids_lst[sm_step]
pos_ids = pos_ids_lst[sm_step]
var_model_inputs = tf.cumsum(var_gaps_pred, axis=1)
var_pred = rmtpp_var_model(var_model_inputs,
bin_ids, grp_ids, pos_ids)
var_pred = tf.squeeze(var_pred, axis=-1)
var_loss_fn = Gaussian_MSE(var_gaps_pred, var_pred)
var_loss = var_loss_fn(var_gaps_batch_out, None)
var_epoch_loss+=var_loss.numpy()
var_grads = var_tape.gradient(var_loss, rmtpp_var_model.trainable_weights)
var_optimizer.apply_gradients(zip(var_grads, rmtpp_var_model.trainable_weights))
print('Var model Training loss (for one batch) at step %s: %s' \
%(sm_step, float(var_loss)))
if best_var_loss > var_epoch_loss:
best_var_loss = var_epoch_loss
best_var_epoch = epoch
print('Saving rmtpp_var_model at epoch', epoch)
rmtpp_var_model.save_weights(var_checkpoint_path)
plt.plot(range(len(train_losses)), train_losses)
plt.savefig(os.path.join(args.output_dir, 'train_'+model_name+'_'+args.current_dataset+'_loss.png'))
plt.close()
print("Loading best model from epoch", best_dev_epoch)
model.load_weights(checkpoint_path)
dev_gaps_pred, dev_logits_pred, _, _, _ = model(nc_event_dev_in_gaps, nc_event_dev_in_feats, nc_event_dev_in_types)
dev_gaps_pred_unnorm = utils.denormalize_avg(dev_gaps_pred,
event_train_norma,
event_train_normd)
dev_gap_metric_mae(nc_event_dev_out_gaps, dev_gaps_pred_unnorm)
dev_gap_metric_mse(nc_event_dev_out_gaps, dev_gaps_pred_unnorm)
dev_gap_mae = dev_gap_metric_mae.result()
dev_gap_mse = dev_gap_metric_mse.result()
dev_gap_metric_mae.reset_states()
dev_gap_metric_mse.reset_states()
dev_types_acc = types_metric(nc_event_dev_out_types-1, dev_logits_pred)
types_metric.reset_states()
print('Best MAE, MSE, type_acc of Dev data: %s, %s, %s' \
%(float(dev_gap_mae), float(dev_gap_mse), float(dev_types_acc)))
if args.extra_var_model and rmtpp_type=='mse':
print("Loading best rmtpp_var_model from epoch", best_var_epoch)
rmtpp_var_model.load_weights(var_checkpoint_path)
return train_losses, rmtpp_var_model
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
# RMTPP run initialize with loss function for run_rmtpp
def run_rmtpp_init(args, data, test_data, var_data,
NLL_loss=False, use_var_model=False, rmtpp_type='mse'):
[event_test_in_gaps, event_test_in_feats, event_test_in_types,
count_test_out_binend, event_test_in_lasttime,
event_test_norma, event_test_normd] = test_data
rmtpp_epochs = args.epochs
enc_len = args.enc_len
dec_len = args.out_bin_sz
bin_size = args.bin_size
num_types = args.num_types
use_intensity = True
if not NLL_loss:
use_intensity = False
model, optimizer = models.build_rmtpp_model(args, use_intensity, use_var_model, num_types)
#model.summary()
if use_var_model:
print('\nTraining Model with MSE Loss with Variance')
elif NLL_loss:
print('\nTraining Model with NLL Loss')
else:
print('\nTraining Model with Mean Square Loss')
train_loss, rmtpp_var_model = run_rmtpp(args, model, optimizer,
data, var_data, NLL_loss=NLL_loss,
rmtpp_epochs=rmtpp_epochs,
use_var_model=use_var_model,
rmtpp_type=rmtpp_type)
return model, rmtpp_var_model
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
# Pure Hierarchical model
def run_pure_hierarchical(args, model, optimizer, data, NLL_loss, rmtpp_epochs=10):
[train_dataset_gaps, nc_event_dev_in_gaps, nc_event_dev_out_gaps, train_norm_gaps] = data
[event_train_norma, event_train_normd] = train_norm_gaps
model_name = args.current_model
os.makedirs('saved_models/training_'+model_name+'_'+args.current_dataset+'/', exist_ok=True)
checkpoint_path = "saved_models/training_"+model_name+"_"+args.current_dataset+"/cp_"+args.current_dataset+".ckpt"
best_dev_gap_mse = np.inf
best_dev_epoch = 0
enc_len = args.enc_len
comp_enc_len = args.comp_enc_len
batch_size = args.batch_size
dataset_name = args.current_dataset
train_losses = list()
for epoch in range(args.epochs):
print('Starting epoch', epoch)
step_train_loss = 0.0
step_cnt = 0
next_initial_state = None
for sm_step, (gaps_batch_in, gaps_batch_out) in enumerate(train_dataset_gaps):
with tf.GradientTape() as tape:
# TODO: Make sure to pass correct next_stat
gaps_batch_out = tf.cast(gaps_batch_out, tf.float32)
gaps_pred_l2, D_l2, WT_l2, gaps_pred, D_l1, WT_l1, next_initial_state, _ = model(gaps_batch_in,
initial_state=None,
gaps_out=gaps_batch_out,
next_state_sno=1)
# print(gaps_pred[0,0,:5])
# print(gaps_pred_l2[0,:5])
# Compute the loss for this minibatch.
if NLL_loss:
gap_loss_fn = NegativeLogLikelihood(D_l1, WT_l1)
gap_loss_fn_l2 = NegativeLogLikelihood(D_l2, WT_l2)
else:
gap_loss_fn = MeanSquareLoss()
gap_loss_fn_l2 = MeanSquareLoss()
gaps_batch_out_l2 = tf.reduce_sum(gaps_batch_out, axis=2)
gap_loss = gap_loss_fn(gaps_batch_out, gaps_pred)
gap_loss_l2 = gap_loss_fn_l2(gaps_batch_out_l2, gaps_pred_l2)
loss = gap_loss + gap_loss_l2
step_train_loss+=loss.numpy()
#TODO: Pred for l2 is same as l1?
grads = tape.gradient(loss, model.trainable_weights)
optimizer.apply_gradients(zip(grads, model.trainable_weights))
train_gap_metric_mae(gaps_batch_out, gaps_pred)
train_gap_metric_mse(gaps_batch_out, gaps_pred)
train_gap_mae = train_gap_metric_mae.result()
train_gap_mse = train_gap_metric_mse.result()
train_gap_metric_mae.reset_states()
train_gap_metric_mse.reset_states()
# print(float(train_gap_mae), float(train_gap_mse))
print('Training loss (for one batch) at step %s: %s' %(sm_step, float(loss)))
step_cnt += 1
# Dev calculations
dev_gaps_pred_l2, _,_, dev_gaps_pred, _,_,_,_ = model(nc_event_dev_in_gaps)
dev_gaps_pred_unnorm = utils.denormalize_avg(dev_gaps_pred,
event_train_norma, event_train_normd)
dev_gap_metric_mae(nc_event_dev_out_gaps, dev_gaps_pred_unnorm)
dev_gap_metric_mse(nc_event_dev_out_gaps, dev_gaps_pred_unnorm)
dev_gap_mae = dev_gap_metric_mae.result()
dev_gap_mse = dev_gap_metric_mse.result()
dev_gap_metric_mae.reset_states()
dev_gap_metric_mse.reset_states()
if best_dev_gap_mse > dev_gap_mse:
best_dev_gap_mse = dev_gap_mse
best_dev_epoch = epoch
print('Saving model at epoch', epoch)
model.save_weights(checkpoint_path)
step_train_loss /= step_cnt
print('Training loss after epoch %s: %s' %(epoch, float(step_train_loss)))
print('MAE and MSE of Dev data %s: %s' \
%(float(dev_gap_mae), float(dev_gap_mse)))
train_losses.append(step_train_loss)
plt.plot(range(len(train_losses)), train_losses)
plt.savefig(os.path.join(args.output_dir, 'train_'+model_name+'_'+args.current_dataset+'_loss.png'))
plt.close()
print("Loading best model from epoch", best_dev_epoch)
model.load_weights(checkpoint_path)
dev_gaps_pred_l2, _,_, dev_gaps_pred, _,_,_,_ = model(nc_event_dev_in_gaps)
dev_gaps_pred_unnorm = utils.denormalize_avg(dev_gaps_pred,
event_train_norma, event_train_normd)
dev_gap_metric_mae(nc_event_dev_out_gaps, dev_gaps_pred_unnorm)
dev_gap_metric_mse(nc_event_dev_out_gaps, dev_gaps_pred_unnorm)
dev_gap_mae = dev_gap_metric_mae.result()
dev_gap_mse = dev_gap_metric_mse.result()
dev_gap_metric_mae.reset_states()
dev_gap_metric_mse.reset_states()
print('Best MAE and MSE of Dev data %s: %s' \
%(float(dev_gap_mae), float(dev_gap_mse)))
return train_losses
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
# Pure RMTPP Hierarchical run initialize with loss function for run_rmtpp
def run_pure_hierarchical_init(args, data, test_data,
NLL_loss=False):
#TODO:
# 1. Add rmtpp_type
# 2. use_var_model?
#
[event_test_in_gaps, event_test_in_feats,
count_test_out_binend, event_test_in_lasttime,
event_test_norma, event_test_normd] = test_data
rmtpp_epochs = args.epochs
use_intensity = True
if not NLL_loss:
use_intensity = False
model, optimizer = models.build_pure_hierarchical_model(args, use_intensity)
# model.summary()
if NLL_loss:
print('\nTraining Model with NLL Loss')
else:
print('\nTraining Model with Mean Square Loss')
train_loss = run_pure_hierarchical(args, model, optimizer,
data, NLL_loss=NLL_loss,
rmtpp_epochs=rmtpp_epochs)
return model, None
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
# RMTPP Comp run initialize with loss function for run_rmtpp with compound layer
def run_rmtpp_comp_init(args, data, test_data, var_data,
NLL_loss=False, use_var_model=False, rmtpp_type='mse'):
[event_test_in_gaps, event_test_in_feats, event_test_in_types,
count_test_out_binend, event_test_in_lasttime,
event_test_norma, event_test_normd] = test_data
rmtpp_epochs = args.epochs
num_types = 1 # num_types is always 1 for compound model
use_intensity = True
if not NLL_loss:
use_intensity = False
model, optimizer = models.build_rmtpp_model(args, use_intensity, use_var_model, num_types)
#model.summary()
if use_var_model:
print('\nTraining Model with MSE Loss with Variance')
elif NLL_loss:
print('\nTraining Model with NLL Loss')
else:
print('\nTraining Model with Mean Square Loss')
train_loss, rmtpp_var_model = run_rmtpp(args, model, optimizer,
data, var_data, NLL_loss=NLL_loss,
rmtpp_epochs=rmtpp_epochs,
use_var_model=use_var_model,
rmtpp_type=rmtpp_type,
comp_model=True)
return model, rmtpp_var_model
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
# Count Model with bin count from plain FF network
def run_hierarchical(args, data, test_data):
validation_split = 0.2
num_epochs = args.epochs * 100
count_train_in_counts, count_train_out_counts = data
(count_test_in_counts, count_test_in_feats, count_test_out_counts,
count_test_normm, count_test_norms) = test_data
batch_size = args.batch_size
model_name = args.current_model
os.makedirs(args.saved_models+'/training_'+model_name+'_'+args.current_dataset+'/', exist_ok=True)
checkpoint_path = args.saved_models+"/training_"+model_name+"_"+args.current_dataset+"/cp_"+args.current_dataset+".ckpt"
model_cnt = models.hierarchical_model(args)
model_cnt.summary()
if num_epochs > 0:
history_cnt = model_cnt.fit(count_train_in_counts, count_train_out_counts, batch_size=batch_size,
epochs=num_epochs, validation_split=validation_split, verbose=0)
model_cnt.save_weights(checkpoint_path)
hist = pd.DataFrame(history_cnt.history)
hist['epoch'] = history_cnt.epoch
print(hist)
else:
model_cnt.load_weights(checkpoint_path)
test_data_out_norm = utils.normalize_data_given_param(count_test_out_counts, count_test_normm, count_test_norms)
loss, mae, mse = model_cnt.evaluate(count_test_in_counts, test_data_out_norm, verbose=0)
print('Normalized loss, mae, mse', loss, mae, mse)
test_predictions_norm_cnt = model_cnt.predict(count_test_in_counts)
test_predictions_cnt = utils.denormalize_data(test_predictions_norm_cnt,
count_test_normm, count_test_norms)
event_count_preds_cnt = test_predictions_cnt
return model_cnt, event_count_preds_cnt
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
# Count model with NB or Gaussian distribution
def run_count_model(args, data, test_data):
validation_split = 0.2
num_epochs = args.epochs * 100
patience = args.patience * 0
distribution_name = 'Gaussian'
#distribution_name = 'var_model'
(count_train_in_counts, count_train_in_feats, count_train_out_counts,
count_dev_in_counts, count_dev_in_feats, count_dev_out_counts) = data
(count_test_in_counts, count_test_in_feats,
count_test_out_counts, count_test_normm, count_test_norms) = test_data
dataset_size = len(count_train_in_counts)
train_data_size = dataset_size - round(validation_split*dataset_size)
count_train_in_counts = count_train_in_counts.astype(np.float32)
count_train_out_counts = count_train_out_counts.astype(np.float32)
count_test_in_counts = count_test_in_counts.astype(np.float32)
count_test_out_counts = count_test_out_counts.astype(np.float32)
#dev_data_in_bin = count_train_in_counts[train_data_size:]
#dev_data_in_bin_feats = count_train_in_feats[train_data_size:]
#dev_data_out_bin = count_train_out_counts[train_data_size:]
#count_train_in_counts = count_train_in_counts[:train_data_size]
#count_train_out_counts = count_train_out_counts[:train_data_size]
#count_train_in_feats = count_train_in_feats[:train_data_size]
batch_size = args.batch_size
train_dataset = tf.data.Dataset.from_tensor_slices(
(
count_train_in_counts,
count_train_in_feats,
count_train_out_counts
)
).batch(batch_size, drop_remainder=True)
model, optimizer = models.build_count_model(args, distribution_name)
#model.summary()
os.makedirs(args.saved_models+'/training_count_'+args.current_dataset+'/', exist_ok=True)
checkpoint_path = args.saved_models+"/training_count_"+args.current_dataset+"/cp_"+args.current_dataset+".ckpt"
best_dev_gap_mae = np.inf
best_dev_epoch = 0
train_losses = list()
stddev_sample = list()
dev_mae_list = list()
for epoch in range(num_epochs):
#print('Starting epoch', epoch)
step_train_loss = 0.0
step_cnt = 0
for sm_step, (bin_count_batch_in, bin_count_batch_in_feats,
bin_count_batch_out) in enumerate(train_dataset):
with tf.GradientTape() as tape:
#import ipdb
#ipdb.set_trace()
bin_counts_pred, distribution_params = model(
bin_count_batch_in,
bin_count_batch_in_feats,
bin_count_batch_out
)
loss_fn = models.NegativeLogLikelihood_CountModel(distribution_params, distribution_name)
loss = loss_fn(bin_count_batch_out, bin_counts_pred)
step_train_loss+=loss.numpy()
grads = tape.gradient(loss, model.trainable_weights)
optimizer.apply_gradients(zip(grads, model.trainable_weights))
# print('Training loss (for one batch) at step %s: %s' %(sm_step, float(loss)))
step_cnt += 1
# Dev calculations
count_dev_pred, _ = model(count_dev_in_counts, count_dev_in_feats)
count_dev_pred_unnorm = utils.denormalize_data(count_dev_pred, count_test_normm, count_test_norms)
dev_gap_metric_mae(count_dev_pred_unnorm, count_dev_out_counts)
dev_gap_metric_mse(count_dev_pred_unnorm, count_dev_out_counts)
dev_gap_mae = dev_gap_metric_mae.result()
dev_gap_mse = dev_gap_metric_mse.result()
dev_gap_metric_mae.reset_states()
dev_gap_metric_mse.reset_states()
if best_dev_gap_mae > dev_gap_mae and patience <= epoch:
best_dev_gap_mae = dev_gap_mae
best_dev_epoch = epoch
print('Saving model at epoch', epoch)
model.save_weights(checkpoint_path)
step_train_loss /= step_cnt
print('Training loss after epoch %s: %s' %(epoch, float(step_train_loss)))
print('MAE and MSE of Dev data %s: %s' \
%(float(dev_gap_mae), float(dev_gap_mse)))
train_losses.append(step_train_loss)
dev_mae_list.append(dev_gap_mae)
if epoch%10 == 0:
_, [_, test_distribution_stddev] = model(count_test_in_counts, count_test_in_feats)
stddev_sample.append(test_distribution_stddev[0])
stddev_sample = np.array(stddev_sample)
if num_epochs>0:
for dec_idx in range(args.out_bin_sz):
plt.plot(range(len(stddev_sample)), stddev_sample[:,dec_idx], label='dec_idx_'+str(dec_idx))
plt.legend(loc='upper right')
plt.savefig(os.path.join(
args.output_dir,
'count_model_test_var_'+distribution_name+'_'+args.current_dataset+'_test_id_0.png')
)
plt.close()
plt.plot(range(len(train_losses)), train_losses)
plt.savefig(os.path.join(
args.output_dir,
'count_model_train_loss_'+distribution_name+'_'+args.current_dataset+'.png'))
plt.close()
plt.plot(range(len(dev_mae_list)), dev_mae_list)
plt.savefig(os.path.join(
args.output_dir,
'count_model_dev_mae_'+distribution_name+'_'+args.current_dataset+'.png'))
plt.close()
print("Loading best model from epoch", best_dev_epoch)
model.load_weights(checkpoint_path)
count_dev_pred, _ = model(count_dev_in_counts, count_dev_in_feats)
count_dev_pred_unnorm = utils.denormalize_data(count_dev_pred, count_test_normm, count_test_norms)
dev_gap_metric_mae(count_dev_pred_unnorm, count_dev_out_counts)
dev_gap_metric_mse(count_dev_pred_unnorm, count_dev_out_counts)
dev_gap_mae = dev_gap_metric_mae.result()
dev_gap_mse = dev_gap_metric_mse.result()
dev_gap_metric_mae.reset_states()
dev_gap_metric_mse.reset_states()
print('MAE and MSE of Dev data %s: %s' \
%(float(dev_gap_mae), float(dev_gap_mse)))
test_bin_count_pred_norm, test_distribution_params = model(count_test_in_counts, count_test_in_feats)
test_bin_count_pred = utils.denormalize_data(test_bin_count_pred_norm, count_test_normm, count_test_norms)
test_distribution_params[1] = utils.denormalize_data_stddev(test_distribution_params[1], count_test_normm, count_test_norms)
return (
model,
{
"count_all_means_pred": test_bin_count_pred.numpy(),
"count_all_sigms_pred": test_distribution_params[1]
}
)
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
# WGAN Model
def run_wgan(args, data, test_data):
'''
Return a trained wgan model
create HomogenouosPoisson sequences
- length of sequence: span the forecast horizon
- intensity: Intensity of the input sequence
Divide training data into input and output
Write expressions for D_loss and G_loss
Write training loops for the model
Add # WGAN Lipschitz constraint
'''
LAMBDA_LP = 0.1 # Penality for Lipschtiz divergence
model = models.WGAN(g_state_size=args.hidden_layer_size,
d_state_size=args.hidden_layer_size)
G_optimizer = keras.optimizers.Adam(args.learning_rate)
D_optimizer = keras.optimizers.Adam(args.learning_rate)
pre_train_optimizer = keras.optimizers.Adam(args.learning_rate)
[train_dataset_gaps,
nc_event_dev_in_gaps, nc_event_dev_in_feats, nc_event_dev_in_types,
nc_event_dev_out_gaps, nc_event_dev_out_types,
train_norm_gaps] = data
[event_train_norma, event_train_normd] = train_norm_gaps
[event_test_in_gaps, event_test_in_feats, event_test_in_types,
count_test_out_binend, event_test_in_lasttime,
event_test_norma, event_test_normd] = test_data
enc_len = args.enc_len
wgan_enc_len = args.wgan_enc_len
dec_len = args.out_bin_sz
bin_size = args.bin_size
# Generating prior fake sequence in the range of forecast horizon
# lambda0 = np.mean([len(item) for item in real_sequences])/T
# intensityPoisson = IntensityHomogenuosPoisson(lambda0)
# fake_sequences = generate_sample(intensityPoisson, T, 20000)
train_z_seqs = list()
for (gaps_batch, _, _, _, _, _) in train_dataset_gaps:
wgan_dec_len = gaps_batch.shape[1] - wgan_enc_len
times_batch = tf.cumsum(gaps_batch, axis=1)
span_batch = times_batch[:, -1] - times_batch[:, 0]
lambda0 = np.ones_like(span_batch) * gaps_batch.shape[1] / span_batch.numpy()
intensityPoisson = IntensityHomogenuosPoisson(lambda0)
output_span_batch = times_batch[:, -1] - times_batch[:, wgan_dec_len]
train_z_seqs_batch = generate_sample(intensityPoisson, wgan_dec_len, lambda0.shape[0])
train_z_seqs += train_z_seqs_batch
train_z_seqs = tf.convert_to_tensor(train_z_seqs)
dev_z_seqs = list()
dev_data_gaps = nc_event_dev_in_gaps
dev_data_feats = nc_event_dev_in_feats
wgan_dec_len = dev_data_gaps.shape[1] - wgan_enc_len
dev_data_times = tf.cumsum(dev_data_gaps, axis=1)
dev_span = dev_data_times[:, wgan_enc_len-1] - dev_data_times[:, 0]
lambda0 = np.ones_like(dev_span) * dev_data_gaps.shape[1] / dev_span.numpy()
intensityPoisson = IntensityHomogenuosPoisson(lambda0)
dev_z_seqs = generate_sample(intensityPoisson, wgan_dec_len, lambda0.shape[0])
dev_z_seqs = tf.convert_to_tensor(dev_z_seqs)
#dev_z_seqs = utils.normalize_avg_given_param(dev_z_seqs,
# event_train_norma,
# event_train_normd)
os.makedirs(args.saved_models+'/training_wgan_'+args.current_dataset+'/', exist_ok=True)
checkpoint_path = args.saved_models+"/training_wgan_"+args.current_dataset+"/cp_"+args.current_dataset+".ckpt"
best_dev_gap_mse = np.inf
best_dev_gap_mae = np.inf
best_dev_epoch = 0
# pre-train wgan model
pre_train_losses = list()
print('pre-training started')
bch_cnt = 0
#for sm_step, (gaps_batch, _) in enumerate(train_dataset_gaps):
# gaps_batch_in = gaps_batch[:, :wgan_enc_len]
# gaps_batch_out = gaps_batch[:, wgan_enc_len:]
# train_z_seqs_batch = train_z_seqs[sm_step*args.batch_size:(sm_step+1)*args.batch_size]
# with tf.GradientTape() as pre_train_tape:
# gaps_pred = model.generator(train_z_seqs_batch, gaps_batch_in)
# bch_pre_train_loss = tf.reduce_mean(tf.abs(gaps_pred - gaps_batch_out))
#
# pre_train_losses.append(bch_pre_train_loss.numpy())
#
# pre_train_grads = pre_train_tape.gradient(bch_pre_train_loss, model.trainable_weights)
# pre_train_optimizer.apply_gradients(zip(pre_train_grads, model.trainable_weights))
# bch_cnt += 1
#print('pre-training done, losses=', pre_train_losses)
## pre-train done
if args.use_wgan_d:
print(' Training with discriminator')
else:
print(' Training without discriminator')
train_losses = list()
for epoch in range(args.epochs):
print('Starting epoch', epoch)
step_train_loss = 0.0
step_cnt = 0
next_initial_state = None
for sm_step, (gaps_batch, feats_batch, _, _, _, _) \
in enumerate(train_dataset_gaps):
gaps_batch_in = gaps_batch[:, :wgan_enc_len]
feats_batch_in = feats_batch[:, :wgan_enc_len]
gaps_batch_out = gaps_batch[:, wgan_enc_len:]
feats_batch_out = feats_batch[:, wgan_enc_len:]
train_z_seqs_batch = train_z_seqs[sm_step*args.batch_size:(sm_step+1)*args.batch_size]
with tf.GradientTape() as g_tape, tf.GradientTape() as d_tape:
gaps_pred = model.generator(train_z_seqs_batch,
enc_inputs=gaps_batch_in,
enc_feats=feats_batch_in)
if args.use_wgan_d:
D_pred = model.discriminator(gaps_batch_in, gaps_pred)
D_true = model.discriminator(gaps_batch_in, gaps_batch_out)
D_loss = tf.reduce_mean(D_pred) - tf.reduce_mean(D_true)
G_loss = -tf.reduce_mean(D_pred)
# Adding Lipschitz Constraint
length_ = tf.minimum(tf.shape(gaps_batch_out)[1],tf.shape(gaps_pred)[1])
lipschtiz_divergence = tf.abs(D_true-D_pred)/tf.sqrt(tf.reduce_sum(tf.square(gaps_batch_out[:,:length_,:]-gaps_pred[:,:length_,:]), axis=[1,2])+0.00001)
lipschtiz_divergence = tf.reduce_mean((lipschtiz_divergence-1)**2)
D_loss += LAMBDA_LP*lipschtiz_divergence
else:
length_ = tf.minimum(tf.shape(gaps_batch_out)[1],tf.shape(gaps_pred)[1])
gaps_pred_cumsum = tf.cumsum(gaps_pred, axis=1)
gaps_batch_out_cumsum = tf.cumsum(gaps_batch_out, axis=1)
G_loss = tf.reduce_mean(tf.sqrt(tf.reduce_sum(tf.square(gaps_batch_out_cumsum[:,:length_,:]-gaps_pred_cumsum[:,:length_,:]), axis=[1,2])+0.00001))
step_train_loss += G_loss.numpy()
G_grads = g_tape.gradient(G_loss, model.trainable_weights)
G_optimizer.apply_gradients(zip(G_grads, model.trainable_weights))
if args.use_wgan_d:
D_grads = d_tape.gradient(D_loss, model.trainable_weights)
D_optimizer.apply_gradients(zip(D_grads, model.trainable_weights))
train_gap_metric_mae(gaps_batch_out, gaps_pred)
train_gap_metric_mse(gaps_batch_out, gaps_pred)
train_gap_mae = train_gap_metric_mae.result()
train_gap_mse = train_gap_metric_mse.result()
train_gap_metric_mae.reset_states()
train_gap_metric_mse.reset_states()
# print(float(train_gap_mae), float(train_gap_mse))
# print('Training loss (for one batch) at step %s: %s' %(sm_step, float(loss)))
print('Training loss (for one batch) at step %s: %s' %(sm_step, float(G_loss)))
step_cnt += 1
# Dev calculations
nc_event_dev_in_gaps = dev_data_gaps[:, :wgan_enc_len]
nc_event_dev_in_feats = dev_data_feats[:, :wgan_enc_len]
nc_event_dev_out_gaps = dev_data_gaps[:, wgan_enc_len:]
dev_gaps_pred = model.generator(dev_z_seqs,
enc_inputs=nc_event_dev_in_gaps,
enc_feats=nc_event_dev_in_feats)
dev_gaps_pred_unnorm = utils.denormalize_avg(dev_gaps_pred,
event_train_norma, event_train_normd)