/
evaluate.py
184 lines (135 loc) · 5.35 KB
/
evaluate.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
import numpy as np
import torch
from utils import getLabel
from metrics import RecallPrecision_ATk, NDCGatK_r
def getUserPosItems(allPos, users):
if isinstance(users, int):
users = [users]
posItems = []
for user in users:
posItems.append(allPos[user])
return posItems
def test_one_batch(Ks, X):
sorted_items = X[0].numpy()
groundTrue = X[1]
r = getLabel(groundTrue, sorted_items)
pre, recall, ndcg = [], [], []
for k in Ks:
ret = RecallPrecision_ATk(groundTrue, r, k)
pre.append(ret['precision'])
recall.append(ret['recall'])
ndcg.append(NDCGatK_r(groundTrue, r, k))
return {'precision': np.array(pre),
'recall': np.array(recall),
'ndcg': np.array(ndcg)}
def test_all_users(model, batch_size, test_data_pos, user_pos, top_k, device='cuda'):
model.eval()
model.to(device)
max_K = max(top_k)
result = {'precision': np.zeros(len(top_k)),
'recall': np.zeros(len(top_k)),
'ndcg': np.zeros(len(top_k))}
test_users = np.array(list(test_data_pos.keys()))
ground_true_items = list(test_data_pos.values())
n_test = len(test_users)
try:
assert batch_size <= n_test / 10
except AssertionError:
print(f"test_batch_size is too big for this dataset, try a small one {n_test // 10}")
batch_size = n_test // 10
n_batchs = n_test // batch_size + 1
rating_list = []
groundTrue_list = []
with torch.no_grad():
for u_batch_id in range(n_batchs):
start = u_batch_id * batch_size
end = (u_batch_id + 1) * batch_size
user_batch = test_users[start: end]
if len(user_batch) == 0:
continue
allPos = getUserPosItems(user_pos, user_batch)
groundTrue = ground_true_items[start: end]
batch_users_gpu = torch.Tensor(user_batch).long()
batch_users_gpu = batch_users_gpu.to(device)
rating = model.getUsersRating(batch_users_gpu)
exclude_index = []
exclude_items = []
for range_i, items in enumerate(allPos):
if len(items) == 0:
continue
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_list.append(rating_K.cpu())
groundTrue_list.append(groundTrue)
X = zip(rating_list, groundTrue_list)
pre_results = []
for x in X:
pre_results.append(test_one_batch(top_k, x))
for re in pre_results:
result['recall'] += re['recall']
result['ndcg'] += re['ndcg']
result['recall'] /= float(n_test)
result['ndcg'] /= float(n_test)
recall = result['recall']
NDCG = result['ndcg']
return recall, NDCG
def test_all_users_with_two_model(model, h_model, batch_size, test_data_pos, user_pos, top_k,
device='cuda', beta1=1.0, beta2=1.0):
model.eval()
model.to(device)
h_model.eval()
h_model.to(device)
max_K = max(top_k)
result = {'precision': np.zeros(len(top_k)),
'recall': np.zeros(len(top_k)),
'ndcg': np.zeros(len(top_k))}
test_users = np.array(list(test_data_pos.keys()))
ground_true_items = list(test_data_pos.values())
n_test = len(test_users)
try:
assert batch_size <= n_test / 10
except AssertionError:
print(f"test_batch_size is too big for this dataset, try a small one {n_test // 10}")
batch_size = n_test // 10
n_batchs = n_test // batch_size + 1
rating_list = []
groundTrue_list = []
with torch.no_grad():
for u_batch_id in range(n_batchs):
start = u_batch_id * batch_size
end = (u_batch_id + 1) * batch_size
user_batch = test_users[start: end]
if len(user_batch) == 0:
continue
allPos = getUserPosItems(user_pos, user_batch)
groundTrue = ground_true_items[start: end]
batch_users_gpu = torch.Tensor(user_batch).long()
batch_users_gpu = batch_users_gpu.to(device)
rating = model.getUsersRating(batch_users_gpu)
rating_h = h_model.getUsersRating(batch_users_gpu)
rating = beta1 * rating + beta2 * rating_h
exclude_index = []
exclude_items = []
for range_i, items in enumerate(allPos):
if len(items) == 0:
continue
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_list.append(rating_K.cpu())
groundTrue_list.append(groundTrue)
X = zip(rating_list, groundTrue_list)
pre_results = []
for x in X:
pre_results.append(test_one_batch(top_k, x))
for re in pre_results:
result['recall'] += re['recall']
result['ndcg'] += re['ndcg']
result['recall'] /= float(n_test)
result['ndcg'] /= float(n_test)
recall = result['recall']
NDCG = result['ndcg']
return recall, NDCG