/
utils.py
208 lines (171 loc) · 8.23 KB
/
utils.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
import torch
import logging
import models
def get_model(model, dim, rel_model, loss_fn, num_entities, num_relations,
encoder_name, regularizer):
if model == 'raild':
return models.BertEmbeddingsLP(dim, rel_model, loss_fn, num_relations,
encoder_name, regularizer)
elif model == 'raild-node2vec-same': ### entities with bert and relations with node2vec
return models.BertNode2Vec(dim, rel_model, loss_fn, num_relations,
encoder_name, regularizer)
elif model == 'raild-combined': ### entities with bert and relations with node2vec
return models.BertCombinedLP(dim, rel_model, loss_fn, num_relations,
encoder_name, regularizer)
### entity : word-emb-pre-trained: relation : word-emb-pre-trained,
elif model == 'bert-bow':
return models.BOW(rel_model, loss_fn, num_relations, regularizer,
encoder_name=encoder_name)
elif model == 'bert-dkrl':
return models.DKRL(dim, rel_model, loss_fn, num_relations, regularizer,
encoder_name=encoder_name)
elif model == 'glove-bow':
return models.BOW(rel_model, loss_fn, num_relations, regularizer,
embeddings='glove/glove.6B.300d.pt')
elif model == 'glove-dkrl':
return models.DKRL(dim, rel_model, loss_fn, num_relations, regularizer,
embeddings='glove/glove.6B.300d.pt')
### Transductive models
#elif model == 'transductive':
#return models.TransductiveLinkPrediction(dim, rel_model, loss_fn,
#num_entities, num_relations,
#regularizer)
else:
raise ValueError(f'Unkown model {model}')
def make_ent2idx(entities, max_ent_id):
"""Given a tensor with entity IDs, return a tensor indexed with
an entity ID, containing the position of the entity.
Empty positions are filled with -1.
Example:
> make_ent2idx(torch.tensor([4, 5, 0]))
tensor([ 2, -1, -1, -1, 0, 1])
"""
idx = torch.arange(entities.shape[0])
ent2idx = torch.empty(max_ent_id + 1, dtype=torch.long).fill_(-1)
ent2idx.scatter_(0, entities, idx)
return ent2idx
def make_rel2idx(relations, max_rel_id):
"""Given a tensor with relation IDs, return a tensor indexed with
a relation ID, containing the position of the relation.
Empty positions are filled with -1.
Example:
> make_rel2idx(torch.tensor([4, 5, 0]))
tensor([ 2, -1, -1, -1, 0, 1])
"""
idx = torch.arange(relations.shape[0])
rel2idx = torch.empty(max_rel_id + 1, dtype=torch.long).fill_(-1)
rel2idx.scatter_(0, relations, idx)
return rel2idx
def get_triple_filters(triples, graph, num_ents, ent2idx):
"""Given a set of triples, filter candidate entities that are valid
substitutes of an entity in the triple at a given position (head or tail).
For a particular triple, this allows to compute rankings for an entity of
interest, against other entities in the graph that would actually be wrong
substitutes.
Results are returned as a mask array with a value of 1.0 for filtered
entities, and 0.0 otherwise.
Args:
triples: Bx3 tensor of type torch.long, where B is the batch size,
and each row contains a triple of the form (head, tail, rel)
graph: nx.MultiDiGraph containing all edges used to filter candidates
num_ents: int, number of candidate entities
ent2idx: tensor, contains at index ent_id the index of the column for
that entity in the output mask array
"""
num_triples = triples.shape[0]
heads_filter = torch.zeros((num_triples, num_ents), dtype=torch.bool)
tails_filter = torch.zeros_like(heads_filter)
triples = triples.tolist()
for i, (head, tail, rel) in enumerate(triples):
head_edges = graph.out_edges(head, data='weight')
for (h, t, r) in head_edges:
if r == rel and t != tail:
ent_idx = ent2idx[t]
if ent_idx != -1:
tails_filter[i, ent_idx] = True
tail_edges = graph.in_edges(tail, data='weight')
for (h, t, r) in tail_edges:
if r == rel and h != head:
ent_idx = ent2idx[h]
if ent_idx != -1:
heads_filter[i, ent_idx] = True
return heads_filter, tails_filter
def get_metrics(pred_scores: torch.Tensor,
true_idx: torch.Tensor,
k_values: torch.Tensor):
"""Calculates mean number of hits@k. Higher values are ranked first.
Args:
pred_scores: (B, N) tensor of prediction values where B is batch size
and N number of classes.
ground_truth_idx: (B, 1) tensor with index of ground truth class
k_values: (1, k) tensor containing number of top-k results to be
considered as hits.
Returns:
reciprocals: (B, 1) tensor containing reciprocals of the ranks
hits: (B, k) tensor containing the number of hits for each value of k
"""
# Based on PyKEEN's implementation
true_scores = pred_scores.gather(dim=1, index=true_idx)
best_rank = (pred_scores > true_scores).sum(dim=1, keepdim=True) + 1
worst_rank = (pred_scores >= true_scores).sum(dim=1, keepdim=True)
average_rank = (best_rank + worst_rank).float() * 0.5
reciprocals = average_rank.reciprocal()
hits = average_rank <= k_values
return reciprocals, hits
def split_by_new_position(triples, mrr_values, new_entities):
"""Split MRR results by the position of new entity. Use to break down
results for a triple where a new entity is at the head and the tail,
at the head only, or the tail only.
Since MRR is calculated by corrupting the head first, and then the head,
the size of mrr_values should be twice the size of triples. The calculated
MRR is then the average of the two cases.
Args:
triples: Bx3 tensor containing (head, tail, rel).
mrr_values: 2B tensor, with first half containing MRR for corrupted
triples at the head position, and second half at the tail position.
new_entities: set, entities to be considered as new.
Returns:
mrr_by_position: tensor of 3 elements breaking down MRR by new entities
at both positions, at head, and tail.
mrr_pos_counts: tensor of 3 elements containing counts for each case.
"""
mrr_by_position = torch.zeros(3, device=mrr_values.device)
mrr_pos_counts = torch.zeros_like(mrr_by_position)
num_triples = triples.shape[0]
for i, (h, t, r) in enumerate(triples):
head, tail = h.item(), t.item()
mrr_val = (mrr_values[i] + mrr_values[i + num_triples]).item() / 2.0
if head in new_entities and tail in new_entities:
mrr_by_position[0] += mrr_val
mrr_pos_counts[0] += 1.0
elif head in new_entities:
mrr_by_position[1] += mrr_val
mrr_pos_counts[1] += 1.0
elif tail in new_entities:
mrr_by_position[2] += mrr_val
mrr_pos_counts[2] += 1.0
return mrr_by_position, mrr_pos_counts
def split_by_category(triples, mrr_values, rel_categories):
mrr_by_category = torch.zeros([2, 4], device=mrr_values.device)
mrr_cat_count = torch.zeros([1, 4], dtype=torch.float,
device=mrr_by_category.device)
num_triples = triples.shape[0]
for i, (h, t, r) in enumerate(triples):
rel_category = rel_categories[r]
mrr_val_head_pred = mrr_values[i]
mrr_by_category[0, rel_category] += mrr_val_head_pred
mrr_val_tail_pred = mrr_values[i + num_triples]
mrr_by_category[1, rel_category] += mrr_val_tail_pred
mrr_cat_count[0, rel_category] += 1
return mrr_by_category, mrr_cat_count
def get_logger():
"""Get a default logger that includes a timestamp."""
logger = logging.getLogger("")
logger.handlers = []
ch = logging.StreamHandler()
str_fmt = '%(asctime)s - %(levelname)s - %(name)s - %(message)s'
formatter = logging.Formatter(str_fmt, datefmt='%H:%M:%S')
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.setLevel('INFO')
return logger