-
Notifications
You must be signed in to change notification settings - Fork 1
/
model.py
408 lines (355 loc) · 15.6 KB
/
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
"""
Author: Yonglong Tian ([email protected])
Date: May 07, 2020
"""
from __future__ import print_function
import torch
import torch.nn as nn
class SupConLoss(nn.Module):
"""Supervised Contrastive Learning: https://arxiv.org/pdf/2004.11362.pdf.
It also supports the unsupervised contrastive loss in SimCLR"""
def __init__(self, temperature=0.2, contrast_mode='all',
base_temperature=0.2):
super(SupConLoss, self).__init__()
self.temperature = temperature
self.contrast_mode = contrast_mode
self.base_temperature = base_temperature
def forward(self, features, labels=None, mask=None):
"""Compute loss for model. If both `labels` and `mask` are None,
it degenerates to SimCLR unsupervised loss:
https://arxiv.org/pdf/2002.05709.pdf
Args:
features: hidden vector of shape [bsz, n_views, ...].
labels: ground truth of shape [bsz].
mask: contrastive mask of shape [bsz, bsz], mask_{i,j}=1 if sample j
has the same class as sample i. Can be asymmetric.
Returns:
A loss scalar.
"""
device = (torch.device('cuda')
if features.is_cuda
else torch.device('cpu'))
if len(features.shape) < 3:
raise ValueError('`features` needs to be [bsz, n_views, ...],'
'at least 3 dimensions are required')
if len(features.shape) > 3:
features = features.view(features.shape[0], features.shape[1], -1)
batch_size = features.shape[0]
if labels is not None and mask is not None:
raise ValueError('Cannot define both `labels` and `mask`')
elif labels is None and mask is None:
mask = torch.eye(batch_size, dtype=torch.float32).to(device)
elif labels is not None:
labels = labels.contiguous().view(-1, 1)
if labels.shape[0] != batch_size:
raise ValueError('Num of labels does not match num of features')
mask = torch.eq(labels, labels.T).float().to(device)
else:
mask = mask.float().to(device)
contrast_count = features.shape[1]
contrast_feature = torch.cat(torch.unbind(features, dim=1), dim=0)
if self.contrast_mode == 'one':
anchor_feature = features[:, 0]
anchor_count = 1
elif self.contrast_mode == 'all':
anchor_feature = contrast_feature
anchor_count = contrast_count
else:
raise ValueError('Unknown mode: {}'.format(self.contrast_mode))
# compute logits
anchor_dot_contrast = torch.div(
torch.matmul(anchor_feature, contrast_feature.T),
self.temperature)
# for numerical stability
logits_max, _ = torch.max(anchor_dot_contrast, dim=1, keepdim=True)
logits = anchor_dot_contrast - logits_max.detach()
# tile mask
mask = mask.repeat(anchor_count, contrast_count)
# mask-out self-contrast cases
logits_mask = torch.scatter(
torch.ones_like(mask),
1,
torch.arange(batch_size * anchor_count).view(-1, 1).to(device),
0
)
mask = mask * logits_mask
# compute log_prob
exp_logits = torch.exp(logits) * logits_mask
log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True))
# compute mean of log-likelihood over positive
mean_log_prob_pos = (mask * log_prob).sum(1) / mask.sum(1)
# loss
loss = - (self.temperature / self.base_temperature) * mean_log_prob_pos
loss = loss.view(anchor_count, batch_size).mean()
return loss
"""
Created on Mar 1, 2020
Pytorch Implementation of LightGCN in
Xiangnan He et al. LightGCN: Simplifying and Powering Graph Convolution Network for Recommendation
@author: Jianbai Ye ([email protected])
Define models here
"""
import world
import torch
from dataloader import BasicDataset
from torch import nn
import numpy as np
import torch.nn.functional as F
class BasicModel(nn.Module):
def __init__(self):
super(BasicModel, self).__init__()
def getUsersRating(self, users):
raise NotImplementedError
class PairWiseModel(BasicModel):
def __init__(self):
super(PairWiseModel, self).__init__()
def bpr_loss(self, users, pos, neg):
"""
Parameters:
users: users list
pos: positive items for corresponding users
neg: negative items for corresponding users
Return:
(log-loss, l2-loss)
"""
raise NotImplementedError
class PureMF(BasicModel):
def __init__(self,
config:dict,
dataset:BasicDataset):
super(PureMF, self).__init__()
self.num_users = dataset.n_users
self.num_items = dataset.m_items
self.latent_dim = config['latent_dim_rec']
self.f = nn.Sigmoid()
self.__init_weight()
def __init_weight(self):
self.embedding_user = torch.nn.Embedding(
num_embeddings=self.num_users, embedding_dim=self.latent_dim)
self.embedding_item = torch.nn.Embedding(
num_embeddings=self.num_items, embedding_dim=self.latent_dim)
print("using Normal distribution N(0,1) initialization for PureMF")
nn.init.normal_(self.embedding_user.weight, std=0.1)
nn.init.normal_(self.embedding_item.weight, std=0.1)
def getUsersRating(self, users):
users = users.long()
users_emb = self.embedding_user(users)
items_emb = self.embedding_item.weight
scores = torch.matmul(users_emb, items_emb.t())
return self.f(scores)
def score_u_i(self, users_emb, item_emb):
# score = torch.sum(users_emb[:, 1:]*item_emb[:, 1:], dim=1)
# score = score + users_emb[:, 0] + item_emb[:, 0]
score = torch.sum(users_emb*item_emb, dim=1)
return score
def CCL(self, pos_logits, neg_logits, _margin=0.8):
"""
:param y_pred: prdicted values of shape (batch_size, 1 + num_negs)
:param y_true: true labels of shape (batch_size, 1 + num_negs)
"""
pos_loss = torch.relu(1 - pos_logits)
neg_loss = torch.relu(neg_logits - _margin)
loss = pos_loss + neg_loss * 100
return loss.mean()
def bpr_loss(self, users, pos, neg):
users_emb = self.embedding_user(users.long())
pos_emb = self.embedding_item(pos.long())
neg_emb = self.embedding_item(neg.long())
pos_scores= self.score_u_i(users_emb, pos_emb)
neg_scores= self.score_u_i(users_emb, neg_emb)
loss = torch.mean(nn.functional.softplus(neg_scores - pos_scores))
reg_loss = (1/2)*(users_emb.norm(2).pow(2) +
pos_emb.norm(2).pow(2) +
neg_emb.norm(2).pow(2))/float(len(users))
return loss, reg_loss
def forward(self, users, items):
users = users.long()
items = items.long()
users_emb = self.embedding_user(users)
items_emb = self.embedding_item(items)
scores = torch.sum(users_emb*items_emb, dim=1)
return self.f(scores)
def xmrec_test(self, users, items):
users = users.long()
items = items.long()
users_emb = self.embedding_user(users)
items_emb = self.embedding_item(items)
scores = torch.sum(users_emb*items_emb, dim=1)
# scores = self.score_u_i(users_emb, items_emb) # 效果不行
return scores, users_emb, items_emb
class LightGCN(BasicModel):
def __init__(self,
config:dict,
dataset:BasicDataset):
super(LightGCN, self).__init__()
self.config = config
self.dataset : dataloader.BasicDataset = dataset
self.__init_weight()
def __init_weight(self):
self.num_users = self.dataset.n_users
self.num_items = self.dataset.m_items
self.latent_dim = self.config['latent_dim_rec']
self.n_layers = self.config['lightGCN_n_layers']
self.keep_prob = self.config['keep_prob']
self.A_split = self.config['A_split']
self.embedding_user = torch.nn.Embedding(
num_embeddings=self.num_users, embedding_dim=self.latent_dim)
self.embedding_item = torch.nn.Embedding(
num_embeddings=self.num_items, embedding_dim=self.latent_dim)
self.scl = SupConLoss()
self.fc_layers = torch.nn.ModuleList()
layers = [self.latent_dim, self.latent_dim//2, self.latent_dim//4, 1]
for idx, (in_size, out_size) in enumerate(zip(layers[:-1], layers[1:])):
self.fc_layers.append(torch.nn.Linear(in_size, out_size))
if self.config['pretrain'] == 0:
# nn.init.xavier_uniform_(self.embedding_user.weight, gain=1)
# nn.init.xavier_uniform_(self.embedding_item.weight, gain=1)
# world.cprint('use xavier initilizer')
# random normal init seems to be a better choice when lightGCN actually don't use any non-linear activation function
nn.init.normal_(self.embedding_user.weight, std=0.1)
nn.init.normal_(self.embedding_item.weight, std=0.1)
world.cprint('use NORMAL distribution initilizer')
else:
self.embedding_user.weight.data.copy_(torch.from_numpy(self.config['user_emb']))
self.embedding_item.weight.data.copy_(torch.from_numpy(self.config['item_emb']))
print('use pretarined data')
self.f = nn.Sigmoid()
self.criterion = nn.CrossEntropyLoss(reduction="mean")
self.Graph = self.dataset.getSparseGraph()
print(f"lgn is already to go(dropout:{self.config['dropout']})")
# print("save_txt")
def __dropout_x(self, x, keep_prob):
size = x.size()
index = x.indices().t()
values = x.values()
random_index = torch.rand(len(values)) + keep_prob
random_index = random_index.int().bool()
index = index[random_index]
values = values[random_index]/keep_prob
g = torch.sparse.FloatTensor(index.t(), values, size)
return g
def __dropout(self, keep_prob):
if self.A_split:
graph = []
for g in self.Graph:
graph.append(self.__dropout_x(g, keep_prob))
else:
graph = self.__dropout_x(self.Graph, keep_prob)
return graph
def computer(self):
"""
propagate methods for lightGCN
"""
users_emb = self.embedding_user.weight
items_emb = self.embedding_item.weight
all_emb = torch.cat([users_emb, items_emb])
# torch.split(all_emb , [self.num_users, self.num_items])
embs = [all_emb]
if self.config['dropout']:
if self.training:
# print("droping")
g_droped = self.__dropout(self.keep_prob)
else:
g_droped = self.Graph
else:
g_droped = self.Graph
for layer in range(self.n_layers):
if self.A_split:
temp_emb = []
for f in range(len(g_droped)):
temp_emb.append(torch.sparse.mm(g_droped[f], all_emb))
side_emb = torch.cat(temp_emb, dim=0)
all_emb = side_emb
else:
all_emb = torch.sparse.mm(g_droped, all_emb)
embs.append(all_emb)
embs = torch.stack(embs, dim=1)
light_out = torch.mean(embs, dim=1)
# light_out = embs[:,-1,:]
# light_out = torch.cat(embs, dim=1)
users, items = torch.split(light_out, [self.num_users, self.num_items])
return users, items
def getUsersRating(self, users):
all_users, all_items = self.computer()
users_emb = all_users[users.long()]
items_emb = all_items
rating = self.f(torch.matmul(users_emb, items_emb.t()))
return rating
def getEmbedding(self, users, pos_items, neg_items):
all_users, all_items = self.computer()
users_emb = all_users[users]
pos_emb = all_items[pos_items]
neg_emb = all_items[neg_items]
users_emb_ego = self.embedding_user(users)
pos_emb_ego = self.embedding_item(pos_items)
neg_emb_ego = self.embedding_item(neg_items)
return users_emb, pos_emb, neg_emb, users_emb_ego, pos_emb_ego, neg_emb_ego
def bpr_loss(self, users, pos, neg):
(users_emb, pos_emb, neg_emb,
userEmb0, posEmb0, negEmb0) = self.getEmbedding(users.long(), pos.long(), neg.long())
(_, pos_emb1, _,
userEmb1, _, _) = self.getEmbedding(users.long(), pos.long(), neg.long())
reg_loss = (1/2)*(userEmb0.norm(2).pow(2) +
posEmb0.norm(2).pow(2) +
negEmb0.norm(2).pow(2))/float(len(users))
pos_scores = torch.mul(users_emb, pos_emb)
pos_scores = torch.sum(pos_scores, dim=1)
neg_scores = torch.mul(users_emb, neg_emb)
neg_scores = torch.sum(neg_scores, dim=1)
# embs = torch.stack([pos_emb, pos_emb1], dim=1)
sceloss = self.SCE(userEmb0, userEmb1)
loss = torch.mean(torch.nn.functional.softplus(neg_scores - pos_scores)) #+ sceloss * 0.01
return loss, reg_loss
def SCE(self, z_i, z_j):
logits = torch.matmul(z_i, z_j.T) / 0.2
size = z_i.shape[0]
labels = torch.arange(0, size).to('cuda:0').long()
loss = self.criterion(logits, labels)
return loss
def CCL(self, pos_logits, neg_logits, _margin=0.8):
"""
:param y_pred: prdicted values of shape (batch_size, 1 + num_negs)
:param y_true: true labels of shape (batch_size, 1 + num_negs)
"""
pos_loss = torch.relu(1 - pos_logits)
neg_loss = torch.relu(neg_logits - _margin)
loss = pos_loss + neg_loss * 100
return loss.mean()
# def bpr_loss(self, users, pos, neg):
# (users_emb, pos_emb, neg_emb,
# userEmb0, posEmb0, negEmb0) = self.getEmbedding(users.long(), pos.long(), neg.long())
# users_emb = F.normalize(users_emb)
# pos_emb = F.normalize(pos_emb)
# neg_emb = F.normalize(neg_emb)
# pos_scores= torch.sum(users_emb*pos_emb, dim=1)
# neg_scores= torch.sum(users_emb*neg_emb, dim=1)
# loss = self.CCL(pos_scores, neg_scores)#torch.mean((1 - pos_scores) + neg_scores * 100)
# # sceloss = self.SCE(users_emb/, pos_emb)
# loss += torch.mean(nn.functional.softplus((neg_scores - pos_scores)/0.1)) ##+ sceloss
# # loss += sceloss
# reg_loss = (1/2)*(userEmb0.norm(2).pow(2) +
# posEmb0.norm(2).pow(2) +
# negEmb0.norm(2).pow(2))/float(len(users))
# return loss, reg_loss
def forward(self, users, items):
# compute embedding
all_users, all_items = self.computer()
# print('forward')
#all_users, all_items = self.computer()
users_emb = all_users[users]
items_emb = all_items[items]
inner_pro = torch.mul(users_emb, items_emb)
gamma = torch.sum(inner_pro, dim=1)
return gamma
def xmrec_test(self, users, items):
# compute embedding
all_users, all_items = self.computer()
# print('forward')
#all_users, all_items = self.computer()
users_emb = all_users[users]
items_emb = all_items[items]
# users_emb = F.normalize(users_emb)
# items_emb = F.normalize(items_emb)
inner_pro = torch.mul(users_emb, items_emb)
gamma = torch.sum(inner_pro, dim=1)
return gamma, users_emb, items_emb