-
Notifications
You must be signed in to change notification settings - Fork 22
/
hfusion.py
484 lines (354 loc) · 17.8 KB
/
hfusion.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
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 6 10:37:22 2017
@author: soujanyaporia
"""
import numpy as np
np.random.seed(1337) # for reproducibility
from keras import backend as K
from keras.layers.core import Lambda
from keras.engine.topology import Layer
from keras.models import Sequential
from keras.layers import Input,Dense,GRU,LSTM,Concatenate,Dropout,Activation,Add, Masking
from keras.layers.pooling import AveragePooling1D,MaxPooling1D
from keras.layers.core import Flatten
from keras.callbacks import EarlyStopping
from keras.layers.convolutional import Conv1D
from keras.models import Model
from keras.layers.wrappers import TimeDistributed, Bidirectional
from keras.layers.core import Reshape
from keras.backend import shape
from keras.utils import plot_model
from keras.layers.merge import Multiply,Concatenate
import pickle
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import accuracy_score
from keras.optimizers import RMSprop,Adadelta,Adam
from keras.callbacks import Callback
import sys
def createOneHot(train_label, test_label):
maxlen = int(max(train_label.max(), test_label.max()))
train = np.zeros((train_label.shape[0], train_label.shape[1], maxlen+1))
test = np.zeros((test_label.shape[0], test_label.shape[1], maxlen+1))
for i in range(train_label.shape[0]):
for j in range(train_label.shape[1]):
train[i,j,train_label[i,j]]=1
for i in range(test_label.shape[0]):
for j in range(test_label.shape[1]):
test[i,j,test_label[i,j]]=1
return train, test
def calc_test_result(result, test_label, test_mask):
true_label=[]
predicted_label=[]
for i in range(result.shape[0]):
for j in range(result.shape[1]):
if test_mask[i,j]==1:
true_label.append(np.argmax(test_label[i,j] ))
predicted_label.append(np.argmax(result[i,j] ))
print("Confusion Matrix :")
print(confusion_matrix(true_label, predicted_label))
print("Classification Report :")
print(classification_report(true_label, predicted_label,digits=4))
print("Accuracy ", accuracy_score(true_label, predicted_label))
print("Macro Classification Report :")
print(precision_recall_fscore_support(true_label, predicted_label,average='macro'))
print("Weighted Classification Report :")
print(precision_recall_fscore_support(true_label, predicted_label,average='weighted'))
#print "Normal Classification Report :"
#print precision_recall_fscore_support(true_label, predicted_label)
def crop(a):
return a[:, 0:text_dim]
def crop1(a):
return a[:, text_dim:(text_dim+visual_dim)]
def crop2(a):
return a[:, (text_dim+visual_dim):dim]
def output_of_lambda(input_shape):
return (input_shape[0], text_dim)
def output_of_lambda1(input_shape):
return (input_shape[0], visual_dim)
def output_of_lambda2(input_shape):
return (input_shape[0], audio_dim)
# ################################################################################
# #Level 2
# #concatenate level 1 output to be sent to hfusion
# fused_tensor=Concatenate(axis=2)([context_1_2,context_1_3,context_2_3])
def load_bimodal_activations():
with open('./bimodal.pickle', 'rb') as handle:
activations = pickle.load(handle, encoding = 'latin1')
merged_train_data = activations['train_bimodal']
merged_test_data = activations['test_bimodal']
train_mask=activations['train_mask']
test_mask=activations['test_mask']
train_label=activations['train_label']
test_label=activations['test_label']
#Setting dummy utterances to be 0
for i in range(activations['train_bimodal'].shape[0]):
for j in range(activations['train_bimodal'].shape[1]):
if train_mask[i][j] == 0.0 :
merged_train_data[i,j,:]=0.0
for i in range(activations['test_bimodal'].shape[0]):
for j in range(activations['test_bimodal'].shape[1]):
if test_mask[i][j] == 0.0 :
merged_test_data[i,j,:]=0.0
audio_dim=500
visual_dim=500
text_dim=500
dim = audio_dim + visual_dim + text_dim
max_len = merged_train_data.shape[1] #max number of utterances per video
dim_proj=450
return merged_train_data, merged_test_data, train_label, test_label, train_mask, test_mask, max_len
def load_unimodal_activations():
with open('./unimodal.pickle', 'rb') as handle:
unimodal_activations = pickle.load(handle, encoding = 'latin1')
merged_train_data = np.concatenate((unimodal_activations['text_train'], unimodal_activations['audio_train'], unimodal_activations['video_train']), axis=2)
merged_test_data = np.concatenate((unimodal_activations['text_test'], unimodal_activations['audio_test'], unimodal_activations['video_test']), axis=2)
train_mask=unimodal_activations['train_mask']
test_mask=unimodal_activations['test_mask']
train_label=unimodal_activations['train_label']
test_label=unimodal_activations['test_label']
#Setting dummy utterances to be 0
for i in range(unimodal_activations['audio_train'].shape[0]):
for j in range(unimodal_activations['audio_train'].shape[1]):
if train_mask[i][j] == 0.0 :
merged_train_data[i,j,:]=0.0
for i in range(unimodal_activations['audio_test'].shape[0]):
for j in range(unimodal_activations['audio_test'].shape[1]):
if test_mask[i][j] == 0.0 :
merged_test_data[i,j,:]=0.0
global audio_dim, visual_dim, text_dim, dim, max_len, dim_proj
audio_dim=unimodal_activations['audio_train'].shape[2]
visual_dim=unimodal_activations['video_train'].shape[2]
text_dim=unimodal_activations['text_train'].shape[2]
dim = audio_dim + visual_dim + text_dim
max_len = merged_train_data.shape[1] #max number of utterances per video
dim_proj=450
return merged_train_data, merged_test_data, train_label, test_label, train_mask, test_mask
def Bimodal():
class hadamard2(Layer):
def __init__(self, prefix, **kwargs):
self.supports_masking = True
self.prefix = prefix
super(hadamard2, self).__init__(**kwargs)
def build(self, input_shape):
# Create a trainable weight variable for this layer.
self.output_dim = dim_proj
self.kernel1 = self.add_weight(name=self.prefix+'kernel1',
shape=(self.output_dim,),
initializer='TruncatedNormal',
trainable=True)
self.kernel2 = self.add_weight(name=self.prefix+'kernel2',
shape=(self.output_dim,),
initializer='TruncatedNormal',
trainable=True)
self.bias = self.add_weight(name=self.prefix+'bias',
shape=(self.output_dim,),
initializer='zeros',
trainable=True)
super(hadamard2, self).build(input_shape) # Be sure to call this somewhere!
def call(self, x):
assert (K.int_shape(x[0])[1] <= dim_proj)
return K.tanh(x[0]*self.kernel1 + x[1]*self.kernel2 + self.bias)
def compute_output_shape(self, input_shape):
return (input_shape[0][0],self.output_dim)
merged_train_data, merged_test_data, train_label, test_label, train_mask, test_mask = load_unimodal_activations()
#################################################################################
#Level 1 sub-model : Hfusion
x=Input(shape=(audio_dim+visual_dim+text_dim,), name='bi_input')
masked = Masking(mask_value =0.0 , name='bi_mask')(x)
x1 = Lambda(crop,output_shape=output_of_lambda, name='bi_crop1')(masked)
x2 =Lambda(crop1,output_shape=output_of_lambda1, name='bi_crop2')(masked)
x3 =Lambda(crop2,output_shape=output_of_lambda2, name='bi_crop3')(masked)
dense1=Dense(dim_proj, activation='tanh', use_bias=False, trainable=True, name='bi_dense1')(x1)
dense2=Dense(dim_proj, activation='tanh', use_bias=False, trainable=True, name='bi_dense2')(x2)
dense3=Dense(dim_proj, activation='tanh', use_bias=False, trainable=True, name='bi_dense3')(x3)
fused_1_2=hadamard2('1')([dense1,dense2])
fused_1_3=hadamard2('2')([dense1,dense3])
fused_2_3=hadamard2('3')([dense2,dense3])
bimodal_1_2=Model(x,outputs=fused_1_2)
bimodal_1_3=Model(x,outputs=fused_1_3)
bimodal_2_3=Model(x,outputs=fused_2_3)
################################################################################
#Level 1 sub-model : biLSTM
input_data = Input(shape=(max_len, K.int_shape(fused_1_2)[1],), name='bi_lstm_input1')
lstm = GRU(600, activation='tanh', return_sequences = True, dropout=0.4, name='bi_lstm1')(input_data)
inter = Dropout(0.9, name='bi_dropout11')(lstm)
inter = TimeDistributed(Dense(500,activation='tanh', name='bi_tdis11'))(inter)
output1 = TimeDistributed(Dense(4,activation='softmax', name='bi_tdis12'))(inter)
lstm1 = Model(input_data, output1)
aux1 = Model(input_data, inter)
input_data = Input(shape=(max_len, K.int_shape(fused_1_2)[1],), name='bi_lstm_input2')
lstm = GRU(600, activation='tanh', return_sequences = True, dropout=0.4, name='bi_lstm2')(input_data)
inter = Dropout(0.9, name='bi_dropout21')(lstm)
inter = TimeDistributed(Dense(500,activation='tanh', name='bi_tdis21'))(inter)
output2 = TimeDistributed(Dense(4,activation='softmax', name='bi_tdis22'))(inter)
lstm2 = Model(input_data, output2)
aux2 = Model(input_data, inter)
input_data = Input(shape=(max_len, K.int_shape(fused_1_2)[1],), name='bi_lstm_input3')
lstm = GRU(600, activation='tanh', return_sequences = True, dropout=0.4, name='bi_lstm3')(input_data)
inter = Dropout(0.9, name='bi_dropout31')(lstm)
inter = TimeDistributed(Dense(500,activation='tanh', name='bi_tdis31'))(inter)
output3 = TimeDistributed(Dense(4,activation='softmax', name='bi_tdis32'))(inter)
lstm3 = Model(input_data, output3)
aux3 = Model(input_data, inter)
################################################################################
#Complete Level 1 : Lstm applied on hfusion
main_input=Input(shape=(max_len,audio_dim+visual_dim+text_dim,), name='bi_main_input')
video_uttr_1_2=TimeDistributed(bimodal_1_2, name='bi_tdis_b12')(main_input)
video_uttr_1_3=TimeDistributed(bimodal_1_3, name='bi_tdis_b13')(main_input)
video_uttr_2_3=TimeDistributed(bimodal_2_3, name='bi_tdis_b23')(main_input)
aux_1_2=aux1(video_uttr_1_2)
aux_1_3=aux2(video_uttr_1_3)
aux_2_3=aux3(video_uttr_2_3)
context_1_2=lstm1(video_uttr_1_2)
BM1 = Model(main_input, context_1_2)
Aux1 = Model(main_input, aux_1_2)
context_1_3=lstm2(video_uttr_1_3)
BM2 = Model(main_input, context_1_3)
Aux2 = Model(main_input, aux_1_3)
context_2_3=lstm3(video_uttr_2_3)
BM3 = Model(main_input, context_2_3)
Aux3 = Model(main_input, aux_2_3)
#Training and fitting of Bimodals
optimizer=Adam(lr=0.001)
BM1.compile(optimizer=optimizer, loss='categorical_crossentropy', sample_weight_mode='temporal')
early_stopping = EarlyStopping(monitor='val_loss', patience=10)
BM1.fit(merged_train_data, train_label,
epochs=200,
batch_size=20,
sample_weight=train_mask,
shuffle=True, callbacks=[early_stopping],
validation_split=0.1)
train_result1 = Aux1.predict(merged_train_data)
test_result1 = Aux1.predict(merged_test_data)
BM2.compile(optimizer=optimizer, loss='categorical_crossentropy', sample_weight_mode='temporal')
early_stopping = EarlyStopping(monitor='val_loss', patience=10)
BM2.fit(merged_train_data, train_label,
epochs=200,
batch_size=20,
sample_weight=train_mask,
shuffle=True, callbacks=[early_stopping],
validation_split=0.1)
train_result2 = Aux2.predict(merged_train_data)
test_result2 = Aux2.predict(merged_test_data)
BM3.compile(optimizer=optimizer, loss='categorical_crossentropy', sample_weight_mode='temporal')
early_stopping = EarlyStopping(monitor='val_loss', patience=10)
BM3.fit(merged_train_data, train_label,
epochs=200,
batch_size=20,
sample_weight=train_mask,
shuffle=True, callbacks=[early_stopping],
validation_split=0.1)
train_result3 = Aux3.predict(merged_train_data)
test_result3 = Aux3.predict(merged_test_data)
train_bimodal = np.concatenate((train_result1, train_result2, train_result3), axis=2)
test_bimodal = np.concatenate((test_result1, test_result2, test_result3), axis=2)
bimodal_activations={}
bimodal_activations['train_bimodal'] = train_bimodal
bimodal_activations['test_bimodal'] = test_bimodal
bimodal_activations['train_mask']=train_mask
bimodal_activations['test_mask']= test_mask
bimodal_activations['train_label']=train_label
bimodal_activations['test_label']=test_label
#merge all output
print("Saving bimodal activations")
with open('bimodal.pickle', 'wb') as handle:
pickle.dump(bimodal_activations, handle, protocol=pickle.HIGHEST_PROTOCOL)
def Trimodal():
merged_train_data, merged_test_data, train_label, test_label, train_mask, test_mask, \
maxlen = load_bimodal_activations()
#################################################################################
class TestCallback(Callback):
def __init__(self, test_data):
self.test_data = test_data
def on_epoch_end(self, epoch, logs={}):
x, y, z = self.test_data
result = model.predict(x)
calc_test_result(result, y, z)
class hadamard3(Layer):
def __init__(self, **kwargs):
self.supports_masking = True
super(hadamard3, self).__init__(**kwargs)
def build(self, input_shape):
# Create a trainable weight variable for this layer.
self.output_dim = 500
self.kernel1 = self.add_weight(name='kernel1',
shape=(self.output_dim,),
initializer='glorot_uniform',
trainable=True)
self.kernel2 = self.add_weight(name='kernel2',
shape=(self.output_dim,),
initializer='glorot_uniform',
trainable=True)
self.kernel3 = self.add_weight(name='kernel3',
shape=(self.output_dim,),
initializer='glorot_uniform',
trainable=True)
self.bias = self.add_weight(name='bias',
shape=(self.output_dim,),
initializer='zeros',
trainable=True)
super(hadamard3, self).build(input_shape) # Be sure to call this somewhere!
def call(self, x, mask=None):
def crop(a):
return a[:, 0:500]
def crop1(a):
return a[:, 500:1000]
def crop2(a):
return a[:, 1000:1500]
def output_of_lambda(input_shape):
return (input_shape[0], 500)
def output_of_lambda1(input_shape):
return (input_shape[0], 500)
def output_of_lambda2(input_shape):
return (input_shape[0], 500)
x1=Lambda(crop,output_shape=output_of_lambda)(x)
x2=Lambda(crop1,output_shape=output_of_lambda1)(x)
x3=Lambda(crop2,output_shape=output_of_lambda2)(x)
ai = K.tanh(x1*self.kernel1 + x2*self.kernel2 + x3*self.kernel3 + self.bias)
return ai
def compute_output_shape(self, input_shape):
return (input_shape[0],self.output_dim)
def compute_mask(self, input, input_mask=None):
if isinstance(input_mask, list):
return [None] * len(input_mask)
else:
return None
#################################################################################
#Level 2: Hfusion3 trimodal
x_tri=Input(shape=(1500,), name='tri_input')
fused_1_2_3=hadamard3()(x_tri)
hfusion_model=Model(x_tri,outputs=fused_1_2_3)
#################################################################################
#Complete Level 2 : Lstm applied on hfusion3
main_input= Input(shape=(maxlen,1500,), name='tri_main_input')
masked = Masking(mask_value =0.0, name='tri_masking')(main_input)
video_uttr=TimeDistributed(hfusion_model, name='tri_td_1')(masked)
lstm = GRU(500, activation='tanh', return_sequences = True, dropout=0.35, name='tri_lstm')(video_uttr)
lstm = Masking(mask_value=0.)(lstm)
inter = Dropout(0.86, name="tri_dropout1")(lstm)
concatenate_=Concatenate(name="tri_concat")([video_uttr,inter])
inter1_tri = TimeDistributed(Dense(450,activation='relu', name='tri_td_2'))(concatenate_)
inter1_tri = Masking(mask_value=0.)(inter1_tri)
context_fused_1_2_3 = Dropout(0.86, name="tri_dropout2")(inter1_tri)
context_fused_1_2_3 = Masking(mask_value=0.)(context_fused_1_2_3)
predictions = Dense(4, activation='softmax', name='tri_td_3')(context_fused_1_2_3)
#################################################################################
model=Model(main_input,outputs=predictions)
optimizer=Adam(lr=0.0001)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', sample_weight_mode='temporal')
early_stopping = EarlyStopping(monitor='val_loss', patience=5)
#print train_label.shape
print(train_label[0])
model.fit(merged_train_data, train_label,
epochs=100,
batch_size=20,
sample_weight=train_mask,
shuffle=True, callbacks=[TestCallback((merged_test_data,test_label,test_mask))],
validation_split=0.1)
result = model.predict(merged_test_data)
calc_test_result(result, test_label, test_mask)
if __name__ == '__main__':
#Bimodal()
Trimodal()