-
Notifications
You must be signed in to change notification settings - Fork 1
/
gmu_model.py
73 lines (53 loc) · 1.75 KB
/
gmu_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
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
class LinearClassifier(nn.Module):
def __init__(self, encoding_size):
super(LinearClassifier, self).__init__()
self.linear = nn.Linear(encoding_size, encoding_size)
def forward(self, x):
x = self.linear(x)
x = torch.tanh(x)
return x
class LinearCombine(nn.Module):
def __init__(self, encoding_size):
super().__init__()
self.linear = nn.Linear(encoding_size, 27) # 27 is the number of genres
self.sigmoid = nn.Sigmoid()
def forward(self, x, y):
x = self.linear(torch.cat((x, y), dim=1))
x = self.sigmoid(x)
return x
class Gated_MultiModal_Unit():
def __init__(self, img_model, text_model):
super().__init__()
self.bert_model = text_model
self.resnet_model = img_model
self.hv_gate = LinearClassifier(27) # num of categories
self.ht_gate = LinearClassifier(27) # num of categories
self.z_gate = LinearCombine(54) # 2* num of categories, for data fusion
def forward(self, mode,imgs, texts, text_masks):
if (mode == 'train'):
self.hv_gate.train()
self.ht_gate.train()
self.z_gate.train()
else:
self.hv_gate.eval()
self.ht_gate.eval()
self.z_gate.eval()
self.resnet_model.eval()
self.bert_model.eval()
# self.resnet_model.cuda()
# self.bert_model.cuda()
img_pred = self.resnet_model(imgs)
text_pred = self.bert_model(texts, text_masks).logits
# self.hv_gate.cuda()
# self.ht_gate.cuda()
# self.z_gate.cuda()
h_v = self.hv_gate(img_pred)
h_t = self.ht_gate(text_pred)
z = self.z_gate(img_pred, text_pred)
h = (torch.mul(z, h_v)) + (torch.mul((1-z), h_t))
predictions = h
return predictions