-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodels.py
1224 lines (1039 loc) · 63.7 KB
/
models.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
from __future__ import absolute_import
from __future__ import division
#from __future__ import print_function
import pandas as pd
import numpy as np
import tensorflow as tf
import tensorflow.contrib.cudnn_rnn as cudnn_rnn
import tensorflow_probability as tfp
tfd = tfp.distributions
from tensorflow.contrib import rnn
from tensorflow.python.ops import array_ops, math_ops
import sru
import fru
import AdaptRegression as ar
import ARU as aru
from walmart_sales_utils import getWalmartEmbeddingTransform
from electricity_utils import getEmbeddingElectricity
from trafficPEMS_utils import getEmbeddingTraffic
from RossmanUtils import transformInput
from oneC_utils import getEmbeddingOneC
from temporal_conv_utils import temporal_convolution_layer
class Models():
def __init__(self, params, inputPh, lagPh, outputPh, maxYYPh, tsIndicesPh, maskPh,
keep_prob, alpha_list,
mode, numFW, aruDims, feature_dict, emb_dict, numTs):
self.inputPh = inputPh
self.lagPh = lagPh
self.outputPh = outputPh
self.maxYYPh = maxYYPh
self.tsIndicesPh = tsIndicesPh
self.maskPh = maskPh
self.feature_dict = feature_dict
self.emb_dict = emb_dict
self.rnnType = params.rnnType
self.decoderType = params.decoderType
self.isSRUFeat = params.isSRUFeat
self.isLagFeat = params.isLagFeat
self.num_layers = params.num_layers
self.encoder_length = params.encoder_length
self.sequence_length = params.sequence_length
self.decoder_length = params.decoder_length
self.lstm_dense_layer_size = params.lstm_dense_layer_size
self.hidden1 = params.hidden1
self.hidden2 = params.hidden2
self.keep_prob = keep_prob
self.sru_num_stats = params.sru_num_stats
self.alpha_list = alpha_list
self.recur_dims = params.recur_dims
self.num_nodes = params.num_nodes
self.isNormalised = params.isNormalised
self.deep_ar_normalize = params.deep_ar_normalize
self.aru_deepar_normalize = params.aru_deepar_normalize
self.mode = mode
self.numFW = numFW
self.step_length = params.stepLen
self.seed = params.seed
self.num_projs = params.numProjs
self.fullLinear = params.fullLinear
self.dataset = params.dataset
self.numY = params.numY
self.modelToRun = params.modelToRun
self.aruDims = aruDims
self.aruRegularizer = params.aruRegularizer
self.is_maru_loss = params.is_maru_loss
self.is_probabilistic_pred = params.is_probabilistic_pred
self.aru_alpha = params.aru_alpha
self.numTs = numTs
self.maskPh = tf.squeeze(tf.cast(self.maskPh, tf.bool), axis=1)
self.inputPh = tf.boolean_mask(self.inputPh, self.maskPh)
self.lagPh = tf.boolean_mask(self.lagPh, self.maskPh)
self.outputPh = tf.boolean_mask(self.outputPh, self.maskPh)
self.maxYYPh = tf.boolean_mask(self.maxYYPh, self.maskPh)
self.tsIndicesPh = tf.boolean_mask(self.tsIndicesPh, self.maskPh)
self.inputPhEmbd = self.getEmbeddingTransform()
self.inputEnc = tf.concat([self.inputPhEmbd[:, :self.encoder_length, :],
self.lagPh[:, :self.encoder_length, :]],
axis=2)
self.inputDec = tf.concat([self.inputPhEmbd[:, self.encoder_length:, :],
self.lagPh[:, self.encoder_length:, 1:]], # inputDec shouldn't get prevY, which is at lagPh[:, :, 0]
axis=2)
self.outputEnc = self.outputPh[:, :self.encoder_length, 0]
self.outputDec = self.outputPh[:, self.encoder_length:self.sequence_length, 0]
def getEmbeddingTransform(self):
inputPhEmbd = []
for feature, idx in self.feature_dict.items():
#print(feature, idx, feature in self.emb_dict.keys())
if feature not in self.emb_dict.keys():
inputPhEmbd.append(self.inputPh[:, :, idx:idx+1])
else:
num_vals, emb_size = self.emb_dict[feature]
v_index = tf.Variable(tf.random_uniform([num_vals, emb_size], -1.0, 1.0, seed=12))
#v_index = tf.Print(v_index, [self.inputPh[:, :, idx]])
em_index = tf.nn.embedding_lookup(v_index, tf.cast(self.inputPh[:, :, idx], tf.int32))
inputPhEmbd.append(em_index)
if self.inputPh.get_shape().as_list()[2] == 0:
X_embd = self.inputPh
else:
X_embd = tf.concat(inputPhEmbd, axis=2)
return X_embd
def sru_cell(self):
return sru.SimpleSRUCell(num_stats=self.sru_num_stats, mavg_alphas=tf.get_variable('alphas',
initializer=tf.constant(self.alpha_list), trainable=False),
output_dims=self.num_nodes, recur_dims=self.recur_dims)
#LSTM Cell
def lstm_cell(self):
return tf.contrib.rnn.BasicLSTMCell(self.num_nodes, forget_bias=1.0)
#Kind of Cell required
def get_cell(self):
if self.rnnType == "lstm":
#print ("getting lstm")
return self.lstm_cell()
elif self.rnnType == "sru":
#print ("getting sru")
return self.sru_cell()
def expMovAvg(self, y, alpha):
expAvg = list()
expAvg.append(tf.expand_dims(y[:,0], axis=1))
for i in range(1, y.get_shape().as_list()[1]):
avg = alpha * expAvg[-1] + (1 - alpha) * tf.expand_dims(y[:, i], axis=1)
expAvg.append(avg)
expAvg = tf.concat(expAvg, axis=1)
return expAvg
def multiScaleAverage(self, outputEncN):
avgOutputs = list()
for alpha in self.alpha_list:
avgOutput = self.expMovAvg(outputEncN, alpha)
avgOutputs.append(tf.expand_dims(avgOutput, axis=2))
avgOutputs = tf.concat(avgOutputs, axis=2)
return avgOutputs
def encodeInput(self):
if self.rnnType in ['lstm']:
self.cell = tf.contrib.rnn.MultiRNNCell([self.get_cell() for _ in range(self.num_layers)],
state_is_tuple=True)
state = self.cell.zero_state(tf.shape(self.inputEnc)[0], dtype = tf.float32)
elif self.rnnType in ['cudnn_lstm']:
self.cell = cudnn_rnn.CudnnLSTM(num_layers=self.num_layers, num_units=self.num_nodes,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed),
direction='unidirectional',
seed=self.seed)
elif self.rnnType in ['feed_forward']:
inputs = self.inputEnc
for l in range(self.num_layers):
inputs = tf.layers.dense(inputs, self.num_nodes, activation=tf.nn.relu)
cell_outputs, state = inputs, None
if self.rnnType in ['lstm']:
cell_outputs = list()
for i in range(self.encoder_length):
cell_output, state = self.cell(self.inputEnc[:, i, :], state)
cell_outputs.append(tf.expand_dims(cell_output, axis=1))
cell_outputs = tf.concat(cell_outputs, axis=1)
elif self.rnnType in ['cudnn_lstm']:
cell_outputs, (h_state, c_state) = self.cell(tf.transpose(self.inputEnc, [1, 0, 2]))
cell_outputs = tf.transpose(cell_outputs, [1, 0, 2])
state = (h_state, c_state)
elif self.rnnType in ['feed_forward']:
pass
return cell_outputs, state
def decoder(self):
self.decoder_cell = cudnn_rnn.CudnnLSTM(num_layers=1, num_units=self.hidden1,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed),
direction='unidirectional',
seed=self.seed)
decoder_input = tf.concat([self.inputPhEmbd, self.lagPh[:, :, 1:]], axis=1)
decoder_outputs, (h_state, c_state) = self.decoder_cell(tf.transpose(decoder_input, [1, 0, 2]))
decoder_outputs = tf.transpose(decoder_outputs, [1, 0, 2])
return decoder_outputs, h_state, c_state
def nn_pass(self, inputS):
with tf.variable_scope('nn_pass', reuse=tf.AUTO_REUSE):
nn_input = tf.layers.dense(inputS, self.hidden1, activation=tf.nn.relu, name='hidden1_layer',
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
#nn_input = tf.nn.dropout(nn_input, self.keep_prob, name='dropout_layer', seed=self.seed)
nn_input = tf.layers.dense(nn_input, self.hidden2, activation=tf.nn.relu, name='hidden2_layer',
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
y_pred_nn = tf.layers.dense(inputs=nn_input, units=1, activation=None, name='Ouptput_layer',
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
return nn_input, y_pred_nn
def getARUModel(self):
tf.set_random_seed(self.seed)
if self.deep_ar_normalize:
#Normalise y
avg_output = tf.expand_dims((1 + tf.reduce_mean(self.outputDec, axis=1)), axis=1)
outputDecN = self.outputDec/avg_output
else:
outputDecN = self.outputDec
if self.isSRUFeat:
self.sru_states = self.multiScaleAverage(self.inputEnc[:, :, 0])
sru_state = tf.tile(tf.expand_dims(self.sru_states[:, -1, :], dim=1), [1, self.decoder_length, 1])
cell_outputs, state = self.encodeInput()
cell_output = cell_outputs[:, -1, :] if self.rnnType not in ['feed_forward'] else cell_outputs
lstm_out_dense = tf.layers.dense(inputs=cell_output,
units=self.lstm_dense_layer_size,
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
if self.rnnType not in ['feed_forward']:
lstm_out_dense = tf.tile(tf.expand_dims(lstm_out_dense, dim=1), [1, self.decoder_length, 1])
adapt_regression = aru.ARU(self.aruDims,
self.numTs,
num_y=self.numY, num_projs=self.num_projs,
full_linear=self.fullLinear,
regularizer=self.aruRegularizer,
proj_vecs=None,
aru_alpha=self.aru_alpha)
if self.modelToRun in ['enc_aru']:
adapt_input = self.inputPh[:, self.encoder_length-self.step_length:self.encoder_length, :]
adapt_labels = tf.expand_dims(self.outputEnc[:, self.encoder_length-self.step_length:self.encoder_length], 2)
#adapt_input = self.inputPh[:, :self.encoder_length, :]
#adapt_labels = tf.expand_dims(self.outputEnc, 2)
elif self.modelToRun in ['dec_aru']:
adapt_input = self.inputPh[:, self.encoder_length:self.encoder_length+self.step_length, :]
adapt_labels = tf.expand_dims(self.outputDec[:, :self.step_length], 2)
output_h, _ = adapt_regression.predict(self.inputPh[:, self.encoder_length:, :], self.tsIndicesPh, self.maskPh)
#output_h = tf.Print(output_h, [tf.reduce_sum(tf.cast(tf.is_nan(output_h), tf.int32))])
if self.aru_deepar_normalize:
avg_aru_output = tf.expand_dims((1 + tf.reduce_mean(output_h, axis=1)), axis=1)
output_h = output_h / avg_aru_output
with tf.control_dependencies([output_h]):
adapted_states = adapt_regression.adapt(adapt_input, adapt_labels, self.tsIndicesPh, self.maskPh)
#output_h = tf.Print(output_h, [tf.reduce_sum(tf.cast(tf.is_nan(self.inputPhEmbd), tf.int32))])
nn_input = tf.concat([self.inputDec, lstm_out_dense, output_h], axis=2)
if self.isSRUFeat:
nn_input = tf.concat([nn_input, sru_state], axis=2)
nn_input, y_pred_nn = self.nn_pass(nn_input)
y_pred_nn = tf.squeeze(y_pred_nn, [2])
y_pred_nn = y_pred_nn# * self.maskPh
#outputDecN *= self.maskPh
if self.is_probabilistic_pred:
mu = y_pred_nn
sigma = tf.layers.dense(inputs=nn_input, units=1, activation=tf.nn.softplus,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
sigma = tf.squeeze(sigma, [2])
dist = tfd.Normal(loc=mu, scale=sigma)
log_likelihood = dist.log_prob(outputDecN)
#log_likelihood *= self.maskPh
loss = -1.0 * tf.reduce_sum(log_likelihood)
self.sigma = sigma
else:
loss = tf.reduce_sum(tf.square(y_pred_nn - outputDecN))
if self.deep_ar_normalize:
#Rescale y
y_pred_nn = y_pred_nn*avg_output
self.reset_op = adapt_regression.reset_states()
self.loss = loss
self.y_pred_nn = y_pred_nn
return loss, y_pred_nn, adapted_states
def getModifiedARUModel(self):
tf.set_random_seed(self.seed)
if self.deep_ar_normalize:
#Normalise y
avg_output = tf.expand_dims((1 + tf.reduce_mean(self.outputDec, axis=1)), axis=1)
outputDecN = self.outputDec/avg_output
avg_enc_output = tf.expand_dims((1 + tf.reduce_mean(self.outputEnc, axis=1)), axis=1)
outputEncN = self.outputEnc/avg_enc_output
else:
outputDecN = self.outputDec
outputEncN = self.outputEnc
cell_outputs, state = self.encodeInput() # encoder pass.
cell_output = cell_outputs[:, -1, :] if self.rnnType not in ['feed_forward'] else cell_outputs
lstm_out_dense = tf.layers.dense(inputs=cell_output,
units=self.lstm_dense_layer_size,
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
if self.rnnType not in ['feed_forward']:
lstm_out_dense = tf.tile(tf.expand_dims(lstm_out_dense, axis=1), [1, self.decoder_length, 1])
if self.isSRUFeat or self.modelToRun in ['maruX_sruAugment']:
sru_state = self.multiScaleAverage()
sru_state = tf.tile(tf.expand_dims(sru_state, dim=1), [1, self.decoder_length, 1])
if self.modelToRun in ['maruY']:
with tf.variable_scope('y_decomposition', reuse=tf.AUTO_REUSE):
y_latent = tf.layers.dense(tf.expand_dims(self.outputDec, axis=2), self.numY, activation=tf.nn.relu)
# Add a dropout layer during training
y_latent = tf.cond(tf.equal(self.mode, 1.0),
lambda: tf.nn.dropout(y_latent, 0.8, name='dropout_layer'),
lambda: y_latent)
y_reconst = tf.layers.dense(y_latent, 1, activation=None, name='reconst_layer')
# Fix adapt_input
if self.modelToRun in ['maruY']:
adapt_input = self.inputPh[:,self.encoder_length:self.encoder_length+self.step_length, :]
aruInput = self.inputPh[:, self.encoder_length:, :]
elif self.modelToRun in ['maruX_sruAugment']:
adapt_input = tf.concat([sru_state[:, self.encoder_length:self.encoder_length+self.step_length, :],
self.inputPh[:, self.encoder_length:self.encoder_length+self.step_length, :]],
axis=2)
aruInput = self.inputPh[:, self.encoder_length:, :]
elif self.modelToRun in ['maruX_rnnAugment']:
adapt_input = tf.concat([lstm_out_dense[:, self.encoder_length:self.encoder_length+self.step_length, :],
self.inputPh[:, self.encoder_length:self.encoder_length+self.step_length, :]],
axis=2)
aruInput = self.inputPh[:, self.encoder_length:, :]
elif self.modelToRun in ['maruX']:
def nn_pass_maruX(nn_input):
with tf.variable_scope('nn_pass_maruX', reuse=tf.AUTO_REUSE):
nn_input = tf.layers.dense(nn_input, self.hidden1, activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
adapt_input = tf.layers.dense(nn_input, self.hidden2, activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
return adapt_input
nn_input = self.inputPh[:, self.encoder_length:self.encoder_length+self.step_length, :]
adapt_input = nn_pass_maruX(nn_input)
aruInput = self.inputPh[:, self.encoder_length:, :]
aruInput = nn_pass_maruX(aruInput)
# Fix adapt_output
if self.modelToRun in ['maruY']:
adapt_labels = y_latent[:, :self.step_length, :]
elif self.modelToRun in ['maruX_sruAugment', 'maruX_rnnAugment', 'maruX']:
adapt_labels = tf.expand_dims(self.outputDec[:, :self.step_length], axis=2)
adapt_regression = aru.ARU(self.aruDims,
self.numTs,
num_y=self.numY,
num_projs=self.num_projs,
full_linear=self.fullLinear,
regularizer=self.aruRegularizer,
aru_alpha=self.aru_alpha)
output_h, _ = adapt_regression.predict(aruInput, self.tsIndicesPh, self.maskPh)
if self.aru_deepar_normalize:
avg_aru_output = tf.expand_dims((1 + tf.reduce_mean(output_h, axis=1)), axis=1)
output_h = output_h / avg_aru_output
with tf.control_dependencies([output_h]):
adapted_states = adapt_regression.adapt(adapt_input, adapt_labels, self.tsIndicesPh, self.maskPh)
nn_input = tf.concat([self.inputDec, lstm_out_dense, output_h], axis=2)
if self.modelToRun in ['maruX']:
nn_input = tf.concat([nn_input, aruInput], axis=2)
nn_input, y_pred_nn = self.nn_pass(nn_input)
y_pred_nn = tf.squeeze(y_pred_nn,[2])
y_pred_nn = y_pred_nn# * self.maskPh
#outputDecN *= self.maskPh
if self.is_probabilistic_pred:
mu = y_pred_nn
sigma = tf.layers.dense(inputs=nn_input, units=1, activation=tf.nn.softplus,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
sigma = tf.squeeze(sigma, [2])
dist = tfd.Normal(loc=mu, scale=sigma)
log_likelihood = dist.log_prob(outputDecN)
#log_likelihood *= self.maskPh
loss = -1.0 * tf.reduce_sum(log_likelihood)
self.sigma = sigma
else:
loss = tf.reduce_sum(tf.square(y_pred_nn - outputDecN))
if self.is_maru_loss:
y_pred_global = tf.layers.dense(inputs=aruInput, units=1, activation=None, name='globalOutputLayer',
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
loss += tf.reduce_sum(tf.square(tf.squeeze(y_pred_global, axis=2) - outputDecN))
if self.modelToRun in ['maruY']:
loss += tf.reduce_sum(tf.square(tf.squeeze(y_reconst, axis=2) - self.outputDec))
if self.deep_ar_normalize:
#Rescale y
y_pred_nn = y_pred_nn*avg_output
self.reset_op = adapt_regression.reset_states()
self.loss = loss
self.y_pred_nn = y_pred_nn
return loss, y_pred_nn, adapted_states
def getModifiedEncARUModel(self):
tf.set_random_seed(self.seed)
if self.deep_ar_normalize:
#Normalise y
avg_output = tf.expand_dims((1 + tf.reduce_mean(self.outputDec, axis=1)), axis=1)
outputDecN = self.outputDec/avg_output
avg_enc_output = tf.expand_dims((1 + tf.reduce_mean(self.outputEnc, axis=1)), axis=1)
outputEncN = self.outputEnc/avg_enc_output
else:
outputDecN = self.outputDec
outputEncN = self.outputEnc
cell_outputs, state = self.encodeInput() # encoder pass.
cell_output = cell_outputs if self.rnnType not in ['feed_forward'] else cell_outputs
lstm_out_dense = tf.layers.dense(inputs=cell_output,
units=self.lstm_dense_layer_size,
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
if self.rnnType not in ['feed_forward']:
lstm_out_dense = tf.tile(tf.expand_dims(lstm_out_dense[:,-1,:], axis=1), [1, self.decoder_length, 1])
if self.isSRUFeat or self.modelToRun in ['mEncAruX_sruAugment']:
sru_state = self.multiScaleAverage(outputEncN)
#sru_state = tf.tile(tf.expand_dims(sru_state, dim=1), [1, self.decoder_length, 1])
if self.modelToRun in ['mEncAruY']:
with tf.variable_scope('y_decomposition', reuse=tf.AUTO_REUSE):
y_latent = tf.layers.dense(tf.expand_dims(self.outputEnc, axis=2), self.numY, activation=tf.nn.relu)
# Add a dropout layer during training
y_latent = tf.cond(tf.equal(self.mode, 1.0),
lambda: tf.nn.dropout(y_latent, 0.7, name='dropout_layer'),
lambda: y_latent)
y_reconst = tf.layers.dense(y_latent, 1, activation=None, name='reconst_layer')
# Fix adapt_input
if self.modelToRun in ['mEncAruX']:
nn_input = self.inputPh[:,:self.step_length,:]
def nn_pass_mEncAruX(nn_input):
with tf.variable_scope('nn_pass_mEncAruX', reuse=tf.AUTO_REUSE):
nn_input = tf.layers.dense(nn_input, self.hidden1, activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
adapt_input = tf.layers.dense(nn_input, self.hidden2, activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
return adapt_input
adapt_input = nn_pass_mEncAruX(nn_input)
aruInput = self.inputPh[:,self.encoder_length:,:]
aruInput = nn_pass_mEncAruX(aruInput)
elif self.modelToRun in ['mEncAruY']:
adapt_input = self.inputPh[:,:self.step_length,:]
aruInput = self.inputPh[:,self.encoder_length:,:]
elif self.modelToRun in ['mEncAruX_sruAugment']:
adapt_input = tf.concat([sru_state[:,:self.step_length,:], self.inputPh[:,:step_length,:]], axis=2)
aruInput = tf.concat([tf.tile(tf.expand_dims(sru_state[:,-1,:], axis=1),
[1, self.decoder_length, 1]),
self.inputPh[:,self.encoder_length:,:]], axis=2)
elif self.modelToRun in ['mEncAruX_rnnAugment']:
adapt_input = tf.concat([lstm_out_dense, self.inputPh[:,:self.step_length,:]], axis=2)
aruInput = tf.concat([lstm_out_dense, self.inputPh[:,self.encoder_length:,:]], axis=2)
# Fix adapt_output
if self.modelToRun in ['mEncAruY']:
adapt_labels = y_latent[:,:self.step_length,:]
elif self.modelToRun in ['mEncAruX_sruAugment','mEncAruX_rnnAugment','mEncAruX']:
adapt_labels = tf.expand_dims(self.outputEnc[:,:self.step_length], axis=2)
adapt_regression = aru.ARU(self.aruDims,
self.numTs,
num_y=self.numY,
num_projs=self.num_projs,
full_linear=self.fullLinear,
regularizer=self.aruRegularizer,
aru_alpha=self.aru_alpha)
output_h,_ = adapt_regression.predict(aruInput, self.tsIndicesPh, self.maskPh)
if self.aru_deepar_normalize:
avg_aru_output = tf.expand_dims((1 + tf.reduce_mean(output_h, axis=1)), axis=1)
output_h = output_h / avg_aru_output
with tf.control_dependencies([output_h]):
adapted_states = adapt_regression.adapt(adapt_input, adapt_labels, self.tsIndicesPh, self.maskPh)
nn_input = tf.concat([self.inputDec, lstm_out_dense, output_h], axis=2)
if self.modelToRun in ['mEncAruX']:
nn_input = tf.concat([nn_input, aruInput], axis=2)
nn_input, y_pred_nn = self.nn_pass(nn_input)
y_pred_nn = tf.squeeze(y_pred_nn,[2])
y_pred_nn = y_pred_nn# * self.maskPh
#outputDecN *= self.maskPh
if self.is_probabilistic_pred:
mu = y_pred_nn
sigma = tf.layers.dense(inputs=nn_input, units=1, activation=tf.nn.softplus,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
sigma = tf.squeeze(sigma, [2])
dist = tfd.Normal(loc=mu, scale=sigma)
log_likelihood = dist.log_prob(outputDecN)
#log_likelihood *= self.maskPh
loss = -1.0 * tf.reduce_sum(log_likelihood)
self.sigma = sigma
else:
loss = tf.reduce_sum(tf.square(y_pred_nn - outputDecN))
if self.modelToRun in ['mEncAruY']:
loss += tf.reduce_sum(tf.square(tf.squeeze(y_reconst, axis=2) - self.outputEnc))
if self.deep_ar_normalize:
#Rescale y
y_pred_nn = y_pred_nn*avg_output
self.reset_op = adapt_regression.reset_states()
self.loss = loss
self.y_pred_nn = y_pred_nn
return loss, y_pred_nn, adapted_states
def getModifiedEncARUModelOld(self):
tf.set_random_seed(self.seed)
if self.deep_ar_normalize:
#Normalise y
avg_output = tf.expand_dims((1 + tf.reduce_mean(self.outputDec, axis=1)), axis=1)
outputDecN = self.outputDec/avg_output
avg_enc_output = tf.expand_dims((1 + tf.reduce_mean(self.outputEnc, axis=1)), axis=1)
outputEncN = self.outputEnc/avg_enc_output
else:
outputDecN = self.outputDec
outputEncN = self.outputEnc
cell_outputs, state = self.encodeInput() # encoder pass.
cell_output = cell_outputs
lstm_out_dense = tf.layers.dense(inputs=cell_output,
units=self.lstm_dense_layer_size,
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
lstm_out_dense = tf.tile(tf.expand_dims(lstm_out_dense[:,-1,:], axis=1), [1, self.decoder_length, 1])
if self.isSRUFeat or self.modelToRun in ['mEncAruX_sruAugment']:
sru_state = self.multiScaleAverage(outputEncN)
#sru_state = tf.tile(tf.expand_dims(sru_state, dim=1), [1, self.decoder_length, 1])
if self.modelToRun in ['mEncAruY']:
with tf.variable_scope('y_decomposition', reuse=tf.AUTO_REUSE):
y_latent = tf.layers.dense(tf.expand_dims(self.outputEnc, axis=2), self.numY, activation=tf.nn.relu)
# Add a dropout layer during training
y_latent = tf.cond(tf.equal(self.mode, 1.0),
lambda: tf.nn.dropout(y_latent, 0.7, name='dropout_layer'),
lambda: y_latent)
y_reconst = tf.layers.dense(y_latent, 1, activation=None, name='reconst_layer')
# Fix adapt_input
if self.modelToRun in ['mEncAruX']:
nn_input = self.inputPh[:,:self.step_length,:]
def nn_pass_mEncAruX(nn_input):
with tf.variable_scope('nn_pass_mEncAruX', reuse=tf.AUTO_REUSE):
nn_input = tf.layers.dense(nn_input, self.hidden1, activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
adapt_input = tf.layers.dense(nn_input, self.hidden2, activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
return adapt_input
adapt_input = nn_pass_mEncAruX(nn_input)
aruInput = self.inputPh[:,self.encoder_length:,:]
aruInput = nn_pass_mEncAruX(aruInput)
elif self.modelToRun in ['mEncAruY']:
adapt_input = self.inputPh[:,:self.step_length,:]
aruInput = self.inputPh[:,self.encoder_length:,:]
elif self.modelToRun in ['mEncAruX_sruAugment']:
adapt_input = tf.concat([sru_state[:,:self.step_length,:], self.inputPh[:,:step_length,:]], axis=2)
aruInput = tf.concat([tf.tile(tf.expand_dims(sru_state[:,-1,:], axis=1),
[1, self.decoder_length, 1]),
self.inputPh[:,self.encoder_length:,:]], axis=2)
elif self.modelToRun in ['mEncAruX_rnnAugment']:
adapt_input = tf.concat([lstm_out_dense, self.inputPh[:,:self.step_length,:]], axis=2)
aruInput = tf.concat([lstm_out_dense, self.inputPh[:,self.encoder_length:,:]], axis=2)
# Fix adapt_output
if self.modelToRun in ['mEncAruY']:
adapt_labels = y_latent[:,:self.step_length,:]
elif self.modelToRun in ['mEncAruX_sruAugment','mEncAruX_rnnAugment','mEncAruX']:
adapt_labels = tf.expand_dims(self.outputEnc[:,:self.step_length], axis=2)
adapt_regression = aru.ARU(self.aruDims, self.numTs, num_y=self.numY, num_projs=self.num_projs,
full_linear=self.fullLinear, regularizer=self.aruRegularizer)
output_h,ar_state_tuple = adapt_regression.predict(aruInput, self.tsIndicesPh, self.maskPh)
adapted_states = adapt_regression.adapt(adapt_input, adapt_labels, self.tsIndicesPh, self.maskPh)
nn_input = tf.concat([self.inputDec, lstm_out_dense, output_h], axis=2)
if self.modelToRun in ['mEncAruX']:
nn_input = tf.concat([nn_input, aruInput], axis=2)
_, y_pred_nn = self.nn_pass(nn_input)
y_pred_nn = tf.squeeze(y_pred_nn,[2])
y_pred_nn = y_pred_nn# * self.maskPh
#outputDecN *= self.maskPh
loss = tf.reduce_sum(tf.square(y_pred_nn - outputDecN))
if self.modelToRun in ['mEncAruY']:
loss += tf.reduce_sum(tf.square(tf.squeeze(y_reconst, axis=2) - self.outputEnc))
if self.deep_ar_normalize:
#Rescale y
y_pred_nn = y_pred_nn*avg_output
self.reset_op = adapt_regression.reset_states()
self.loss = loss
self.y_pred_nn = y_pred_nn
return loss, y_pred_nn, ar_state_tuple
def getFullyLocalModel(self):
tf.set_random_seed(self.seed)
if self.deep_ar_normalize:
#Normalise y
avg_output = tf.expand_dims((1 + tf.reduce_mean(self.outputDec, axis=1)), axis=1)
outputDecN = self.outputDec/avg_output
avg_enc_output = tf.expand_dims((1 + tf.reduce_mean(self.outputEnc, axis=1)), axis=1)
outputEncN = self.outputEnc/avg_enc_output
else:
outputDecN = self.outputDec
outputEncN = self.outputEnc
adapt_regression = aru.ARU(self.aruDims,
self.numTs,
num_y=self.numY,
num_projs=self.num_projs,
full_linear=self.fullLinear,
regularizer=self.aruRegularizer,
aru_alpha=self.aru_alpha)
if self.modelToRun in ['localEncAru']:
adapt_input = self.inputPh[:, self.encoder_length-self.step_length:self.encoder_length, :]
adapt_labels = tf.expand_dims(self.outputEnc[:, self.encoder_length-self.step_length:self.encoder_length], 2)
elif self.modelToRun in ['localDecAru']:
adapt_input = self.inputPh[:, self.encoder_length:self.encoder_length+self.step_length, :]
adapt_labels = tf.expand_dims(self.outputDec[:, :self.step_length], 2)
output_h, _ = adapt_regression.predict(self.inputPh[:, self.encoder_length:, :], self.tsIndicesPh, self.maskPh)
#output_h = tf.Print(output_h, [ar_state_tuple[2]])
adapted_states = adapt_regression.adapt(adapt_input, adapt_labels, self.tsIndicesPh, self.maskPh)
y_pred_nn = output_h[:, :, 0]
#y_pred_nn = tf.squeeze(y_pred_nn, axis=2)
y_pred_nn = y_pred_nn# * self.maskPh
#outputDecN *= self.maskPh
loss = tf.reduce_sum(tf.square(y_pred_nn - outputDecN))
if self.deep_ar_normalize:
#Rescale y
y_pred_nn = y_pred_nn*avg_output
self.reset_op = adapt_regression.reset_states()
self.loss = loss
self.y_pred_nn = y_pred_nn
return loss, y_pred_nn, adapted_states
def getBaselineModel(self):
tf.set_random_seed(self.seed)
if self.deep_ar_normalize:
#Normalise y
avg_output = tf.expand_dims((1 + tf.reduce_mean(self.outputDec, axis=1)), axis=1)
outputDecN = self.outputDec/avg_output
else:
outputDecN = self.outputDec
cell_outputs, state = self.encodeInput()
if self.rnnType in ['cudnn_lstm']:
h_state, c_state = state
else:
encoder_state = state
cell_output = cell_outputs[:, -1, :]
log_likelihood = list()
y_pred_nn = list()
sigma_pred_nn = list()
for i in range(self.decoder_length):
with tf.variable_scope('lstm_out_dense', reuse=tf.AUTO_REUSE):
lstm_out_dense = tf.layers.dense(inputs=cell_output,
units=self.lstm_dense_layer_size,
activation=tf.nn.relu, name='lstm_out_dense',
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
lstm_out_dense = tf.expand_dims(lstm_out_dense, axis=1)
nn_input = tf.expand_dims(self.inputDec[:, i, :], axis=1)
nn_input_concat = tf.concat([nn_input, lstm_out_dense],axis=2)
nn_input_concat, y_pred_nn_ = self.nn_pass(nn_input_concat)
y_pred_nn_ = tf.squeeze(y_pred_nn_, axis=2)
y_pred_nn.append(y_pred_nn_)
next_input = tf.cond(tf.equal(self.mode, 1.0),
lambda: tf.concat([outputDecN[:, i:i+1], self.inputDec[:, i, :]], axis=1),
lambda: tf.concat([y_pred_nn_, self.inputDec[:, i, :]], axis=1))
if self.rnnType in ['lstm']:
cell_output, encoder_state = self.cell(next_input, encoder_state)
elif self.rnnType in ['cudnn_lstm']:
cell_output, (h_state, c_state) = self.cell(tf.transpose(tf.expand_dims(next_input, axis=1), [1, 0, 2]),
initial_state=(h_state, c_state))
cell_output = tf.transpose(cell_output, [1, 0, 2])
cell_output = cell_output[:, -1, :]
if self.is_probabilistic_pred:
mu = y_pred_nn_
with tf.variable_scope('sigma_layer', reuse=tf.AUTO_REUSE):
sigma = tf.layers.dense(inputs=nn_input_concat, units=1, activation=tf.nn.softplus,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
sigma = tf.squeeze(sigma, axis=2)
dist = tfd.Normal(loc=mu, scale=sigma)
log_likelihood_ = dist.log_prob(outputDecN[:, i])
log_likelihood.append(log_likelihood_)
sigma_pred_nn.append(sigma)
y_pred_nn = tf.concat(y_pred_nn, 1)
y_pred_nn = y_pred_nn# * self.maskPh
#outputDecN *= self.maskPh
if self.is_probabilistic_pred:
sigma_pred_nn = tf.concat(tf.squeeze(sigma_pred_nn, axis=2), 1)
log_likelihood = tf.concat(log_likelihood, 1)
#log_likelihood *= self.maskPh
loss = -1.0 * tf.reduce_sum(log_likelihood)
self.sigma = sigma_pred_nn
else:
loss = tf.reduce_sum(tf.square(y_pred_nn - outputDecN))
if self.deep_ar_normalize:
#Rescale y
y_pred_nn = y_pred_nn*avg_output
self.loss = loss
self.y_pred_nn = y_pred_nn
return loss, y_pred_nn
def getHybridModel(self):
tf.set_random_seed(self.seed)
if self.deep_ar_normalize:
#Normalise y
avg_output = tf.expand_dims((1 + tf.reduce_mean(self.outputDec, axis=1)), axis=1)
outputDecN = self.outputDec/avg_output
else:
outputDecN = self.outputDec
cell_outputs, state = self.encodeInput()
cell_output = cell_outputs[:, -1, :]
lstm_out_dense = tf.layers.dense(inputs=cell_output,
units=self.lstm_dense_layer_size,
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
lstm_out_dense = tf.tile(tf.expand_dims(lstm_out_dense, dim=1), [1, self.decoder_length, 1])
if self.decoderType in ['rnn']:
inputDec, _, _ = self.decoder()
inputDec = inputDec[:, self.encoder_length:, :]
else:
inputDec = self.inputDec
nn_input = tf.concat([inputDec, lstm_out_dense], axis=2)
nn_input, y_pred_nn = self.nn_pass(nn_input)
y_pred_nn = tf.squeeze(y_pred_nn, [2])
#outputDecN *= self.maskPh
y_pred_nn = y_pred_nn# * self.maskPh
if self.is_probabilistic_pred:
mu = y_pred_nn
sigma = tf.layers.dense(inputs=nn_input, units=1, activation=tf.nn.softplus,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
sigma = tf.squeeze(sigma, [2])
dist = tfd.Normal(loc=mu, scale=sigma)
log_likelihood = dist.log_prob(outputDecN)
#log_likelihood *= self.maskPh
loss = -1.0 * tf.reduce_sum(log_likelihood)
self.sigma = sigma
else:
loss = tf.reduce_sum(tf.square(y_pred_nn - outputDecN))
if self.deep_ar_normalize:
y_pred_nn = y_pred_nn*avg_output
self.loss = loss
self.y_pred_nn = y_pred_nn
return loss, y_pred_nn
def getSNAILModel(self):
tf.set_random_seed(self.seed)
if self.deep_ar_normalize:
#Normalise y
avg_output = tf.expand_dims((1 + tf.reduce_mean(self.outputDec, axis=1)), axis=1)
outputDecN = self.outputDec/avg_output
else:
outputDecN = self.outputDec
def denseBlock(inputs, dilation_rate, num_filters, scope):
xf = temporal_convolution_layer(inputs, num_filters, 2, causal=True, dilation_rate=dilation_rate, scope=scope+'/kernel_1')
xg = temporal_convolution_layer(inputs, num_filters, 2, causal=True, dilation_rate=dilation_rate, scope=scope+'/kernel_2')
activations = tf.multiply(tf.tanh(xf), tf.nn.sigmoid(xg))
return tf.concat([activations, inputs], axis=2)
def TCBlock(inputs, num_filters):
seq_len = inputs.get_shape().as_list()[1]
for i in range(int(np.floor(np.log2(seq_len)))):
inputs = denseBlock(inputs, [np.power(2, i)], num_filters, 'conv_'+str(i))
return inputs
def attentionBlock(inputs, key_size, value_size):
keys = tf.layers.dense(inputs, key_size)
query = tf.layers.dense(inputs, key_size)
values = tf.layers.dense(inputs, value_size)
logits = tf.einsum('bij,bkj->bik', query, keys)
#logits = tf.Print(logits, [tf.shape(logits)])
mask = tf.constant(np.tril(np.ones([inputs.shape.as_list()[1], inputs.shape.as_list()[1]])), dtype=tf.float32)
logits = tf.multiply(logits, mask)
probs = tf.nn.softmax(logits)
read = tf.einsum('bij,bjk->bik', probs, values)
return tf.concat([inputs, read], axis=2)
inputs = denseBlock(self.inputEnc, [1], 4, 'conv_1')
inputs = attentionBlock(inputs, 4, 8)
inputs = denseBlock(inputs, [2], 4, 'conv_2')
inputs = attentionBlock(inputs, 4, 8)
#inputs = TCBlock(self.inputEnc, 16)
#inputs = attentionBlock(inputs, 16, 32)
context_vec = inputs[:,-1,:]
context_vec = tf.tile(tf.expand_dims(context_vec, dim=1), [1, self.decoder_length, 1])
nn_input = tf.concat([self.inputDec, context_vec], axis=2)
nn_input, y_pred_nn = self.nn_pass(nn_input)
y_pred_nn = tf.squeeze(y_pred_nn,[2])
y_pred_nn = y_pred_nn# * self.maskPh
#outputDecN *= self.maskPh
if self.is_probabilistic_pred:
mu = y_pred_nn
sigma = tf.layers.dense(inputs=nn_input, units=1, activation=tf.nn.softplus,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
sigma = tf.squeeze(sigma, [2])
dist = tfd.Normal(loc=mu, scale=sigma)
log_likelihood = dist.log_prob(outputDecN)
#log_likelihood *= self.maskPh
loss = -1.0 * tf.reduce_sum(log_likelihood)
self.sigma = sigma
else:
loss = tf.reduce_sum(tf.square(y_pred_nn - outputDecN))
if self.deep_ar_normalize:
y_pred_nn = y_pred_nn*avg_output
return loss, y_pred_nn
def getNeuralARUModel(self):
tf.set_random_seed(self.seed)
if self.deep_ar_normalize:
#Normalise y
avg_output = tf.expand_dims((1 + tf.reduce_mean(self.outputDec, axis=1)), axis=1)
outputDecN = self.outputDec/avg_output
else:
outputDecN = self.outputDec
cell_outputs, state = self.encodeInput()
cell_output = cell_outputs[:, -1, :]
lstm_out_dense = tf.layers.dense(inputs=cell_output,
units=self.lstm_dense_layer_size,
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
lstm_out_dense = tf.tile(tf.expand_dims(lstm_out_dense, dim=1), [1, self.decoder_length, 1])
def ARUPass(nn_input):
with tf.variable_scope('nn_pass_maruX', reuse=tf.AUTO_REUSE):
nn_input = tf.layers.dense(nn_input, self.hidden1, activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
nn_input = tf.layers.dense(nn_input, self.hidden2, activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
W = tf.layers.dense(nn_input, self.aruDims, activation=None,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
b = tf.layers.dense(nn_input, 1, activation=None,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
return W, b
W, b = ARUPass(self.inputPh[:, self.encoder_length:, :])
#W = tf.Print(W, [tf.reduce_sum(tf.cast(tf.is_nan(self.inputPh), tf.float32)), tf.shape(self.inputPh)])
output_h = tf.expand_dims(tf.reduce_sum(self.inputPh[:, self.encoder_length:, :] * W, axis=2), axis=2) + b
if self.decoderType in ['rnn']:
inputDec, _, _ = self.decoder()
inputDec = inputDec[:, self.encoder_length:, :]
else:
inputDec = self.inputDec
nn_input = tf.concat([inputDec, lstm_out_dense, output_h], axis=2)
nn_input, y_pred_nn = self.nn_pass(nn_input)
y_pred_nn = tf.squeeze(y_pred_nn, [2])
#outputDecN *= self.maskPh
y_pred_nn = y_pred_nn# * self.maskPh
if self.is_probabilistic_pred:
mu = y_pred_nn
sigma = tf.layers.dense(inputs=nn_input, units=1, activation=tf.nn.softplus,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
sigma = tf.squeeze(sigma, [2])
dist = tfd.Normal(loc=mu, scale=sigma)
log_likelihood = dist.log_prob(outputDecN)
#log_likelihood *= self.maskPh
loss = -1.0 * tf.reduce_sum(log_likelihood)
self.sigma = sigma
else:
loss = tf.reduce_sum(tf.square(y_pred_nn - outputDecN))
if self.deep_ar_normalize:
y_pred_nn = y_pred_nn*avg_output
self.loss = loss
self.y_pred_nn = y_pred_nn
return loss, y_pred_nn
def getAdaptModel(self):
tf.set_random_seed(self.seed)
if self.deep_ar_normalize:
#Normalise y
avg_output = tf.expand_dims((1 + tf.reduce_mean(self.outputDec, axis=1)), axis=1)
outputDecN = self.outputDec/avg_output
else:
outputDecN = self.outputDec
if self.isSRUFeat:
self.sru_states = self.multiScaleAverage(self.inputEnc[:, :, 0])
sru_state = tf.tile(tf.expand_dims(self.sru_states[:, -1, :], dim=1), [1, self.decoder_length, 1])
cell_outputs, state = self.encodeInput()
cell_output = cell_outputs[:, -1, :]
lstm_out_dense = tf.layers.dense(inputs=cell_output,
units=self.lstm_dense_layer_size,
activation=tf.nn.relu,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
lstm_out_dense = tf.tile(tf.expand_dims(lstm_out_dense, dim=1), [1, self.decoder_length, 1])
adapt_regression = aru.ARU(self.aruDims,
self.numTs,
num_y=self.numY, num_projs=self.num_projs,
full_linear=self.fullLinear,
regularizer=self.aruRegularizer,
proj_vecs=None,
aru_alpha=self.aru_alpha)
adapt_input = lstm_out_dense#[:, self.encoder_length:self.encoder_length+self.step_length, :]
adapt_labels = tf.expand_dims(self.outputDec, 2)
nn_input = tf.concat([self.inputDec, lstm_out_dense], axis=2)
if self.isSRUFeat:
nn_input = tf.concat([nn_input, sru_state], axis=2)
nn_input, y_pred_global = self.nn_pass(nn_input)
output_h, _ = adapt_regression.predict(nn_input, self.tsIndicesPh, self.maskPh)
#output_h = tf.Print(output_h, [tf.reduce_sum(tf.cast(tf.is_nan(output_h), tf.int32))])
if self.aru_deepar_normalize:
avg_aru_output = tf.expand_dims((1 + tf.reduce_mean(output_h, axis=1)), axis=1)
output_h = output_h / avg_aru_output
with tf.control_dependencies([output_h]):
adapted_states = adapt_regression.adapt(nn_input, adapt_labels, self.tsIndicesPh, self.maskPh)
#output_h = tf.Print(output_h, [tf.reduce_sum(tf.cast(tf.is_nan(self.inputPhEmbd), tf.int32))])
count = tf.gather(adapt_regression.count, self.tsIndicesPh)
gate = tf.expand_dims(tf.expand_dims(tf.maximum(tf.sigmoid(count - 10),0.0), axis=1), axis=2)
y_pred_nn = (1-gate)*y_pred_global + gate*output_h
y_pred_nn = tf.squeeze(y_pred_nn, [2])
y_pred_nn = y_pred_nn# * self.maskPh
#outputDecN *= self.maskPh
if self.is_probabilistic_pred:
mu = y_pred_nn
sigma = tf.layers.dense(inputs=nn_input, units=1, activation=tf.nn.softplus,
kernel_initializer=tf.glorot_uniform_initializer(seed=self.seed))
sigma = tf.squeeze(sigma, [2])
dist = tfd.Normal(loc=mu, scale=sigma)
log_likelihood = dist.log_prob(outputDecN)
#log_likelihood *= self.maskPh
loss = -1.0 * tf.reduce_sum(log_likelihood)
self.sigma = sigma
else:
loss = tf.reduce_sum(tf.square(y_pred_nn - outputDecN))
if self.deep_ar_normalize:
#Rescale y
y_pred_nn = y_pred_nn*avg_output
self.reset_op = adapt_regression.reset_states()
self.loss = loss
self.y_pred_nn = y_pred_nn
return loss, y_pred_nn, adapted_states
def getAdaptModel_old(self,adapt_tuple_placeholders):