/
evaluator.py
341 lines (274 loc) · 13.2 KB
/
evaluator.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module is for evaluating the results
"""
import os
import timeit
import torch
import numpy as np
import pandas as pd
from pykg2vec.utils.logger import Logger
from tqdm import tqdm
class MetricCalculator:
'''
MetricCalculator aims to
1) address all the statistic tasks.
2) provide interfaces for querying results.
MetricCalculator is expected to be used by "evaluation_process".
'''
_logger = Logger().get_logger(__name__)
def __init__(self, config):
self.config = config
self.hr_t = config.knowledge_graph.read_cache_data('hr_t')
self.tr_h = config.knowledge_graph.read_cache_data('tr_h')
# (f)mr : (filtered) mean rank
# (f)mrr : (filtered) mean reciprocal rank
# (f)hit : (filtered) hit-k ratio
self.mr = {}
self.fmr = {}
self.mrr = {}
self.fmrr = {}
self.hit = {}
self.fhit = {}
self.epoch = None
self.reset()
def reset(self):
# temporarily used buffers and indexes.
self.rank_head = []
self.rank_tail = []
self.f_rank_head = []
self.f_rank_tail = []
self.epoch = None
self.start_time = timeit.default_timer()
def append_result(self, result):
predict_tail = result[0]
predict_head = result[1]
h, r, t = result[2], result[3], result[4]
self.epoch = result[5]
t_rank, f_t_rank = self.get_tail_rank(predict_tail, h, r, t)
h_rank, f_h_rank = self.get_head_rank(predict_head, h, r, t)
self.rank_head.append(h_rank)
self.rank_tail.append(t_rank)
self.f_rank_head.append(f_h_rank)
self.f_rank_tail.append(f_t_rank)
def get_tail_rank(self, tail_candidate, h, r, t):
"""Function to evaluate the tail rank.
Args:
id_replace_tail (list): List of the predicted tails for the given head, relation pair
h (int): head id
r (int): relation id
t (int): tail id
hr_t (dict): list of tails for the given hwS and relation pari.
Returns:
Tensors: Returns tail rank and filetered tail rank
"""
trank = 0
ftrank = 0
for j in range(len(tail_candidate)):
val = tail_candidate[-j - 1]
if val != t:
trank += 1
ftrank += 1
if val in self.hr_t[(h, r)]:
ftrank -= 1
else:
break
return trank, ftrank
def get_head_rank(self, head_candidate, h, r, t):
"""Function to evaluate the head rank.
Args:
head_candidate (list): List of the predicted head for the given tail, relation pair
h (int): head id
r (int): relation id
t (int): tail id
Returns:
Tensors: Returns head rank and filetered head rank
"""
hrank = 0
fhrank = 0
for j in range(len(head_candidate)):
val = head_candidate[-j - 1]
if val != h:
hrank += 1
fhrank += 1
if val in self.tr_h[(t, r)]:
fhrank -= 1
else:
break
return hrank, fhrank
def settle(self):
head_ranks = np.asarray(self.rank_head, dtype=np.float32)+1
tail_ranks = np.asarray(self.rank_tail, dtype=np.float32)+1
head_franks = np.asarray(self.f_rank_head, dtype=np.float32)+1
tail_franks = np.asarray(self.f_rank_tail, dtype=np.float32)+1
ranks = np.concatenate((head_ranks, tail_ranks))
franks = np.concatenate((head_franks, tail_franks))
self.mr[self.epoch] = np.mean(ranks)
self.mrr[self.epoch] = np.mean(np.reciprocal(ranks))
self.fmr[self.epoch] = np.mean(franks)
self.fmrr[self.epoch] = np.mean(np.reciprocal(franks))
for hit in self.config.hits:
self.hit[(self.epoch, hit)] = np.mean(ranks <= hit, dtype=np.float32)
self.fhit[(self.epoch, hit)] = np.mean(franks <= hit, dtype=np.float32)
def get_curr_scores(self):
scores = {'mr': self.mr[self.epoch],
'fmr':self.fmr[self.epoch],
'mrr':self.mrr[self.epoch],
'fmrr':self.fmrr[self.epoch]}
return scores
def save_test_summary(self, model_name):
"""Function to save the test of the summary.
Args:
model_name (str): specify the name of the model.
"""
files = os.listdir(str(self.config.path_result))
l = len([f for f in files if model_name in f if 'Testing' in f])
with open(str(self.config.path_result / (model_name + '_summary_' + str(l) + '.txt')), 'w') as fh:
fh.write('----------------SUMMARY----------------\n')
for key, val in self.config.__dict__.items():
if 'gpu' in key:
continue
if 'knowledge_graph' in key:
continue
if not isinstance(val, str):
if isinstance(val, list):
v_tmp = '['
for i, v in enumerate(val):
if i == 0:
v_tmp += str(v)
else:
v_tmp += ',' + str(v)
v_tmp += ']'
val = v_tmp
else:
val = str(val)
fh.write(key + ':' + val + '\n')
fh.write('-----------------------------------------\n')
fh.write("\n----------Metadata Info for Dataset:%s----------------" % self.config.knowledge_graph.dataset_name)
fh.write("Total Training Triples :%d\n"%self.config.tot_train_triples)
fh.write("Total Testing Triples :%d\n"%self.config.tot_test_triples)
fh.write("Total validation Triples :%d\n"%self.config.tot_valid_triples)
fh.write("Total Entities :%d\n"%self.config.tot_entity)
fh.write("Total Relations :%d\n"%self.config.tot_relation)
fh.write("---------------------------------------------")
columns = ['Epoch', 'Mean Rank', 'Filtered Mean Rank', 'Mean Reciprocal Rank', 'Filtered Mean Reciprocal Rank']
for hit in self.config.hits:
columns += ['Hit-%d Ratio'%hit, 'Filtered Hit-%d Ratio'%hit]
results = []
for epoch, _ in self.mr.items():
res_tmp = [epoch, self.mr[epoch], self.fmr[epoch], self.mrr[epoch], self.fmrr[epoch]]
for hit in self.config.hits:
res_tmp.append(self.hit[(epoch, hit)])
res_tmp.append(self.fhit[(epoch, hit)])
results.append(res_tmp)
df = pd.DataFrame(results, columns=columns)
with open(str(self.config.path_result / (model_name + '_Testing_results_' + str(l) + '.csv')), 'a') as fh:
df.to_csv(fh)
def display_summary(self):
"""Function to print the test summary."""
stop_time = timeit.default_timer()
test_results = []
test_results.append('')
test_results.append("------Test Results for %s: Epoch: %d --- time: %.2f------------" % (self.config.dataset_name, self.epoch, stop_time - self.start_time))
test_results.append('--# of entities, # of relations: %d, %d'%(self.config.tot_entity, self.config.tot_relation))
test_results.append('--mr, filtered mr : %.4f, %.4f'%(self.mr[self.epoch], self.fmr[self.epoch]))
test_results.append('--mrr, filtered mrr : %.4f, %.4f'%(self.mrr[self.epoch], self.fmrr[self.epoch]))
for hit in self.config.hits:
test_results.append('--hits%d : %.4f ' % (hit, (self.hit[(self.epoch, hit)])))
test_results.append('--filtered hits%d : %.4f ' % (hit, (self.fhit[(self.epoch, hit)])))
test_results.append("---------------------------------------------------------")
test_results.append('')
self._logger.info("\n".join(test_results))
class Evaluator:
"""Class to perform evaluation of the model.
Args:
model (object): Model object
tuning (bool): Flag to denoting tuning if True
Examples:
>>> from pykg2vec.utils.evaluator import Evaluator
>>> evaluator = Evaluator(model=model, tuning=True)
>>> evaluator.test_batch(Session(), 0)
>>> acc = evaluator.output_queue.get()
>>> evaluator.stop()
"""
_logger = Logger().get_logger(__name__)
def __init__(self, model, config, tuning=False):
self.model = model
self.config = config
self.tuning = tuning
self.test_data = self.config.knowledge_graph.read_cache_data('triplets_test')
self.eval_data = self.config.knowledge_graph.read_cache_data('triplets_valid')
self.metric_calculator = MetricCalculator(self.config)
def test_tail_rank(self, h, r, topk=-1):
if hasattr(self.model, 'predict_tail_rank'):
# TODO: this broke training on ProjE_pointwise
# h = h.unsqueeze(0).to(self.config.device)
# r = r.unsqueeze(0).to(self.config.device)
rank = self.model.predict_tail_rank(h, r, topk=topk)
return rank.squeeze(0)
h_batch = torch.LongTensor([h]).repeat([self.config.tot_entity]).to(self.config.device)
r_batch = torch.LongTensor([r]).repeat([self.config.tot_entity]).to(self.config.device)
entity_array = torch.LongTensor(list(range(self.config.tot_entity))).to(self.config.device)
preds = self.model.forward(h_batch, r_batch, entity_array)
_, rank = torch.topk(preds, k=topk)
return rank
def test_head_rank(self, r, t, topk=-1):
if hasattr(self.model, 'predict_head_rank'):
# TODO: this broke training on ProjE_pointwise
# t = t.unsqueeze(0).to(self.config.device)
# r = r.unsqueeze(0).to(self.config.device)
rank = self.model.predict_head_rank(t, r, topk=topk)
return rank.squeeze(0)
entity_array = torch.LongTensor(list(range(self.config.tot_entity))).to(self.config.device)
r_batch = torch.LongTensor([r]).repeat([self.config.tot_entity]).to(self.config.device)
t_batch = torch.LongTensor([t]).repeat([self.config.tot_entity]).to(self.config.device)
preds = self.model.forward(entity_array, r_batch, t_batch)
_, rank = torch.topk(preds, k=topk)
return rank
def test_rel_rank(self, h, t, topk=-1):
if hasattr(self.model, 'predict_rel_rank'):
# TODO: this broke training on ProjE_pointwise
# h = h.unsqueeze(0).to(self.config.device)
# t = t.unsqueeze(0).to(self.config.device)
rank = self.model.predict_rel_rank(h, t, topk=topk)
return rank.squeeze(0)
h_batch = torch.LongTensor([h]).repeat([self.config.tot_relation]).to(self.config.device)
rel_array = torch.LongTensor(list(range(self.config.tot_relation))).to(self.config.device)
t_batch = torch.LongTensor([t]).repeat([self.config.tot_relation]).to(self.config.device)
preds = self.model.forward(h_batch, rel_array, t_batch)
_, rank = torch.topk(preds, k=topk)
return rank
def mini_test(self, epoch=None):
if self.config.test_num == 0:
tot_valid_to_test = len(self.eval_data)
else:
tot_valid_to_test = min(self.config.test_num, len(self.eval_data))
if self.config.debug:
tot_valid_to_test = 10
self._logger.info("Mini-Testing on [%d/%d] Triples in the valid set." % (tot_valid_to_test, len(self.eval_data)))
return self.test(self.eval_data, tot_valid_to_test, epoch=epoch)
def full_test(self, epoch=None):
tot_valid_to_test = len(self.test_data)
if self.config.debug:
tot_valid_to_test = 10
self._logger.info("Full-Testing on [%d/%d] Triples in the test set." % (tot_valid_to_test, len(self.test_data)))
return self.test(self.test_data, tot_valid_to_test, epoch=epoch)
def test(self, data, num_of_test, epoch=None):
self.metric_calculator.reset()
progress_bar = tqdm(range(num_of_test))
for i in progress_bar:
h, r, t = data[i].h, data[i].r, data[i].t
# generate head batch and predict heads.
h_tensor = torch.LongTensor([h]).to(self.config.device)
r_tensor = torch.LongTensor([r]).to(self.config.device)
t_tensor = torch.LongTensor([t]).to(self.config.device)
hrank = self.test_head_rank(r_tensor, t_tensor, self.config.tot_entity)
trank = self.test_tail_rank(h_tensor, r_tensor, self.config.tot_entity)
result_data = [trank.cpu().numpy(), hrank.cpu().numpy(), h, r, t, epoch]
self.metric_calculator.append_result(result_data)
self.metric_calculator.settle()
self.metric_calculator.display_summary()
if self.metric_calculator.epoch >= self.config.epochs - 1:
self.metric_calculator.save_test_summary(self.model.model_name)
return self.metric_calculator.get_curr_scores()