-
Notifications
You must be signed in to change notification settings - Fork 2
/
triple_GRU_like_ungated_baseline-train-w-vision-noise.py
553 lines (478 loc) · 23.8 KB
/
triple_GRU_like_ungated_baseline-train-w-vision-noise.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
import sys
import glob
import scipy.io as sio
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import torchvision.models as models
from matplotlib import pyplot as plt
import numpy as np
import h5py
from PIL import Image
from sklearn.externals import joblib
import shutil
import os
import random
import pickle
import time
import gc
import re
from tensorboardX import SummaryWriter
import time
import math
from torchvision import datasets, models, transforms
import matplotlib.cm as cm
import cv2
import pandas as pd
from sklearn.metrics import precision_score, recall_score, confusion_matrix, classification_report, accuracy_score, f1_score
from torch.utils.data import Dataset, DataLoader
from mosei_dataloader import mosei
from torch.nn.parameter import Parameter
from models.highway import GRULikeUpdate
torch.manual_seed(777)
torch.cuda.manual_seed(777)
np.random.seed(777)
preprocess = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
'---------------------------------------------------LSTM VocalNet-------------------------------------------------------'
class VocalNet(nn.Module):
def __init__(self,input_size,hidden_size,num_layers):
super(VocalNet, self).__init__()
self.lstm = nn.LSTM(input_size,hidden_size,num_layers,bidirectional=True)
self.linear = nn.Linear(hidden_size, 6)
def forward(self,x):
x = torch.transpose(x,0,1)
hiddens,_ = self.lstm(x)
hiddens = hiddens.squeeze(1)
return hiddens
'---------------------------------------------------LSTM TextNet-------------------------------------------------------'
class WordvecNet(nn.Module):
# def __init__(self,input_size,hidden_size,num_layers,out_size,dropout=0.2,bidirectional=False):
def __init__(self,input_size,hidden_size,num_layers,dropout=0.2,bidirectional=True):
super(WordvecNet, self).__init__()
# self.rnn = nn.LSTM(input_size,hidden_size,num_layers,dropout,bidirectional,batch_first=True)
self.rnn = nn.LSTM(input_size,hidden_size,num_layers,dropout,bidirectional=bidirectional)
def forward(self,x):
"""
param x: tensor of shape (batch_size, seq_len, in_size)
"""
# output,final_hiddens = self.rnn(x)
# return output,final_hiddens
x = torch.transpose(x,0,1)
hiddens,_ = self.rnn(x)
hiddens = hiddens.squeeze(1)
return hiddens
'---------------------------------------------------LSTM VisualNet-------------------------------------------------------'
class VisionNet(nn.Module):
def __init__(self,input_size,hidden_size,num_layers):
super(VisionNet, self).__init__()
self.lstm = nn.LSTM(input_size,hidden_size,num_layers,bidirectional=True)
def forward(self,x):
x = torch.transpose(x,0,1)
hiddens,_ = self.lstm(x)
hiddens = hiddens.squeeze(1)
return hiddens
'---------------------------------------------------Gated Attention----------------------------------------------------'
class GatedAttention(nn.Module):
def __init__(self,att_input_size,att_hidden_size,att_num_layers,no_of_emotions):
super(GatedAttention, self).__init__()
self.lstm = nn.LSTM(att_input_size,att_hidden_size,att_num_layers)
self.linear = nn.Linear(att_hidden_size, no_of_emotions)
def forward(self,vocal,vision):
vocal = vocal.repeat(45,1)
vision = vision.squeeze(2)
vision = vision.squeeze(2)
fusion = vocal*vision
fusion = fusion.unsqueeze(0)
fusion = fusion.transpose(0,1)
hiddens,_ = self.lstm(fusion)
outputs = self.linear(hiddens[-1])
return outputs
'---------------------------------------------------Triple Attention----------------------------------------------------'
class TripleAttention(nn.Module):
def __init__(self,no_of_emotions,dan_hidden_size,attention_hidden_size,gated_mem):
super(TripleAttention, self).__init__()
N = dan_hidden_size
N2 = attention_hidden_size
self.gated_mem = gated_mem
self.Wvision_gh = nn.Linear(N2,1)
self.Wvocal_gh = nn.Linear(N2,1)
self.Wemb_gh = nn.Linear(N2,1)
if gated_mem:
self.gated_mem_update = GRULikeUpdate(4*N, N, 4*N, 3*N)
else:
self.mem_update_fc = nn.Linear(3*N, N)
''' K= 1 '''
self.Wvision_1 = nn.Linear(N,N2)
self.Wvision_m1 = nn.Linear(N,N2)
self.Wvision_h1 = nn.Linear(N2,1)
self.Wvocal_1 = nn.Linear(N,N2)
self.Wvocal_m1 = nn.Linear(N,N2)
self.Wvocal_h1 = nn.Linear(N2,1)
self.Wemb_1 = nn.Linear(N,N2)
self.Wemb_m1 = nn.Linear(N,N2)
self.Wemb_h1 = nn.Linear(N2,1)
''' K = 2 '''
self.Wvision_2 = nn.Linear(N,N2)
self.Wvision_m2 = nn.Linear(N,N2)
self.Wvision_h2 = nn.Linear(N2,1)
self.Wvocal_2 = nn.Linear(N,N2)
self.Wvocal_m2 = nn.Linear(N,N2)
self.Wvocal_h2 = nn.Linear(N2,1)
self.Wemb_2 = nn.Linear(N,N2)
self.Wemb_m2 = nn.Linear(N,N2)
self.Wemb_h2 = nn.Linear(N2,1)
''' K = 3 '''
self.Wvision_3 = nn.Linear(N,N2)
self.Wvision_m3 = nn.Linear(N,N2)
self.Wvision_h3 = nn.Linear(N2,1)
self.Wvocal_3 = nn.Linear(N,N2)
self.Wvocal_m3 = nn.Linear(N,N2)
self.Wvocal_h3 = nn.Linear(N2,1)
self.Wemb_3 = nn.Linear(N,N2)
self.Wemb_m3 = nn.Linear(N,N2)
self.Wemb_h3 = nn.Linear(N2,1)
self.fc = nn.Linear(N, no_of_emotions)
def forward(self,vocal,vision,emb):
N = dan_hidden_size
N2 = attention_hidden_size
one_constant = Variable(torch.ones(1,N).float(), requires_grad=False).cuda()
# Sorting out vision
# print(resnet_output.size())
# resnet_output = resnet_output.mean(0)
# resnet_output = resnet_output.view(512,49)
# vision = resnet_output.transpose(0,1)
'-------------------------------------------------Initializing Memory--------------------------------------'
# vision_zero = vision.mean(0).unsqueeze(0)
# vocal_zero = vocal.mean(0).unsqueeze(0)
# emb_zero = emb.mean(0).unsqueeze(0)
# m_zero = vision_zero * vocal_zero * emb_zero
m_zero = Variable(torch.zeros([1,dan_hidden_size]).float(),requires_grad=False).cuda()
m_zero_vision = m_zero.repeat(vision.size(0),1)
m_zero_vocal = m_zero.repeat(vocal.size(0),1)
m_zero_emb = m_zero.repeat(emb.size(0),1)
'--------------------------------------------------K = 1 ---------------------------------------------------'
# Visual Attention
h_one_vision = F.tanh(self.Wvision_1(vision)) # *F.tanh(self.Wvision_m1(m_zero_vision))
a_one_vision = F.softmax(self.Wvision_h1(h_one_vision),dim=0) ## along dimsions
vision_one = (a_one_vision.repeat(1,N)*vision).sum(0)
# gate_one_vision = F.sigmoid(self.Wvision_gh(h_one_vision.mean(0).unsqueeze(0)))
# vision_one_pregate = (a_one_vision.repeat(1,N)*vision).sum(0).unsqueeze(0)
# vision_one = gate_one_vision.repeat(1,N)*vision_one_pregate + (((1-gate_one_vision).repeat(1,N))*one_constant)
# Vocal Attention
h_one_vocal = F.tanh(self.Wvocal_1(vocal)) # *F.tanh(self.Wvocal_m1(m_zero_vocal))
a_one_vocal = F.softmax(self.Wvocal_h1(h_one_vocal),dim=0)
vocal_one = (a_one_vocal.repeat(1,N)*vocal).sum(0)
# gate_one_vocal = F.sigmoid(self.Wvocal_gh(h_one_vocal.mean(0).unsqueeze(0)))
# vocal_one_pregate = (a_one_vocal.repeat(1,N)*vocal).sum(0).unsqueeze(0)
# vocal_one = gate_one_vocal.repeat(1,N)*vocal_one_pregate + (((1-gate_one_vocal).repeat(1,N))*one_constant)
# Emb Attention
h_one_emb = F.tanh(self.Wemb_1(emb)) # *F.tanh(self.Wemb_m1(m_zero_emb))
a_one_emb = F.softmax(self.Wemb_h1(h_one_emb),dim=0)
emb_one = (a_one_emb.repeat(1,N)*emb).sum(0)
# gate_one_emb = F.sigmoid(self.Wemb_gh(h_one_emb.mean(0).unsqueeze(0)))
# emb_one_pregate = (a_one_emb.repeat(1,N)*emb).sum(0).unsqueeze(0)
# emb_one = gate_one_emb.repeat(1,N)*emb_one_pregate + (((1-gate_one_emb).repeat(1,N))*one_constant)
# Memory Update
if self.gated_mem:
concated = torch.cat((vision_one, vocal_one, emb_one)).unsqueeze(0)
m_one = self.gated_mem_update(m_zero, concated)
else:
concated = torch.cat((vision_one, vocal_one, emb_one)).unsqueeze(0)
m_one = m_zero + F.tanh(self.mem_update_fc(concated))
m_one_vision = m_one.repeat(vision.size(0),1)
m_one_vocal = m_one.repeat(vocal.size(0),1)
m_one_emb = m_one.repeat(emb.size(0),1)
'--------------------------------------------------K = 2 ---------------------------------------------------'
# Visual Attention
h_two_vision = F.tanh(self.Wvision_2(vision))*F.tanh(self.Wvision_m2(m_one_vision))
a_two_vision = F.softmax(self.Wvision_h2(h_two_vision),dim=0)
vision_two = (a_two_vision.repeat(1,N)*vision).sum(0)
# gate_two_vision = F.sigmoid(self.Wvision_gh(h_two_vision.mean(0).unsqueeze(0)))
# vision_two_pregate = (a_two_vision.repeat(1,N)*vision).sum(0).unsqueeze(0)
# vision_two = gate_two_vision.repeat(1,N)*vision_two_pregate + (((1-gate_two_vision).repeat(1,N))*one_constant)
# Vocal Attention
h_two_vocal = F.tanh(self.Wvocal_2(vocal))*F.tanh(self.Wvocal_m2(m_one_vocal))
a_two_vocal = F.softmax(self.Wvocal_h2(h_two_vocal),dim=0)
vocal_two = (a_two_vocal.repeat(1,N)*vocal).sum(0)
# gate_two_vocal = F.sigmoid(self.Wvocal_gh(h_two_vocal.mean(0).unsqueeze(0)))
# vocal_two_pregate = (a_two_vocal.repeat(1,N)*vocal).sum(0).unsqueeze(0)
# vocal_two = gate_two_vocal.repeat(1,N)*vocal_two_pregate + (((1-gate_two_vocal).repeat(1,N))*one_constant)
# Emb Attention
h_two_emb = F.tanh(self.Wemb_2(emb))*F.tanh(self.Wemb_m2(m_one_emb))
a_two_emb = F.softmax(self.Wemb_h2(h_two_emb),dim=0)
emb_two = (a_two_emb.repeat(1,N)*emb).sum(0)
# gate_two_emb = F.sigmoid(self.Wemb_gh(h_two_emb.mean(0).unsqueeze(0)))
# emb_two_pregate = (a_two_emb.repeat(1,N)*emb).sum(0).unsqueeze(0)
# emb_two = gate_two_emb.repeat(1,N)*emb_two_pregate + (((1-gate_two_emb).repeat(1,N))*one_constant)
# Memory Update
if self.gated_mem:
concated = torch.cat((vision_two, vocal_two, emb_two)).unsqueeze(0)
m_two = self.gated_mem_update(m_one, concated)
else:
concated = torch.cat((vision_two, vocal_two, emb_two)).unsqueeze(0)
m_two = m_one + F.tanh(self.mem_update_fc(concated))
m_two_vision = m_two.repeat(vision.size(0),1)
m_two_vocal = m_two.repeat(vocal.size(0),1)
m_two_emb = m_two.repeat(emb.size(0),1)
'--------------------------------------------------K = 3 ---------------------------------------------------'
# Visual Attention
h_three_vision = F.tanh(self.Wvision_3(vision))*F.tanh(self.Wvision_m3(m_two_vision))
a_three_vision = F.softmax(self.Wvision_h3(h_three_vision),dim=0)
vision_three = (a_three_vision.repeat(1,N)*vision).sum(0)
# gate_three_vision = F.sigmoid(self.Wvision_gh(h_three_vision.mean(0).unsqueeze(0)))
# vision_three_pregate = (a_three_vision.repeat(1,N)*vision).sum(0).unsqueeze(0)
# vision_three = gate_three_vision.repeat(1,N)*vision_three_pregate + (((1-gate_three_vision).repeat(1,N))*one_constant)
# Vocal Attention
h_three_vocal = F.tanh(self.Wvocal_3(vocal))*F.tanh(self.Wvocal_m3(m_two_vocal))
a_three_vocal = F.softmax(self.Wvocal_h3(h_three_vocal),dim=0)
vocal_three = (a_three_vocal.repeat(1,N)*vocal).sum(0)
# gate_three_vocal = F.sigmoid(self.Wvocal_gh(h_three_vocal.mean(0).unsqueeze(0)))
# vocal_three_pregate = (a_three_vocal.repeat(1,N)*vocal).sum(0).unsqueeze(0)
# vocal_three = gate_three_vocal.repeat(1,N)*vocal_three_pregate + (((1-gate_three_vocal).repeat(1,N))*one_constant)
# Emb Attention
h_three_emb = F.tanh(self.Wemb_3(emb))*F.tanh(self.Wemb_m3(m_two_emb))
a_three_emb = F.softmax(self.Wemb_h3(h_three_emb),dim=0)
emb_three = (a_three_emb.repeat(1,N)*emb).sum(0)
# gate_three_emb = F.sigmoid(self.Wemb_gh(h_three_emb.mean(0).unsqueeze(0)))
# emb_three_pregate = (a_three_emb.repeat(1,N)*emb).sum(0).unsqueeze(0)
# emb_three = gate_three_emb.repeat(1,N)*emb_three_pregate + (((1-gate_three_emb).repeat(1,N))*one_constant)
# Memory Update
if self.gated_mem:
concated = torch.cat((vision_three, vocal_three, emb_three)).unsqueeze(0)
m_three = self.gated_mem_update(m_two, concated)
else:
concated = torch.cat((vision_three, vocal_three, emb_three)).unsqueeze(0)
m_three = m_two + F.tanh(self.mem_update_fc(concated))
return m_three
'-------------------------------------------------Prediction--------------------------------------------------'
# return m_two
# outputs = self.fc(m_two)
# # print(outputs)
# return outputs
'---------------------------------------------------Memory to Emotion Decoder------------------------------------------'
class predictor(nn.Module):
def __init__(self,no_of_emotions,hidden_size,output_scale_factor = 1, output_shift = 0):
super(predictor, self).__init__()
self.fc = nn.Linear(hidden_size, no_of_emotions)
# self.output_scale_factor = Parameter(torch.FloatTensor([output_scale_factor]), requires_grad=False)
# self.output_shift = Parameter(torch.FloatTensor([output_shift]), requires_grad=False)
def forward(self,x):
x = self.fc(x)
# x = F.sigmoid(x)
# x = x*self.output_scale_factor + self.output_shift
return x
'------------------------------------------------------Hyperparameters-------------------------------------------------'
batch_size = 1
mega_batch_size = 1
no_of_emotions = 6
use_CUDA = True
use_pretrained = False
num_workers = 20
test_mode = False
val_mode = False
train_mode = True
use_clean_test = True
no_of_epochs = 1000
vocal_input_size = 74 # Dont Change
vision_input_size = 35 # Dont Change
wordvec_input_size = 300
vocal_num_layers = 2
vision_num_layers = 2
wordvec_num_layers = 2
vocal_hidden_size = 512
vision_hidden_size = 512
wordvec_hidden_size = 512
dan_hidden_size = 1024
attention_hidden_size = 128
gated_mem = False
'----------------------------------------------------------------------------------------------------------------------'
Vocal_encoder = VocalNet(vocal_input_size, vocal_hidden_size, vocal_num_layers)
Vision_encoder = VisionNet(vision_input_size, vision_hidden_size, vision_num_layers)
Wordvec_encoder = WordvecNet(wordvec_input_size, wordvec_hidden_size, wordvec_num_layers)
Attention = TripleAttention(no_of_emotions,dan_hidden_size,attention_hidden_size, gated_mem)
Predictor = predictor(no_of_emotions,dan_hidden_size)
if train_mode:
train_dataset = mosei(mode= "train")
data_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True,num_workers = num_workers)
elif val_mode:
val_dataset = mosei(mode = "val")
data_loader = torch.utils.data.DataLoader(dataset=val_dataset,
batch_size=1,
shuffle=False,num_workers = num_workers)
no_of_epochs = 1
else:
test_dataset = mosei(mode = "test")
data_loader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=1,
shuffle=False,num_workers = num_workers)
no_of_epochs = 1
curr_epoch = 0
total = 0
'----------------------------------------------------------------------------------------------------------------------'
Vocal_encoder = Vocal_encoder.cuda()
Attention = Attention.cuda()
Vision_encoder = Vision_encoder.cuda()
Wordvec_encoder = Wordvec_encoder.cuda()
Predictor = Predictor.cuda()
'----------------------------------------------------------------------------------------------------------------------'
criterion = nn.MSELoss(size_average = False)
# params = list(Vocal_encoder.parameters())+ list(Attention.parameters()) + list(Wordvec_encoder.parameters()) + list(Vision_encoder.parameters()) + list(Predictor.parameters())[2:]
params = list(Vocal_encoder.parameters())+ list(Attention.parameters()) + list(Wordvec_encoder.parameters()) + list(Vision_encoder.parameters()) + list(Predictor.parameters())
print('Parameters in the model = ' + str(len(params)))
optimizer = torch.optim.Adam(params, lr = 0.0001)
# optimizer = torch.optim.SGD(params, lr =0.001,momentum = 0.9 )
'------------------------------------------Saving Intermediate Models--------------------------------------------------'
def save_checkpoint(state, is_final, filename='attention_net'):
filename = filename +'_'+str(state['epoch'])+'.pth.tar'
os.system("mkdir -p TAN_GRU_ungated_baseline-train-w-vision-noise")
torch.save(state, './TAN_GRU_ungated_baseline-train-w-vision-noise/'+filename)
if is_final:
shutil.copyfile(filename, 'model_final.pth.tar')
'-------------------------------------------Setting into train mode----------------------------------------------------'
if not train_mode:
Vision_encoder.train(False)
Vocal_encoder.train(False)
Wordvec_encoder.train(False)
Attention.train(False)
Predictor.train(False)
else:
Vision_encoder.train(True)
Vocal_encoder.train(True)
Wordvec_encoder.train(True)
Attention.train(True)
Predictor.train(True)
'----------------------------------------------------------------------------------------------------------------------'
epoch = 0
y_true = []
y_pred = []
while epoch<no_of_epochs:
j_start = 0
running_loss = 0
running_corrects = 0
if use_pretrained:
pretrained_file = './TAN_GRU_ungated_baseline-train-w-vision-noise/triple_attention_net__4.pth.tar'
# pretrained_file = './TAN/triple_attention_net__8.pth.tar'
checkpoint = torch.load(pretrained_file)
Vocal_encoder.load_state_dict(checkpoint['Vocal_encoder'])
Vision_encoder.load_state_dict(checkpoint['Vision_encoder'])
Wordvec_encoder.load_state_dict(checkpoint['Wordvec_encoder'])
Attention.load_state_dict(checkpoint['Attention'])
Predictor.load_state_dict(checkpoint['Predictor'])
use_pretrained = False
if train_mode:
epoch = checkpoint['epoch']+1
optimizer.load_state_dict(checkpoint['optimizer'])
K = 0
#### compute vocal mean and std #####################
vision_mean = torch.zeros(vision_input_size)
vision_std = torch.zeros(vision_input_size)
vision_all_size = 0
for i,(vision,vocal,emb,gt) in enumerate(data_loader):
vision_mean = vision_mean + torch.mul((vision.float().mean(dim=1).squeeze(0)) , (float(vision.size()[1])/1000))
vision_std = vision_std + torch.mul((vision.float().std(dim=1).squeeze(0)) , (float(vision.size()[1])/1000))
vision_all_size += float(vision.size()[1])/1000
if i%1000==0 and i>0:
print('------- Computing vision mean '+str(i)+' --------')
vision_mean.div_(vision_all_size)
vision_std.div_(vision_all_size)
#####################################################
for i,(vision,vocal,emb,gt) in enumerate(data_loader):
if use_CUDA:
# if i==0 or i==1:
# print('To load data into CUDA')
# print(vision.size())
# print(vocal.size())
# print(emb.size())
#### CORRUPT VISION INPUT ######################
# vision = Variable(vision.float()).cuda()
if batch_size != 1:
sys.stderr.write('assuming batch size=1 in add noise')
sys.exit()
if train_mode and i%2 == 0:
vision_noised = torch.zeros(batch_size,vision.size()[1],vision.size()[2])
for j in range(0,vision.size()[1]):
vision_noised[0,j,:] = torch.normal(vision_mean,vision_std).add_(vision[0,j,:].float())
vision = Variable(vision_noised.float()).cuda()
elif train_mode and i%2 != 0:
vision = Variable(vision.float()).cuda()
elif ( test_mode or val_mode ) and ( use_clean_test is True ):
vision = Variable(vision.float()).cuda()
elif ( test_mode or val_mode ) and ( use_clean_test is not True ):
vision_noised = torch.zeros(batch_size,vision.size()[1],vision.size()[2])
for j in range(0,vision.size()[1]):
vision_noised[0,j,:] = torch.normal(vision_mean,vision_std).add_(vision[0,j,:].float())
vision = Variable(vision_noised.float()).cuda()
##############################################
vocal = Variable(vocal.float()).cuda()
emb = Variable(emb.float()).cuda()
gt = Variable(gt.float()).cuda()
vision_output = Vision_encoder(vision)
vocal_output = Vocal_encoder(vocal)
emb_output = Wordvec_encoder(emb)
# output = Attention(vocal_output,vision_output)
output = Attention(vocal_output,vision_output,emb_output)
outputs = Predictor(output)
outputs = torch.clamp(outputs,0,3)
loss = criterion(outputs, gt)
if train_mode and K%mega_batch_size==0:
loss.backward()
optimizer.step()
optimizer.zero_grad()
Vocal_encoder.zero_grad()
Vision_encoder.zero_grad()
Wordvec_encoder.zero_grad()
Attention.zero_grad()
Predictor.zero_grad()
# outputs_ = Variable(torch.FloatTensor([ 0.1565 ,0.1233, 0.0401, 0.4836 , 0.1596, 0.04842])).cuda()
# loss = criterion(outputs_, gt)
running_loss += loss.data[0]
K+=1
average_loss = running_loss/K
if train_mode and K%mega_batch_size==0:
print('Training -- Epoch [%d], Sample [%d], Average Loss: %.4f'
% (epoch+1, K, average_loss))
elif val_mode:
print('Validating -- Epoch [%d], Sample [%d], Average Loss: %.4f'
% (epoch+1, K, average_loss))
elif test_mode:
print('Testing -- Epoch [%d], Sample [%d], Average Loss: %.4f'
% (epoch+1, K, average_loss))
'-------------------------------------------------Saving model after every epoch-----------------------------------'
if train_mode:
save_checkpoint({
'epoch': epoch,
'loss' : running_loss,
'correct' : running_corrects,
'j_start' : 0,
'Vocal_encoder': Vocal_encoder.state_dict(),
'Vision_encoder' : Vision_encoder.state_dict(),
'Wordvec_encoder' : Wordvec_encoder.state_dict(),
'Attention' : Attention.state_dict(),
'Predictor' : Predictor.state_dict(),
'optimizer': optimizer.state_dict(),
}, False,'triple_attention_net_')
epoch+= 1
'------------------------------------------------------Saving model after training completion--------------------------'
if train_mode:
save_checkpoint({
'epoch': epoch,
'loss' : running_loss,
'j_start' : 0,
'Vocal_encoder': Vocal_encoder.state_dict(),
'Vision_encoder' : Vision_encoder.state_dict(),
'Wordvec_encoder' : Wordvec_encoder.state_dict(),
'Attention' : Attention.state_dict(),
'Predictor' : Predictor.state_dict(),
'optimizer': optimizer.state_dict(),
}, False)
# print('Accuracy:', accuracy_score(y_true, y_pred))
# print('F1 score:', f1_score(y_true, y_pred,average = 'weighted'))
# print('Recall:', recall_score(y_true, y_pred,average ='weighted'))
# print('Precision:', precision_score(y_true, y_pred,average = 'weighted'))