-
Notifications
You must be signed in to change notification settings - Fork 9
/
eval_lib.py
62 lines (53 loc) · 1.79 KB
/
eval_lib.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
import torch
import torch.autograd as autograd
USE_CUDA = torch.cuda.is_available()
if USE_CUDA:
longTensor = torch.cuda.LongTensor
floatTensor = torch.cuda.FloatTensor
else:
longTensor = torch.LongTensor
floatTensor = torch.FloatTensor
def isHit10(triple, tree, cal_embedding, tripleDict, isTail):
# If isTail == True, evaluate the prediction of tail entity
if isTail == True:
k = 0
wrongCount = 0
while wrongCount < 10:
k += 15
tail_dist, tail_ind = tree.query(cal_embedding, k=k)
for elem in tail_ind[0][k - 15: k]:
if triple.t == elem:
return True
elif (triple.h, elem, triple.r) in tripleDict:
continue
else:
wrongCount += 1
if wrongCount > 9:
return False
# If isTail == False, evaluate the prediction of head entity
else:
k = 0
wrongCount = 0
while wrongCount < 10:
k += 15
head_dist, head_ind = tree.query(cal_embedding, k=k)
for elem in head_ind[0][k - 15: k]:
if triple.h == elem:
return True
elif (elem, triple.t, triple.r) in tripleDict:
continue
else:
wrongCount += 1
if wrongCount > 9:
return False
def pairwise_L1_distances(A, B):
dist = torch.sum(torch.abs(A.unsqueeze(1) - B.unsqueeze(0)), dim=2)
return dist
def pairwise_L2_distances(A, B):
AA = torch.sum(A ** 2, dim=1).unsqueeze(1)
BB = torch.sum(B ** 2, dim=1).unsqueeze(0)
dist = torch.mm(A, torch.transpose(B, 0, 1))
dist *= -2
dist += AA
dist += BB
return dist