-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathviddesc_model.py
2621 lines (2361 loc) · 174 KB
/
viddesc_model.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 logging
import os
import numpy as np
from keras import backend as K
from keras.layers import *
from keras.models import model_from_json, Model
from keras.regularizers import l2
from keras_wrapper.cnn_model import Model_Wrapper
from keras_wrapper.extra.regularize import Regularize
class VideoDesc_Model(Model_Wrapper):
"""
Translation model class. Instance of the Model_Wrapper class (see staged_keras_wrapper).
"""
def resumeTrainNet(self, ds, params, out_name=None):
pass
def __init__(self, params, type='VideoDesc_Model', verbose=1, structure_path=None, weights_path=None,
model_name=None, vocabularies=None, store_path=None, set_optimizer=True, clear_dirs=True):
"""
VideoDesc_Model object constructor.
:param params: all hyperparameters of the model.
:param type: network name type (corresponds to any method defined in the section 'MODELS' of this class). Only valid if 'structure_path' == None.
:param verbose: set to 0 if you don't want the model to output informative messages
:param structure_path: path to a Keras' model json file. If we speficy this parameter then 'type' will be only an informative parameter.
:param weights_path: path to the pre-trained weights file (if None, then it will be randomly initialized)
:param model_name: optional name given to the network (if None, then it will be assigned to current time as its name)
:param vocabularies: vocabularies used for GLOVE word embedding
:param store_path: path to the folder where the temporal model packups will be stored
References:
[PReLU]
Kaiming He et al. Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification
[BatchNormalization]
Sergey Ioffe and Christian Szegedy. Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift
"""
super(self.__class__, self).__init__(type=type, model_name=model_name,
silence=verbose == 0, models_path=store_path, inheritance=True)
self.__toprint = ['_model_type', 'name', 'model_path', 'verbose']
self.verbose = verbose
self._model_type = type
self.params = params
self.vocabularies = vocabularies
self.ids_inputs = params['INPUTS_IDS_MODEL']
self.ids_outputs = params['OUTPUTS_IDS_MODEL']
# Sets the model name and prepares the folders for storing the models
self.setName(model_name, models_path=store_path, clear_dirs=clear_dirs)
# Prepare target word embedding
if params['TRG_PRETRAINED_VECTORS'] is not None:
if self.verbose > 0:
logging.info("<<< Loading pretrained word vectors from: " + params['TRG_PRETRAINED_VECTORS'] + " >>>")
self.trg_word_vectors = np.load(os.path.join(params['TRG_PRETRAINED_VECTORS'])).item()
self.trg_embedding_weights = np.random.rand(params['OUTPUT_VOCABULARY_SIZE'],
params['TARGET_TEXT_EMBEDDING_SIZE'])
for word, index in self.vocabularies[self.ids_outputs[0]]['words2idx'].iteritems():
if self.trg_word_vectors.get(word) is not None:
self.trg_embedding_weights[index, :] = self.trg_word_vectors[word]
self.trg_embedding_weights = [self.trg_embedding_weights]
self.trg_embedding_weights_trainable = params['TRG_PRETRAINED_VECTORS_TRAINABLE']
del self.trg_word_vectors
else:
self.trg_embedding_weights = None
self.trg_embedding_weights_trainable = True
# Prepare model
if structure_path:
# Load a .json model
if self.verbose > 0:
logging.info("<<< Loading model structure from file " + structure_path + " >>>")
self.model = model_from_json(open(structure_path).read())
else:
# Build model from scratch
if hasattr(self, type):
if self.verbose > 0:
logging.info("<<< Building '" + type + "' Video Captioning Model >>>")
eval('self.' + type + '(params)')
else:
raise Exception('Video_Captioning_Model type "' + type + '" is not implemented.')
# Load weights from file
if weights_path:
if self.verbose > 0:
logging.info("<<< Loading weights from file " + weights_path + " >>>")
self.model.load_weights(weights_path)
# Print information of self
if verbose > 0:
print str(self)
self.model.summary()
if set_optimizer:
self.setOptimizer()
def setOptimizer(self, **kwargs):
"""
Sets a new optimizer for the Translation_Model.
:param **kwargs:
"""
super(self.__class__, self).setOptimizer(lr=self.params['LR'],
clipnorm=self.params['CLIP_C'],
loss=self.params['LOSS'],
optimizer=self.params['OPTIMIZER'],
sample_weight_mode='temporal' if self.params.get('SAMPLE_WEIGHTS',
False) else None)
def __str__(self):
"""
Plots basic model information.
"""
obj_str = '-----------------------------------------------------------------------------------\n'
class_name = self.__class__.__name__
obj_str += '\t\t' + class_name + ' instance\n'
obj_str += '-----------------------------------------------------------------------------------\n'
# Print pickled attributes
for att in self.__toprint:
obj_str += att + ': ' + str(self.__dict__[att])
obj_str += '\n'
obj_str += '\n'
obj_str += 'MODEL params:\n'
obj_str += str(self.params)
obj_str += '\n'
obj_str += '-----------------------------------------------------------------------------------'
return obj_str
# ------------------------------------------------------- #
# PREDEFINED MODELS
# ------------------------------------------------------- #
def DeepSeek(self, params):
"""
:param params:
:return:
"""
# Video model
video = Input(name=self.ids_inputs[0], shape=tuple([None, params['IMG_FEAT_SIZE']]))
input_video = video
##################################################################
# ENCODER
##################################################################
encoder = Bidirectional(eval(params['RNN_TYPE'])(params['ENCODER_HIDDEN_SIZE'],
W_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
dropout_W=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
return_sequences=True),
name='bidirectional_encoder_' + params['RNN_TYPE'],
merge_mode='concat')(input_video)
input_video = Regularize(encoder, params, name='after_blstm1')
# Affine layer (not their best model)
"""
encoder_back = TimeDistributed(Dense(params['AFFINE_LAYERS_DIM'])
, name='affine_back')(encoder_back)
encoder = TimeDistributed(Dense(params['AFFINE_LAYERS_DIM'])
, name='affine_forw')(encoder)
input_video = Lambda(function=lambda x: K.sum(x, axis=1),
output_shape=lambda shape: shape[0],
mask_function=lambda x, m: m[0])([encoder_back, encoder])
input_video = TimeDistributed(Activation('relu'))(input_video)
"""
# They alternatively use a double BLSTM encoder
input_video = Bidirectional(eval(params['RNN_TYPE'])(params['ENCODER_HIDDEN_SIZE'],
W_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
dropout_W=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
return_sequences=True),
name='bidirectional_encoder2_' + params['RNN_TYPE'],
merge_mode='concat')(input_video)
input_video = Regularize(input_video, params, name='after_blstm2')
# Previously generated words as inputs for training
next_words = Input(name=self.ids_inputs[1], batch_shape=tuple([None, None]), dtype='int32')
emb = Embedding(params['OUTPUT_VOCABULARY_SIZE'],
params['TARGET_TEXT_EMBEDDING_SIZE'],
name='target_word_embedding',
W_regularizer=l2(params['WEIGHT_DECAY']),
trainable=self.trg_embedding_weights_trainable,
weights=self.trg_embedding_weights,
mask_zero=True)(next_words)
emb = Regularize(emb, params, name='target_word_embedding')
# LSTM initialization perceptrons with ctx mean
# 3.2. Decoder's RNN initialization perceptrons with ctx mean
ctx_mean = Lambda(lambda x: K.mean(x, axis=1),
output_shape=lambda s: (s[0], s[2]), name='lambda_mean')(input_video)
if len(params['INIT_LAYERS']) > 0:
for n_layer_init in range(len(params['INIT_LAYERS']) - 1):
ctx_mean = Dense(params['DECODER_HIDDEN_SIZE'], name='init_layer_%d' % n_layer_init,
W_regularizer=l2(params['WEIGHT_DECAY']),
activation=params['INIT_LAYERS'][n_layer_init]
)(ctx_mean)
ctx_mean = Regularize(ctx_mean, params, name='ctx' + str(n_layer_init))
initial_state = Dense(params['DECODER_HIDDEN_SIZE'], name='initial_state',
W_regularizer=l2(params['WEIGHT_DECAY']),
activation=params['INIT_LAYERS'][-1]
)(ctx_mean)
initial_state = Regularize(initial_state, params, name='initial_state')
input_attentional_decoder = [emb, input_video, initial_state]
if params['RNN_TYPE'] == 'LSTM':
initial_memory = Dense(params['DECODER_HIDDEN_SIZE'], name='initial_memory',
W_regularizer=l2(params['WEIGHT_DECAY']),
activation=params['INIT_LAYERS'][-1])(ctx_mean)
initial_memory = Regularize(initial_memory, params, name='initial_memory')
input_attentional_decoder.append(initial_memory)
else:
input_attentional_decoder = [emb, input_video]
##################################################################
# DECODER
##################################################################
# 3.3. LSTM decoder
sharedRNN = eval(params['RNN_TYPE'] + 'Cond')(params['DECODER_HIDDEN_SIZE'],
W_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
dropout_W=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
return_sequences=True,
name='decoder_' + params['RNN_TYPE'] + 'Cond')
proj_h = sharedRNN(input_attentional_decoder)
# 3.7. Output layer: Softmax
shared_FC_soft = TimeDistributed(Dense(params['OUTPUT_VOCABULARY_SIZE'],
activation=params['CLASSIFIER_ACTIVATION'],
W_regularizer=l2(params['WEIGHT_DECAY']),
name=params['CLASSIFIER_ACTIVATION']
),
name=self.ids_outputs[0])
softout = shared_FC_soft(proj_h)
self.model = Model(input=[video, next_words], output=softout)
def ArcticVideoCaptionWithInit(self, params):
"""
Video captioning with:
* Attention mechansim on video frames
* Conditional LSTM for processing the video
* Feed forward layers:
+ Context projected to output
+ Last word projected to output
:param params:
:return:
"""
# Video model
# video = Input(name=self.ids_inputs[0], shape=tuple([params['NUM_FRAMES'], params['IMG_FEAT_SIZE']]))
video = Input(name=self.ids_inputs[0], shape=tuple([None, params['IMG_FEAT_SIZE']]))
input_video = video
##################################################################
# ENCODER
##################################################################
for activation, dimension in params['IMG_EMBEDDING_LAYERS']:
input_video = TimeDistributed(Dense(dimension, name='%s_1' % activation, activation=activation,
W_regularizer=l2(params['WEIGHT_DECAY'])))(input_video)
input_video = Regularize(input_video, params, name='%s_1' % activation)
if params['ENCODER_HIDDEN_SIZE'] > 0:
if params['BIDIRECTIONAL_ENCODER']:
encoder = Bidirectional(eval(params['RNN_TYPE'])(params['ENCODER_HIDDEN_SIZE'],
W_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
dropout_W=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
return_sequences=True),
name='bidirectional_encoder_' + params['RNN_TYPE'],
merge_mode='concat')(input_video)
else:
encoder = eval(params['RNN_TYPE'])(params['ENCODER_HIDDEN_SIZE'],
W_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
dropout_W=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
return_sequences=True,
name='encoder_' + params['RNN_TYPE'])(input_video)
input_video = merge([input_video, encoder], mode='concat', concat_axis=2)
input_video = Regularize(input_video, params, name='input_video')
# 2.3. Potentially deep encoder
for n_layer in range(1, params['N_LAYERS_ENCODER']):
if params['BIDIRECTIONAL_DEEP_ENCODER']:
current_input_video = Bidirectional(eval(params['RNN_TYPE'])(params['ENCODER_HIDDEN_SIZE'],
W_regularizer=l2(
params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(
params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(
params['RECURRENT_WEIGHT_DECAY']),
dropout_W=params[
'RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params[
'RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
return_sequences=True,
),
merge_mode='concat',
name='bidirectional_encoder_' + str(n_layer))(input_video)
else:
current_input_video = eval(params['RNN_TYPE'])(params['ENCODER_HIDDEN_SIZE'],
W_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
dropout_W=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
return_sequences=True,
name='encoder_' + str(n_layer))(input_video)
current_input_video = Regularize(current_input_video, params, name='input_video_' + str(n_layer))
input_video = merge([input_video, current_input_video], mode='sum')
# Previously generated words as inputs for training
next_words = Input(name=self.ids_inputs[1], batch_shape=tuple([None, None]), dtype='int32')
emb = Embedding(params['OUTPUT_VOCABULARY_SIZE'],
params['TARGET_TEXT_EMBEDDING_SIZE'],
name='target_word_embedding',
W_regularizer=l2(params['WEIGHT_DECAY']),
trainable=self.trg_embedding_weights_trainable,
weights=self.trg_embedding_weights,
mask_zero=True)(next_words)
emb = Regularize(emb, params, name='target_word_embedding')
# LSTM initialization perceptrons with ctx mean
# 3.2. Decoder's RNN initialization perceptrons with ctx mean
ctx_mean = Lambda(lambda x: K.mean(x, axis=1),
output_shape=lambda s: (s[0], s[2]), name='lambda_mean')(input_video)
if len(params['INIT_LAYERS']) > 0:
for n_layer_init in range(len(params['INIT_LAYERS']) - 1):
ctx_mean = Dense(params['DECODER_HIDDEN_SIZE'], name='init_layer_%d' % n_layer_init,
W_regularizer=l2(params['WEIGHT_DECAY']),
activation=params['INIT_LAYERS'][n_layer_init]
)(ctx_mean)
ctx_mean = Regularize(ctx_mean, params, name='ctx' + str(n_layer_init))
initial_state = Dense(params['DECODER_HIDDEN_SIZE'], name='initial_state',
W_regularizer=l2(params['WEIGHT_DECAY']),
activation=params['INIT_LAYERS'][-1]
)(ctx_mean)
initial_state = Regularize(initial_state, params, name='initial_state')
input_attentional_decoder = [emb, input_video, initial_state]
if params['RNN_TYPE'] == 'LSTM':
initial_memory = Dense(params['DECODER_HIDDEN_SIZE'], name='initial_memory',
W_regularizer=l2(params['WEIGHT_DECAY']),
activation=params['INIT_LAYERS'][-1])(ctx_mean)
initial_memory = Regularize(initial_memory, params, name='initial_memory')
input_attentional_decoder.append(initial_memory)
else:
input_attentional_decoder = [emb, input_video]
##################################################################
# DECODER
##################################################################
# 3.3. Attentional decoder
sharedAttRNNCond = eval('Att' + params['RNN_TYPE'] + 'Cond')(params['DECODER_HIDDEN_SIZE'],
W_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
V_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
wa_regularizer=l2(params['WEIGHT_DECAY']),
Wa_regularizer=l2(params['WEIGHT_DECAY']),
Ua_regularizer=l2(params['WEIGHT_DECAY']),
ba_regularizer=l2(params['WEIGHT_DECAY']),
dropout_W=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_V=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_wa=params['DROPOUT_P'] if params[
'USE_DROPOUT'] else None,
dropout_Wa=params['DROPOUT_P'] if params[
'USE_DROPOUT'] else None,
dropout_Ua=params['DROPOUT_P'] if params[
'USE_DROPOUT'] else None,
return_sequences=True,
return_extra_variables=True,
return_states=True,
name='decoder_Att' + params['RNN_TYPE'] + 'Cond')
rnn_output = sharedAttRNNCond(input_attentional_decoder)
proj_h = rnn_output[0]
x_att = rnn_output[1]
alphas = rnn_output[2]
h_state = rnn_output[3]
if params['RNN_TYPE'] == 'LSTM':
h_memory = rnn_output[4]
[proj_h, shared_reg_proj_h] = Regularize(proj_h, params, shared_layers=True, name='proj_h0')
shared_FC_mlp = TimeDistributed(Dense(params['SKIP_VECTORS_HIDDEN_SIZE'],
W_regularizer=l2(params['WEIGHT_DECAY']),
activation='linear',
), name='logit_lstm')
out_layer_mlp = shared_FC_mlp(proj_h)
shared_FC_ctx = TimeDistributed(Dense(params['SKIP_VECTORS_HIDDEN_SIZE'],
W_regularizer=l2(params['WEIGHT_DECAY']),
activation='linear',
), name='logit_ctx')
out_layer_ctx = shared_FC_ctx(x_att)
shared_Lambda_Permute = PermuteGeneral((1, 0, 2))
out_layer_ctx = shared_Lambda_Permute(out_layer_ctx)
shared_FC_emb = TimeDistributed(Dense(params['SKIP_VECTORS_HIDDEN_SIZE'],
W_regularizer=l2(params['WEIGHT_DECAY']),
activation='linear'),
name='logit_emb')
out_layer_emb = shared_FC_emb(emb)
[out_layer_mlp, shared_reg_out_layer_mlp] = Regularize(out_layer_mlp, params,
shared_layers=True, name='out_layer_mlp')
[out_layer_ctx, shared_reg_out_layer_ctx] = Regularize(out_layer_ctx, params,
shared_layers=True, name='out_layer_ctx')
[out_layer_emb, shared_reg_out_layer_emb] = Regularize(out_layer_emb, params,
shared_layers=True, name='out_layer_emb')
additional_output = merge([out_layer_mlp, out_layer_ctx, out_layer_emb],
mode=params['ADDITIONAL_OUTPUT_MERGE_MODE'], name='additional_input')
shared_activation_tanh = Activation('tanh')
out_layer = shared_activation_tanh(additional_output)
shared_deep_list = []
shared_reg_deep_list = []
# 3.6 Optional deep ouput layer
for i, (activation, dimension) in enumerate(params['DEEP_OUTPUT_LAYERS']):
if activation.lower() == 'maxout':
shared_deep_list.append(TimeDistributed(MaxoutDense(dimension,
W_regularizer=l2(params['WEIGHT_DECAY'])),
name='maxout_%d' % i))
else:
shared_deep_list.append(TimeDistributed(Dense(dimension, activation=activation,
W_regularizer=l2(params['WEIGHT_DECAY'])),
name=activation + '_%d' % i))
out_layer = shared_deep_list[-1](out_layer)
[out_layer, shared_reg_out_layer] = Regularize(out_layer,
params, shared_layers=True,
name='out_layer' + str(activation))
shared_reg_deep_list.append(shared_reg_out_layer)
# 3.7. Output layer: Softmax
shared_FC_soft = TimeDistributed(Dense(params['OUTPUT_VOCABULARY_SIZE'],
activation=params['CLASSIFIER_ACTIVATION'],
W_regularizer=l2(params['WEIGHT_DECAY']),
name=params['CLASSIFIER_ACTIVATION']
),
name=self.ids_outputs[0])
softout = shared_FC_soft(out_layer)
self.model = Model(input=[video, next_words], output=softout)
##################################################################
# BEAM SEARCH OPTIMIZED MODEL #
##################################################################
# Now that we have the basic training model ready, let's prepare the model for applying decoding
# The beam-search model will include all the minimum required set of layers (decoder stage) which offer the
# possibility to generate the next state in the sequence given a pre-processed input (encoder stage)
if params['BEAM_SEARCH']:
# First, we need a model that outputs the preprocessed input + initial h state
# for applying the initial forward pass
model_init_input = [video, next_words]
model_init_output = [softout, input_video, h_state]
if params['RNN_TYPE'] == 'LSTM':
model_init_output.append(h_memory)
self.model_init = Model(input=model_init_input, output=model_init_output)
# Store inputs and outputs names for model_init
self.ids_inputs_init = self.ids_inputs
# first output must be the output probs.
self.ids_outputs_init = self.ids_outputs + ['preprocessed_input', 'next_state']
if params['RNN_TYPE'] == 'LSTM':
self.ids_outputs_init.append('next_memory')
# Second, we need to build an additional model with the capability to have the following inputs:
# - preprocessed_input
# - prev_word
# - prev_state
# and the following outputs:
# - softmax probabilities
# - next_state
if params['ENCODER_HIDDEN_SIZE'] > 0:
if params['BIDIRECTIONAL_ENCODER']:
preprocessed_size = params['ENCODER_HIDDEN_SIZE'] * 2 + params['IMG_FEAT_SIZE']
else:
preprocessed_size = params['ENCODER_HIDDEN_SIZE'] + params['IMG_FEAT_SIZE']
else:
preprocessed_size = params['IMG_FEAT_SIZE']
# Define inputs
preprocessed_annotations = Input(name='preprocessed_input',
shape=tuple([params['NUM_FRAMES'], preprocessed_size]))
prev_h_state = Input(name='prev_state', shape=tuple([params['DECODER_HIDDEN_SIZE']]))
input_attentional_decoder = [emb, preprocessed_annotations, prev_h_state]
if params['RNN_TYPE'] == 'LSTM':
prev_h_memory = Input(name='prev_memory', shape=tuple([params['DECODER_HIDDEN_SIZE']]))
input_attentional_decoder.append(prev_h_memory)
# Apply decoder
rnn_output = sharedAttRNNCond(input_attentional_decoder)
proj_h = rnn_output[0]
x_att = rnn_output[1]
alphas = rnn_output[2]
h_state = rnn_output[3]
if params['RNN_TYPE'] == 'LSTM':
h_memory = rnn_output[4]
for reg in shared_reg_proj_h:
proj_h = reg(proj_h)
out_layer_mlp = shared_FC_mlp(proj_h)
out_layer_ctx = shared_FC_ctx(x_att)
out_layer_ctx = shared_Lambda_Permute(out_layer_ctx)
out_layer_emb = shared_FC_emb(emb)
for (reg_out_layer_mlp, reg_out_layer_ctx, reg_out_layer_emb) in zip(shared_reg_out_layer_mlp,
shared_reg_out_layer_ctx,
shared_reg_out_layer_emb):
out_layer_mlp = reg_out_layer_mlp(out_layer_mlp)
out_layer_ctx = reg_out_layer_ctx(out_layer_ctx)
out_layer_emb = reg_out_layer_emb(out_layer_emb)
additional_output = merge([out_layer_mlp, out_layer_ctx, out_layer_emb],
mode=params['ADDITIONAL_OUTPUT_MERGE_MODE'], name='additional_input_model_next')
out_layer = shared_activation_tanh(additional_output)
for (deep_out_layer, reg_list) in zip(shared_deep_list, shared_reg_deep_list):
out_layer = deep_out_layer(out_layer)
for reg in reg_list:
out_layer = reg(out_layer)
# Softmax
softout = shared_FC_soft(out_layer)
model_next_inputs = [next_words, preprocessed_annotations, prev_h_state]
model_next_outputs = [softout, preprocessed_annotations, h_state]
if params['RNN_TYPE'] == 'LSTM':
model_next_inputs.append(prev_h_memory)
model_next_outputs.append(h_memory)
self.model_next = Model(input=model_next_inputs,
output=model_next_outputs)
# Store inputs and outputs names for model_next
# first input must be previous word
self.ids_inputs_next = [self.ids_inputs[1]] + ['preprocessed_input', 'prev_state']
# first output must be the output probs.
self.ids_outputs_next = self.ids_outputs + ['preprocessed_input', 'next_state']
# Input -> Output matchings from model_init to model_next and from model_next to model_next
self.matchings_init_to_next = {'preprocessed_input': 'preprocessed_input',
'next_state': 'prev_state'}
self.matchings_next_to_next = {'preprocessed_input': 'preprocessed_input',
'next_state': 'prev_state'}
if params['RNN_TYPE'] == 'LSTM':
self.ids_inputs_next.append('prev_memory')
self.ids_outputs_next.append('next_memory')
self.matchings_init_to_next['next_memory'] = 'prev_memory'
self.matchings_next_to_next['next_memory'] = 'prev_memory'
def ArcticVideoCaptionNoLSTMEncWithInit(self, params):
"""
Video captioning with:
* Attention mechansim on video frames
* Conditional LSTM for processing the video
* Feed forward layers:
+ Context projected to output
+ Last word projected to output
:param params:
:return:
"""
# Video model
# video = Input(name=self.ids_inputs[0], shape=tuple([params['NUM_FRAMES'], params['IMG_FEAT_SIZE']]))
video = Input(name=self.ids_inputs[0], shape=tuple([None, params['IMG_FEAT_SIZE']]))
input_video = video
##################################################################
# ENCODER
##################################################################
for activation, dimension in params['IMG_EMBEDDING_LAYERS']:
input_video = TimeDistributed(Dense(dimension, name='%s_1' % activation, activation=activation,
W_regularizer=l2(params['WEIGHT_DECAY'])))(input_video)
input_video = Regularize(input_video, params, name='%s_1' % activation)
input_video = Regularize(input_video, params, name='input_video')
# Previously generated words as inputs for training
next_words = Input(name=self.ids_inputs[1], batch_shape=tuple([None, None]), dtype='int32')
emb = Embedding(params['OUTPUT_VOCABULARY_SIZE'],
params['TARGET_TEXT_EMBEDDING_SIZE'],
name='target_word_embedding',
W_regularizer=l2(params['WEIGHT_DECAY']),
trainable=self.trg_embedding_weights_trainable,
weights=self.trg_embedding_weights,
mask_zero=True)(next_words)
emb = Regularize(emb, params, name='target_word_embedding')
# LSTM initialization perceptrons with ctx mean
# 3.2. Decoder's RNN initialization perceptrons with ctx mean
ctx_mean = Lambda(lambda x: K.mean(x, axis=1),
output_shape=lambda s: (s[0], s[2]), name='lambda_mean')(input_video)
if len(params['INIT_LAYERS']) > 0:
for n_layer_init in range(len(params['INIT_LAYERS']) - 1):
ctx_mean = Dense(params['DECODER_HIDDEN_SIZE'], name='init_layer_%d' % n_layer_init,
W_regularizer=l2(params['WEIGHT_DECAY']),
activation=params['INIT_LAYERS'][n_layer_init]
)(ctx_mean)
ctx_mean = Regularize(ctx_mean, params, name='ctx' + str(n_layer_init))
initial_state = Dense(params['DECODER_HIDDEN_SIZE'], name='initial_state',
W_regularizer=l2(params['WEIGHT_DECAY']),
activation=params['INIT_LAYERS'][-1]
)(ctx_mean)
initial_state = Regularize(initial_state, params, name='initial_state')
input_attentional_decoder = [emb, input_video, initial_state]
if params['RNN_TYPE'] == 'LSTM':
initial_memory = Dense(params['DECODER_HIDDEN_SIZE'], name='initial_memory',
W_regularizer=l2(params['WEIGHT_DECAY']),
activation=params['INIT_LAYERS'][-1])(ctx_mean)
initial_memory = Regularize(initial_memory, params, name='initial_memory')
input_attentional_decoder.append(initial_memory)
else:
input_attentional_decoder = [emb, input_video]
##################################################################
# DECODER
##################################################################
# 3.3. Attentional decoder
sharedAttRNNCond = eval('Att' + params['RNN_TYPE'] + 'Cond')(params['DECODER_HIDDEN_SIZE'],
W_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
V_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
wa_regularizer=l2(params['WEIGHT_DECAY']),
Wa_regularizer=l2(params['WEIGHT_DECAY']),
Ua_regularizer=l2(params['WEIGHT_DECAY']),
ba_regularizer=l2(params['WEIGHT_DECAY']),
dropout_W=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_V=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_wa=params['DROPOUT_P'] if params[
'USE_DROPOUT'] else None,
dropout_Wa=params['DROPOUT_P'] if params[
'USE_DROPOUT'] else None,
dropout_Ua=params['DROPOUT_P'] if params[
'USE_DROPOUT'] else None,
return_sequences=True,
return_extra_variables=True,
return_states=True,
name='decoder_Att' + params['RNN_TYPE'] + 'Cond')
rnn_output = sharedAttRNNCond(input_attentional_decoder)
proj_h = rnn_output[0]
x_att = rnn_output[1]
alphas = rnn_output[2]
h_state = rnn_output[3]
if params['RNN_TYPE'] == 'LSTM':
h_memory = rnn_output[4]
[proj_h, shared_reg_proj_h] = Regularize(proj_h, params, shared_layers=True, name='proj_h0')
shared_FC_mlp = TimeDistributed(Dense(params['DECODER_HIDDEN_SIZE'],
W_regularizer=l2(params['WEIGHT_DECAY']),
activation='linear',
), name='logit_lstm')
out_layer_mlp = shared_FC_mlp(proj_h)
shared_FC_ctx = TimeDistributed(Dense(params['DECODER_HIDDEN_SIZE'],
W_regularizer=l2(params['WEIGHT_DECAY']),
activation='linear',
), name='logit_ctx')
out_layer_ctx = shared_FC_ctx(x_att)
shared_Lambda_Permute = PermuteGeneral((1, 0, 2))
out_layer_ctx = shared_Lambda_Permute(out_layer_ctx)
shared_FC_emb = TimeDistributed(Dense(params['DECODER_HIDDEN_SIZE'],
W_regularizer=l2(params['WEIGHT_DECAY']),
activation='linear'),
name='logit_emb')
out_layer_emb = shared_FC_emb(emb)
[out_layer_mlp, shared_reg_out_layer_mlp] = Regularize(out_layer_mlp, params,
shared_layers=True, name='out_layer_mlp')
[out_layer_ctx, shared_reg_out_layer_ctx] = Regularize(out_layer_ctx, params,
shared_layers=True, name='out_layer_ctx')
[out_layer_emb, shared_reg_out_layer_emb] = Regularize(out_layer_emb, params,
shared_layers=True, name='out_layer_emb')
additional_output = merge([out_layer_mlp, out_layer_ctx, out_layer_emb],
mode=params['ADDITIONAL_OUTPUT_MERGE_MODE'], name='additional_input')
shared_activation_tanh = Activation('tanh')
out_layer = shared_activation_tanh(additional_output)
shared_deep_list = []
shared_reg_deep_list = []
# 3.6 Optional deep ouput layer
for i, (activation, dimension) in enumerate(params['DEEP_OUTPUT_LAYERS']):
if activation.lower() == 'maxout':
shared_deep_list.append(TimeDistributed(MaxoutDense(dimension,
W_regularizer=l2(params['WEIGHT_DECAY'])),
name='maxout_%d' % i))
else:
shared_deep_list.append(TimeDistributed(Dense(dimension, activation=activation,
W_regularizer=l2(params['WEIGHT_DECAY'])),
name=activation + '_%d' % i))
out_layer = shared_deep_list[-1](out_layer)
[out_layer, shared_reg_out_layer] = Regularize(out_layer,
params, shared_layers=True,
name='out_layer' + str(activation))
shared_reg_deep_list.append(shared_reg_out_layer)
# 3.7. Output layer: Softmax
shared_FC_soft = TimeDistributed(Dense(params['OUTPUT_VOCABULARY_SIZE'],
activation=params['CLASSIFIER_ACTIVATION'],
W_regularizer=l2(params['WEIGHT_DECAY']),
name=params['CLASSIFIER_ACTIVATION']
),
name=self.ids_outputs[0])
softout = shared_FC_soft(out_layer)
self.model = Model(input=[video, next_words], output=softout)
##################################################################
# BEAM SEARCH OPTIMIZED MODEL #
##################################################################
# Now that we have the basic training model ready, let's prepare the model for applying decoding
# The beam-search model will include all the minimum required set of layers (decoder stage) which offer the
# possibility to generate the next state in the sequence given a pre-processed input (encoder stage)
if params['BEAM_SEARCH']:
# First, we need a model that outputs the preprocessed input + initial h state
# for applying the initial forward pass
model_init_input = [video, next_words]
model_init_output = [softout, input_video, h_state]
if params['RNN_TYPE'] == 'LSTM':
model_init_output.append(h_memory)
self.model_init = Model(input=model_init_input, output=model_init_output)
# Store inputs and outputs names for model_init
self.ids_inputs_init = self.ids_inputs
# first output must be the output probs.
self.ids_outputs_init = self.ids_outputs + ['preprocessed_input', 'next_state']
if params['RNN_TYPE'] == 'LSTM':
self.ids_outputs_init.append('next_memory')
# Second, we need to build an additional model with the capability to have the following inputs:
# - preprocessed_input
# - prev_word
# - prev_state
# and the following outputs:
# - softmax probabilities
# - next_state
preprocessed_size = params['IMG_FEAT_SIZE']
# Define inputs
preprocessed_annotations = Input(name='preprocessed_input',
shape=tuple([params['NUM_FRAMES'], preprocessed_size]))
prev_h_state = Input(name='prev_state', shape=tuple([params['DECODER_HIDDEN_SIZE']]))
input_attentional_decoder = [emb, preprocessed_annotations, prev_h_state]
if params['RNN_TYPE'] == 'LSTM':
prev_h_memory = Input(name='prev_memory', shape=tuple([params['DECODER_HIDDEN_SIZE']]))
input_attentional_decoder.append(prev_h_memory)
# Apply decoder
rnn_output = sharedAttRNNCond(input_attentional_decoder)
proj_h = rnn_output[0]
x_att = rnn_output[1]
alphas = rnn_output[2]
h_state = rnn_output[3]
if params['RNN_TYPE'] == 'LSTM':
h_memory = rnn_output[4]
for reg in shared_reg_proj_h:
proj_h = reg(proj_h)
out_layer_mlp = shared_FC_mlp(proj_h)
out_layer_ctx = shared_FC_ctx(x_att)
out_layer_ctx = shared_Lambda_Permute(out_layer_ctx)
out_layer_emb = shared_FC_emb(emb)
for (reg_out_layer_mlp, reg_out_layer_ctx, reg_out_layer_emb) in zip(shared_reg_out_layer_mlp,
shared_reg_out_layer_ctx,
shared_reg_out_layer_emb):
out_layer_mlp = reg_out_layer_mlp(out_layer_mlp)
out_layer_ctx = reg_out_layer_ctx(out_layer_ctx)
out_layer_emb = reg_out_layer_emb(out_layer_emb)
additional_output = merge([out_layer_mlp, out_layer_ctx, out_layer_emb],
mode=params['ADDITIONAL_OUTPUT_MERGE_MODE'], name='additional_input_model_next')
out_layer = shared_activation_tanh(additional_output)
for (deep_out_layer, reg_list) in zip(shared_deep_list, shared_reg_deep_list):
out_layer = deep_out_layer(out_layer)
for reg in reg_list:
out_layer = reg(out_layer)
# Softmax
softout = shared_FC_soft(out_layer)
model_next_inputs = [next_words, preprocessed_annotations, prev_h_state]
model_next_outputs = [softout, preprocessed_annotations, h_state]
if params['RNN_TYPE'] == 'LSTM':
model_next_inputs.append(prev_h_memory)
model_next_outputs.append(h_memory)
self.model_next = Model(input=model_next_inputs,
output=model_next_outputs)
# Store inputs and outputs names for model_next
# first input must be previous word
self.ids_inputs_next = [self.ids_inputs[1]] + ['preprocessed_input', 'prev_state']
# first output must be the output probs.
self.ids_outputs_next = self.ids_outputs + ['preprocessed_input', 'next_state']
# Input -> Output matchings from model_init to model_next and from model_next to model_next
self.matchings_init_to_next = {'preprocessed_input': 'preprocessed_input',
'next_state': 'prev_state'}
self.matchings_next_to_next = {'preprocessed_input': 'preprocessed_input',
'next_state': 'prev_state'}
if params['RNN_TYPE'] == 'LSTM':
self.ids_inputs_next.append('prev_memory')
self.ids_outputs_next.append('next_memory')
self.matchings_init_to_next['next_memory'] = 'prev_memory'
self.matchings_next_to_next['next_memory'] = 'prev_memory'
def TemporallyLinkedVideoDescriptionNoAtt(self, params):
"""
Video captioning with:
* Attention mechansim on video frames
* Conditional LSTM for processing the video
* Feed forward layers:
+ Context projected to output
+ Last word projected to output
* LSTM on output of previous sequence/video
:param params:
:return:
"""
# Prepare variables for temporally linked samples
self.ids_temporally_linked_inputs = [self.ids_inputs[2]]
self.matchings_sample_to_next_sample = {self.ids_outputs[0]: self.ids_inputs[2]}
# Video model
# video = Input(name=self.ids_inputs[0], shape=tuple([params['NUM_FRAMES'], params['IMG_FEAT_SIZE']]))
video = Input(name=self.ids_inputs[0], shape=tuple([None, params['IMG_FEAT_SIZE']]))
input_video = video
##################################################################
# ENCODER
##################################################################
for activation, dimension in params['IMG_EMBEDDING_LAYERS']:
input_video = TimeDistributed(Dense(dimension, name='%s_1' % activation, activation=activation,
W_regularizer=l2(params['WEIGHT_DECAY'])))(input_video)
input_video = Regularize(input_video, params, name='%s_1' % activation)
if params['ENCODER_HIDDEN_SIZE'] > 0:
if params['BIDIRECTIONAL_ENCODER']:
encoder = Bidirectional(eval(params['RNN_TYPE'])(params['ENCODER_HIDDEN_SIZE'],
W_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
dropout_W=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
return_sequences=True),
name='bidirectional_encoder_' + params['RNN_TYPE'],
merge_mode='concat')(input_video)
else:
encoder = eval(params['RNN_TYPE'])(params['ENCODER_HIDDEN_SIZE'],
W_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
dropout_W=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
return_sequences=True,
name='encoder_' + params['RNN_TYPE'])(input_video)
input_video = merge([input_video, encoder], mode='concat', concat_axis=2)
input_video = Regularize(input_video, params, name='input_video')
# 2.3. Potentially deep encoder
for n_layer in range(1, params['N_LAYERS_ENCODER']):
if params['BIDIRECTIONAL_DEEP_ENCODER']:
current_input_video = Bidirectional(eval(params['RNN_TYPE'])(params['ENCODER_HIDDEN_SIZE'],
W_regularizer=l2(
params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(
params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(
params['RECURRENT_WEIGHT_DECAY']),
dropout_W=params[
'RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params[
'RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
return_sequences=True,
),
merge_mode='concat',
name='bidirectional_encoder_' + str(n_layer))(input_video)
else:
current_input_video = eval(params['RNN_TYPE'])(params['ENCODER_HIDDEN_SIZE'],
W_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
dropout_W=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
return_sequences=True,
name='encoder_' + str(n_layer))(input_video)
current_input_video = Regularize(current_input_video, params, name='input_video_' + str(n_layer))
input_video = merge([input_video, current_input_video], mode='sum')
# Previously generated words as inputs for training
next_words = Input(name=self.ids_inputs[1], batch_shape=tuple([None, None]), dtype='int32')
shared_emb = Embedding(params['OUTPUT_VOCABULARY_SIZE'],
params['TARGET_TEXT_EMBEDDING_SIZE'],
name='target_word_embedding',
W_regularizer=l2(params['WEIGHT_DECAY']),
trainable=self.trg_embedding_weights_trainable,
weights=self.trg_embedding_weights,
mask_zero=True)
emb = shared_emb(next_words)
emb = Regularize(emb, params, name='target_word_embedding')
# Previously generated description from temporally-linked sample
prev_desc = Input(name=self.ids_inputs[2], batch_shape=tuple([None, None]), dtype='int32')
# previous description and previously generated words share the same embedding
prev_desc_emb = shared_emb(prev_desc)
# LSTM for encoding the previous description
if params['PREV_SENT_ENCODER_HIDDEN_SIZE'] > 0:
if params['BIDIRECTIONAL_PREV_SENT_ENCODER']:
prev_desc_enc = Bidirectional(eval(params['RNN_TYPE'])(params['PREV_SENT_ENCODER_HIDDEN_SIZE'],
W_regularizer=l2(
params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(
params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(
params['RECURRENT_WEIGHT_DECAY']),
dropout_W=params['RECURRENT_DROPOUT_P'] if
params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params['RECURRENT_DROPOUT_P'] if
params[
'USE_RECURRENT_DROPOUT'] else None,
return_sequences=False),
name='prev_desc_emb_bidirectional_encoder_' + params['RNN_TYPE'],
merge_mode='concat')(prev_desc_emb)
else:
prev_desc_enc = eval(params['RNN_TYPE'])(params['PREV_SENT_ENCODER_HIDDEN_SIZE'],
W_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
U_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
b_regularizer=l2(params['RECURRENT_WEIGHT_DECAY']),
dropout_W=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,
dropout_U=params['RECURRENT_DROPOUT_P'] if params[
'USE_RECURRENT_DROPOUT'] else None,