-
Notifications
You must be signed in to change notification settings - Fork 4
/
Procedure.py
312 lines (264 loc) · 11.4 KB
/
Procedure.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
'''
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])
Design training and test process
'''
import world
import numpy as np
import torch
from torch import nn
import utils
import dataloader
from pprint import pprint
from utils import timer
from time import time
from tqdm import tqdm
import model
import multiprocessing
from sklearn.metrics import roc_auc_score
CORES = multiprocessing.cpu_count() // 2
def BPR_train_original(dataset, recommend_model, loss_class, epoch, neg_k=1, w=None):
Recmodel = recommend_model
Recmodel.train()
bpr: utils.BPRLoss = loss_class
with timer(name="Sample"):
S = utils.UniformSample_original(dataset)
users = torch.Tensor(S[:, 0]).long()
posItems = torch.Tensor(S[:, 1]).long()
negItems = torch.Tensor(S[:, 2]).long()
users = users.to(world.device)
posItems = posItems.to(world.device)
negItems = negItems.to(world.device)
users, posItems, negItems = utils.shuffle(users, posItems, negItems)
total_batch = len(users) // world.config['bpr_batch_size'] + 1
aver_loss = 0.
for (batch_i,
(batch_users,
batch_pos,
batch_neg)) in enumerate(utils.minibatch(users,
posItems,
negItems,
batch_size=world.config['bpr_batch_size'])):
cri = bpr.stageOne(batch_users, batch_pos, batch_neg)
aver_loss += cri
if world.tensorboard:
w.add_scalar(f'BPRLoss/BPR', cri, epoch * int(len(users) / world.config['bpr_batch_size']) + batch_i)
aver_loss = aver_loss / total_batch
time_info = timer.dict()
timer.zero()
return f"loss{aver_loss:.3f}-{time_info}"
def test_one_batch(X):
sorted_items = X[0].numpy()
groundTrue = X[1]
r = utils.getLabel(groundTrue, sorted_items)
pre, recall, ndcg = [], [], []
for k in world.topks:
ret = utils.RecallPrecision_ATk(groundTrue, r, k)
pre.append(ret['precision'])
recall.append(ret['recall'])
ndcg.append(utils.NDCGatK_r(groundTrue,r,k))
return {'recall':np.array(recall),
'precision':np.array(pre),
'ndcg':np.array(ndcg)}
def Test(dataset, Recmodel, epoch, w=None, multicore=0):
u_batch_size = world.config['test_u_batch_size']
dataset: utils.BasicDataset
testDict: dict = dataset.testDict
Recmodel: model.LightGCN
# eval mode with no dropout
Recmodel = Recmodel.eval()
max_K = max(world.topks)
if multicore == 1:
pool = multiprocessing.Pool(CORES)
results = {'precision': np.zeros(len(world.topks)),
'recall': np.zeros(len(world.topks)),
'ndcg': np.zeros(len(world.topks))}
with torch.no_grad():
users = list(testDict.keys())
try:
assert u_batch_size <= len(users) / 10
except AssertionError:
print(f"test_u_batch_size is too big for this dataset, try a small one {len(users) // 10}")
users_list = []
rating_list = []
groundTrue_list = []
total_batch = len(users) // u_batch_size + 1
for batch_users in utils.minibatch(users, batch_size=u_batch_size):
allPos = dataset.getUserPosItems(batch_users)
groundTrue = [testDict[u] for u in batch_users]
batch_users_gpu = torch.Tensor(batch_users).long()
batch_users_gpu = batch_users_gpu.to(world.device)
rating = Recmodel.getUsersRating(batch_users_gpu)
exclude_index = []
exclude_items = []
for range_i, items in enumerate(allPos):
exclude_index.extend([range_i] * len(items))
exclude_items.extend(items)
rating[exclude_index, exclude_items] = -(1<<10)
_, rating_K = torch.topk(rating, k=max_K)
rating = rating.cpu().numpy()
del rating
users_list.append(batch_users)
rating_list.append(rating_K.cpu())
groundTrue_list.append(groundTrue)
assert total_batch == len(users_list)
X = zip(rating_list, groundTrue_list)
if multicore == 1:
pre_results = pool.map(test_one_batch, X)
else:
pre_results = []
for x in X:
pre_results.append(test_one_batch(x))
scale = float(u_batch_size/len(users))
for result in pre_results:
results['recall'] += result['recall']
results['precision'] += result['precision']
results['ndcg'] += result['ndcg']
results['recall'] /= float(len(users))
results['precision'] /= float(len(users))
results['ndcg'] /= float(len(users))
# results['auc'] = np.mean(auc_record)
if world.tensorboard:
w.add_scalars(f'Test/Recall@{world.topks}',
{str(world.topks[i]): results['recall'][i] for i in range(len(world.topks))}, epoch)
w.add_scalars(f'Test/Precision@{world.topks}',
{str(world.topks[i]): results['precision'][i] for i in range(len(world.topks))}, epoch)
w.add_scalars(f'Test/NDCG@{world.topks}',
{str(world.topks[i]): results['ndcg'][i] for i in range(len(world.topks))}, epoch)
if multicore == 1:
pool.close()
print(results)
return results
def Valid(dataset, Recmodel, epoch, w=None, multicore=0):
u_batch_size = world.config['test_u_batch_size']
dataset: utils.BasicDataset
validDict: dict = dataset.validDict
Recmodel: model.LightGCN
# eval mode with no dropout
Recmodel = Recmodel.eval()
max_K = max(world.topks)
if multicore == 1:
pool = multiprocessing.Pool(CORES)
results = {'precision': np.zeros(len(world.topks)),
'recall': np.zeros(len(world.topks)),
'ndcg': np.zeros(len(world.topks))}
with torch.no_grad():
users = list(validDict.keys())
try:
assert u_batch_size <= len(users) / 10
except AssertionError:
print(f"test_u_batch_size is too big for this dataset, try a small one {len(users) // 10}")
users_list = []
rating_list = []
groundTrue_list = []
total_batch = len(users) // u_batch_size + 1
for batch_users in utils.minibatch(users, batch_size=u_batch_size):
allPos = dataset.getUserPosItems(batch_users)
groundTrue = [validDict[u] for u in batch_users]
batch_users_gpu = torch.Tensor(batch_users).long()
batch_users_gpu = batch_users_gpu.to(world.device)
rating = Recmodel.getUsersRating(batch_users_gpu)
exclude_index = []
exclude_items = []
for range_i, items in enumerate(allPos):
exclude_index.extend([range_i] * len(items))
exclude_items.extend(items)
rating[exclude_index, exclude_items] = -(1<<10)
_, rating_K = torch.topk(rating, k=max_K)
rating = rating.cpu().numpy()
del rating
users_list.append(batch_users)
rating_list.append(rating_K.cpu())
groundTrue_list.append(groundTrue)
assert total_batch == len(users_list)
X = zip(rating_list, groundTrue_list)
if multicore == 1:
pre_results = pool.map(test_one_batch, X)
else:
pre_results = []
for x in X:
pre_results.append(test_one_batch(x))
scale = float(u_batch_size/len(users))
for result in pre_results:
results['recall'] += result['recall']
results['precision'] += result['precision']
results['ndcg'] += result['ndcg']
results['recall'] /= float(len(users))
results['precision'] /= float(len(users))
results['ndcg'] /= float(len(users))
# results['auc'] = np.mean(auc_record)
if world.tensorboard:
w.add_scalars(f'Valid/Recall@{world.topks}',
{str(world.topks[i]): results['recall'][i] for i in range(len(world.topks))}, epoch)
w.add_scalars(f'Valid/Precision@{world.topks}',
{str(world.topks[i]): results['precision'][i] for i in range(len(world.topks))}, epoch)
w.add_scalars(f'Valid/NDCG@{world.topks}',
{str(world.topks[i]): results['ndcg'][i] for i in range(len(world.topks))}, epoch)
if multicore == 1:
pool.close()
print(results)
return results
def getUsersRating(users, all_users, all_items):
users_emb = all_users[users.long()]
items_emb = all_items
rating = nn.Sigmoid()(torch.matmul(users_emb, items_emb.t()))
return rating
def Test_Offline(dataset, all_users, all_items, w=None, multicore=0):
u_batch_size = world.config['test_u_batch_size']
dataset: utils.BasicDataset
testDict: dict = dataset.testDict
max_K = max(world.topks)
if multicore == 1:
pool = multiprocessing.Pool(CORES)
results = {'precision': np.zeros(len(world.topks)),
'recall': np.zeros(len(world.topks)),
'ndcg': np.zeros(len(world.topks))}
with torch.no_grad():
users = list(testDict.keys())
try:
assert u_batch_size <= len(users) / 10
except AssertionError:
print(f"test_u_batch_size is too big for this dataset, try a small one {len(users) // 10}")
users_list = []
rating_list = []
groundTrue_list = []
total_batch = len(users) // u_batch_size + 1
for batch_users in utils.minibatch(users, batch_size=u_batch_size):
allPos = dataset.getUserPosItems(batch_users)
groundTrue = [testDict[u] for u in batch_users]
batch_users_gpu = torch.Tensor(batch_users).long()
batch_users_gpu = batch_users_gpu.to(world.device)
rating = getUsersRating(batch_users_gpu, all_users, all_items)
exclude_index = []
exclude_items = []
for range_i, items in enumerate(allPos):
exclude_index.extend([range_i] * len(items))
exclude_items.extend(items)
rating[exclude_index, exclude_items] = -(1<<10)
_, rating_K = torch.topk(rating, k=max_K)
rating = rating.cpu().numpy()
del rating
users_list.append(batch_users)
rating_list.append(rating_K.cpu())
groundTrue_list.append(groundTrue)
assert total_batch == len(users_list)
X = zip(rating_list, groundTrue_list)
if multicore == 1:
pre_results = pool.map(test_one_batch, X)
else:
pre_results = []
for x in X:
pre_results.append(test_one_batch(x))
scale = float(u_batch_size/len(users))
for result in pre_results:
results['recall'] += result['recall']
results['precision'] += result['precision']
results['ndcg'] += result['ndcg']
results['recall'] /= float(len(users))
results['precision'] /= float(len(users))
results['ndcg'] /= float(len(users))
if multicore == 1:
pool.close()
return results