-
Notifications
You must be signed in to change notification settings - Fork 3
/
models.py
230 lines (168 loc) · 7.55 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
import torch
from torch import nn
from transformers import AdamW
import gluonnlp as nlp
from kobert import get_pytorch_kobert_model, get_tokenizer
import sentencepiece
# apt-get update && apt-get -y install build-essential
class LSTM(nn.Module):
def __init__(self, args):
super(LSTM, self).__init__()
self.bi = args.bidirectional
self.dropout = nn.Dropout(args.dr_rate)
self.txt_emb = nn.Embedding(args.vocab_size, args.hidden_dim)
self.lstm = nn.LSTM(input_size=args.hidden_dim, hidden_size=args.hidden_dim//4, batch_first=True, bidirectional=True)
def forward(self, inputs):
embs = self.txt_emb(inputs)
o, (h, c) = self.lstm(embs)
h = self.dropout(h)
if self.bi:
h = torch.cat([h[-1], h[-2]], dim=-1)
else:
h = h[-1]
return h
def _init_weight(self):
for m in self.modules():
if isinstance(m, nn.LSTM):
nn.init.xavier_normal_(m.weight)
nn.init.zeros_(m.bias)
class UserItem(nn.Module):
def __init__(self, args):
super(UserItem, self).__init__()
self.num_users = args.num_users
self.num_items = args.num_items
self.hidden_dim = args.hidden_dim
self.user_emb = nn.Embedding(self.num_users, self.hidden_dim)
self.item_emb = nn.Embedding(self.num_items, self.hidden_dim)
def forward(self, user_id, item_id):
user_emb = self.user_emb(user_id)
item_emb = self.item_emb(item_id)
outs = torch.concat([user_emb, item_emb], dim=-1)
return outs
class CNNBlock(nn.Module):
def __init__(self, args):
super(CNNBlock, self).__init__()
self.size = args.size
self.args = args
self.hidden_dim = args.hidden_dim
self.pooling = 2
self.num_layers = [3, 8, 16, 32, 64, 128]
self.layers = nn.Sequential()
for idx, (in_dim, out_dim) in enumerate(zip(self.num_layers[:-1], self.num_layers[1:])):
self.layers.add_module(f'cnn_block-{idx+1}', self.block3x3(in_dim=in_dim, out_dim=out_dim, activation='relu', pooling=self.pooling))
self.fc_layer = nn.Sequential(
nn.Linear( args.size * args.size * self.num_layers[-1] // (self.pooling ** (len(self.num_layers)-1))**2, self.hidden_dim)
)
def block3x3(self, in_dim=3, out_dim=8, activation='relu', pooling=False):
layers = nn.Sequential(
self.conv3x3(in_dim, out_dim),
nn.BatchNorm2d(out_dim)
)
if activation == 'relu':
layers.add_module('relu', nn.ReLU())
elif activation == 'softmax':
layers.add_module('softmax', nn.Softmax())
if pooling:
layers.add_module('pooling', nn.MaxPool2d(pooling))
return layers
def forward(self, img):
outs = self.layers(img)
outs = self.fc_layer(outs.flatten(1))
return outs
def conv3x3(self, in_dim, out_dim, stride = 1, padding=1):
return nn.Conv2d(in_dim, out_dim, kernel_size=3, stride=stride, padding=padding, bias=False)
def conv1x1(self, in_dim, out_dim, stride = 1):
return nn.Conv2d(in_dim, out_dim, kernel_size=1, stride=stride, bias=False)
class BERTClassifier(nn.Module):
def __init__(self, args, bert_model):
super(BERTClassifier, self).__init__()
self.model = bert_model
self.hidden_dim = args.hidden_dim
self.dr_rate = args.dr_rate
self.classifier = nn.Linear(self.hidden_size, self.hidden_dim)
if self.dr_rate: self.dropout = nn.Dropout(p=self.dr_rate)
def gen_attention_mask(self, token_ids, valid_length):
attention_mask = torch.zeros_like(token_ids)
for i, v in enumerate(valid_length):
attention_mask[i][:v] = 1
return attention_mask.float()
def forward(self, token_ids, valid_length, segment_ids):
attention_mask = self.gen_attention_mask(token_ids, valid_length)
_, pooler = self.model(input_ids=token_ids, token_type_ids=segment_ids, attention_mask=attention_mask.float())
if self.dr_rate: pooler = self.dropout(pooler)
FClayer = self.classifier(pooler)
return FClayer
# Model: user_id + item_id + reviews + images
class MMR(nn.Module):
def __init__(self, args):
super(MMR, self).__init__()
self.ncf = UserItem(args)
self.lstm = LSTM(args)
self.resnet = CNNBlock(args)
self.hidden_dim = args.hidden_dim
self.fc_layer = nn.Sequential(
nn.Linear(self.hidden_dim * (2 + 1) + self.hidden_dim // 2, self.hidden_dim),
nn.ReLU(),
nn.Linear(self.hidden_dim, self.hidden_dim//2),
nn.ReLU(),
nn.Linear(self.hidden_dim // 2, 1)
)
self.sigmoid = nn.Sigmoid()
def forward(self, user, item, review, image):
ui_emb = self.ncf(user, item) # (b, hidden_dim * 2) 128
review_emb = self.lstm(review) # (b, hidden_dim // 2) 32
img_emb = self.resnet(image) # (b, hidden_dim)
outs = torch.concat([ui_emb, review_emb], dim=-1)
outs = torch.concat([outs, img_emb], dim=-1)
outs = self.fc_layer(outs)
outs = self.sigmoid(outs)
return outs
# Baseline Model: user_id + item_id + reviews
class NCF_LSTM(nn.Module):
def __init__(self, args):
super(NCF_LSTM, self).__init__()
self.user_emb = nn.Embedding(args.num_users, args.hidden_dim)
self.item_emb = nn.Embedding(args.num_items, args.hidden_dim)
self.lstm = LSTM(args)
self.hidden_dim = args.hidden_dim
self.fc_layer = nn.Sequential(
nn.Linear(self.hidden_dim * 2 + self.hidden_dim // 2, self.hidden_dim),
nn.ReLU(),
nn.Linear(self.hidden_dim, self.hidden_dim//2),
nn.ReLU(),
nn.Linear(self.hidden_dim // 2, 1)
)
self.sigmoid = nn.Sigmoid()
def forward(self, user, item, review):
user_emb = self.user_emb(user)
item_emb = self.item_emb(item)
ui_emb = torch.concat([user_emb, item_emb], dim=-1)
review_emb = self.lstm(review) # (b, hidden_dim // 2) 32
outs = torch.concat([ui_emb, review_emb], dim=-1)
outs = self.fc_layer(outs)
outs = self.sigmoid(outs)
return outs
# Baseline Model: user_id + item_id
class NCF(nn.Module):
def __init__(self, args):
super(NCF, self).__init__()
self.num_users = args.num_users
self.num_items = args.num_items
self.hidden_dim = args.hidden_dim
self.user_emb = nn.Embedding(self.num_users, self.hidden_dim)
self.item_emb = nn.Embedding(self.num_items, self.hidden_dim)
self.fc_layer = nn.Sequential(
nn.Linear(self.hidden_dim*2, self.hidden_dim),
nn.ReLU(),
nn.Linear(self.hidden_dim, self.hidden_dim//2),
nn.ReLU(),
nn.Linear(self.hidden_dim//2, 1)
)
self.sigmoid = nn.Sigmoid()
def forward(self, user, item):
user_emb = self.user_emb(user)
item_emb = self.item_emb(item)
outs = torch.concat([user_emb, item_emb], dim=-1)
outs = self.fc_layer(outs)
outs = self.sigmoid(outs)
return outs