KGATE 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kgate/__init__.py +3 -0
- kgate/config_template.toml +83 -0
- kgate/data_structures.py +607 -0
- kgate/decoders/__init__.py +2 -0
- kgate/decoders/bilinear.py +126 -0
- kgate/decoders/translational.py +291 -0
- kgate/encoders.py +51 -0
- kgate/evaluators.py +277 -0
- kgate/inference.py +163 -0
- kgate/kgate.py +859 -0
- kgate/preprocessing.py +379 -0
- kgate/samplers.py +89 -0
- kgate/utils.py +326 -0
- kgate-0.1.0.dist-info/LICENSE +7 -0
- kgate-0.1.0.dist-info/METADATA +67 -0
- kgate-0.1.0.dist-info/RECORD +17 -0
- kgate-0.1.0.dist-info/WHEEL +4 -0
kgate/__init__.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
seed = 42
|
|
2
|
+
|
|
3
|
+
# Path to the KG in CSV format with at least columns named from, to and rel
|
|
4
|
+
kg_csv = ""
|
|
5
|
+
# Path to the KG in pickle format. If both csv and pkl are set, the pickle will have priority.
|
|
6
|
+
kg_pkl = ""
|
|
7
|
+
|
|
8
|
+
# Path to the CSV mapping entities to their metadata, with at least columns id (must be the same as the KG id) and type
|
|
9
|
+
metadata_csv = ""
|
|
10
|
+
|
|
11
|
+
# Path to the analysis output directory
|
|
12
|
+
output_directory = ""
|
|
13
|
+
|
|
14
|
+
verbose = true
|
|
15
|
+
run_kg_preprocess = true
|
|
16
|
+
run_training = false
|
|
17
|
+
run_evaluation = false
|
|
18
|
+
|
|
19
|
+
[preprocessing]
|
|
20
|
+
|
|
21
|
+
remove_duplicate_triples = true
|
|
22
|
+
|
|
23
|
+
# If undirected relations are found, will make them directed by creating a reverse relation
|
|
24
|
+
make_directed = true
|
|
25
|
+
make_directed_relations = []
|
|
26
|
+
|
|
27
|
+
flag_near_duplicate_relations = true
|
|
28
|
+
|
|
29
|
+
# DL stuff, keep ?
|
|
30
|
+
#permute_entities = false
|
|
31
|
+
|
|
32
|
+
# Remove all flagged relations from the train set
|
|
33
|
+
clean_train_set = true
|
|
34
|
+
|
|
35
|
+
#mixed_test = true
|
|
36
|
+
|
|
37
|
+
[preprocessing.params]
|
|
38
|
+
theta = 0.8
|
|
39
|
+
theta1 = 0.8
|
|
40
|
+
theta2 = 0.8
|
|
41
|
+
|
|
42
|
+
[model]
|
|
43
|
+
emb_dim = 256
|
|
44
|
+
rel_emb_dim = 256
|
|
45
|
+
|
|
46
|
+
[model.encoder]
|
|
47
|
+
name = "Default" #Lookup table
|
|
48
|
+
gnn_layer_number = 1
|
|
49
|
+
#add other possible hyperparams
|
|
50
|
+
|
|
51
|
+
[model.decoder]
|
|
52
|
+
name = "TransE"
|
|
53
|
+
margin = 1 # Models using MarginLoss
|
|
54
|
+
dissimilarity = "L2"
|
|
55
|
+
#add other possible hyperparams
|
|
56
|
+
|
|
57
|
+
[sampler]
|
|
58
|
+
name = "Positional"
|
|
59
|
+
n_neg = 1
|
|
60
|
+
|
|
61
|
+
[optimizer]
|
|
62
|
+
name = "Adam"
|
|
63
|
+
[optimizer.params]
|
|
64
|
+
weight_decay = 0.001
|
|
65
|
+
|
|
66
|
+
[lr_scheduler]
|
|
67
|
+
type = "CosineAnnealingWarmRestarts"
|
|
68
|
+
[lr_scheduler.params]
|
|
69
|
+
T_0 = 10
|
|
70
|
+
T_mult = 2
|
|
71
|
+
|
|
72
|
+
[training]
|
|
73
|
+
max_epochs = 100
|
|
74
|
+
patience = 20
|
|
75
|
+
train_batch_size = 2048
|
|
76
|
+
eval_interval = 10
|
|
77
|
+
eval_batch_size = 32
|
|
78
|
+
|
|
79
|
+
[evaluation]
|
|
80
|
+
made_directed_relations = []
|
|
81
|
+
# List of relations for which link prediction will be evaluated
|
|
82
|
+
target_relations = []
|
|
83
|
+
thresholds = [10]
|
kgate/data_structures.py
ADDED
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
from collections import Counter
|
|
2
|
+
from itertools import combinations
|
|
3
|
+
import random
|
|
4
|
+
from torchkge import KnowledgeGraph
|
|
5
|
+
from torchkge.exceptions import SizeMismatchError, WrongArgumentsError, SanityError
|
|
6
|
+
import torch
|
|
7
|
+
from torch import cat, tensor
|
|
8
|
+
import logging
|
|
9
|
+
|
|
10
|
+
from tqdm import tqdm
|
|
11
|
+
|
|
12
|
+
logging.basicConfig(
|
|
13
|
+
level=logging.INFO,
|
|
14
|
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
class KGATEGraph(KnowledgeGraph):
|
|
18
|
+
"""Class extending on torchKGE KnowledgeGraph class, adding functionalities"""
|
|
19
|
+
def __init__(self, df=None, kg=None, ent2ix=None, rel2ix=None,
|
|
20
|
+
dict_of_heads=None, dict_of_tails=None, dict_of_rels=None):
|
|
21
|
+
super().__init__(df, kg, ent2ix, rel2ix, dict_of_heads, dict_of_tails, dict_of_rels)
|
|
22
|
+
|
|
23
|
+
def split_kg(self, share=0.8, sizes=None, validation=False):
|
|
24
|
+
"""Split the knowledge graph into train and test. If `sizes` is
|
|
25
|
+
provided then it is used to split the samples as explained below. If
|
|
26
|
+
only `share` is provided, the split is done at random but it assures
|
|
27
|
+
to keep at least one fact involving each type of entity and relation
|
|
28
|
+
in the training subset.
|
|
29
|
+
Does not update the dictionary of facts.
|
|
30
|
+
|
|
31
|
+
Parameters
|
|
32
|
+
----------
|
|
33
|
+
share: float
|
|
34
|
+
Percentage to allocate to train set.
|
|
35
|
+
sizes: tuple
|
|
36
|
+
Tuple of ints of length 2 or 3.
|
|
37
|
+
|
|
38
|
+
* If len(sizes) == 2, then the first sizes[0] values of the
|
|
39
|
+
knowledge graph will be used as training set and the rest as
|
|
40
|
+
test set.
|
|
41
|
+
|
|
42
|
+
* If len(sizes) == 3, then the first sizes[0] values of the
|
|
43
|
+
knowledge graph will be used as training set, the following
|
|
44
|
+
sizes[1] as validation set and the last sizes[2] as testing set.
|
|
45
|
+
validation: bool
|
|
46
|
+
Indicate if a validation set should be produced along with train
|
|
47
|
+
and test sets.
|
|
48
|
+
|
|
49
|
+
Returns
|
|
50
|
+
-------
|
|
51
|
+
train_kg: torchkge.data_structures.KnowledgeGraph
|
|
52
|
+
val_kg: torchkge.data_structures.KnowledgeGraph, optional
|
|
53
|
+
test_kg: torchkge.data_structures.KnowledgeGraph
|
|
54
|
+
|
|
55
|
+
"""
|
|
56
|
+
if sizes is not None:
|
|
57
|
+
try:
|
|
58
|
+
if len(sizes) == 3:
|
|
59
|
+
try:
|
|
60
|
+
assert (sizes[0] + sizes[1] + sizes[2] == self.n_facts)
|
|
61
|
+
except AssertionError:
|
|
62
|
+
raise WrongArgumentsError('Sizes should sum to the '
|
|
63
|
+
'number of facts.')
|
|
64
|
+
elif len(sizes) == 2:
|
|
65
|
+
try:
|
|
66
|
+
assert (sizes[0] + sizes[1] == self.n_facts)
|
|
67
|
+
except AssertionError:
|
|
68
|
+
raise WrongArgumentsError('Sizes should sum to the '
|
|
69
|
+
'number of facts.')
|
|
70
|
+
else:
|
|
71
|
+
raise SizeMismatchError('Tuple `sizes` should be of '
|
|
72
|
+
'length 2 or 3.')
|
|
73
|
+
except AssertionError:
|
|
74
|
+
raise SizeMismatchError('Tuple `sizes` should sum up to the '
|
|
75
|
+
'number of facts in the knowledge '
|
|
76
|
+
'graph.')
|
|
77
|
+
else:
|
|
78
|
+
assert share < 1
|
|
79
|
+
|
|
80
|
+
if ((sizes is not None) and (len(sizes) == 3)) or \
|
|
81
|
+
((sizes is None) and validation):
|
|
82
|
+
# return training, validation and a testing graphs
|
|
83
|
+
|
|
84
|
+
if (sizes is None) and validation:
|
|
85
|
+
mask_tr, mask_val, mask_te = self.get_mask(share,
|
|
86
|
+
validation=True)
|
|
87
|
+
else:
|
|
88
|
+
mask_tr = cat([tensor([1 for _ in range(sizes[0])]),
|
|
89
|
+
tensor([0 for _ in range(sizes[1] + sizes[2])])]).bool()
|
|
90
|
+
mask_val = cat([tensor([0 for _ in range(sizes[0])]),
|
|
91
|
+
tensor([1 for _ in range(sizes[1])]),
|
|
92
|
+
tensor([0 for _ in range(sizes[2])])]).bool()
|
|
93
|
+
mask_te = ~(mask_tr | mask_val)
|
|
94
|
+
|
|
95
|
+
return (self.__class__(
|
|
96
|
+
kg={'heads': self.head_idx[mask_tr],
|
|
97
|
+
'tails': self.tail_idx[mask_tr],
|
|
98
|
+
'relations': self.relations[mask_tr]},
|
|
99
|
+
ent2ix=self.ent2ix, rel2ix=self.rel2ix,
|
|
100
|
+
dict_of_heads=self.dict_of_heads,
|
|
101
|
+
dict_of_tails=self.dict_of_tails,
|
|
102
|
+
dict_of_rels=self.dict_of_rels),
|
|
103
|
+
self.__class__(
|
|
104
|
+
kg={'heads': self.head_idx[mask_val],
|
|
105
|
+
'tails': self.tail_idx[mask_val],
|
|
106
|
+
'relations': self.relations[mask_val]},
|
|
107
|
+
ent2ix=self.ent2ix, rel2ix=self.rel2ix,
|
|
108
|
+
dict_of_heads=self.dict_of_heads,
|
|
109
|
+
dict_of_tails=self.dict_of_tails,
|
|
110
|
+
dict_of_rels=self.dict_of_rels),
|
|
111
|
+
self.__class__(
|
|
112
|
+
kg={'heads': self.head_idx[mask_te],
|
|
113
|
+
'tails': self.tail_idx[mask_te],
|
|
114
|
+
'relations': self.relations[mask_te]},
|
|
115
|
+
ent2ix=self.ent2ix, rel2ix=self.rel2ix,
|
|
116
|
+
dict_of_heads=self.dict_of_heads,
|
|
117
|
+
dict_of_tails=self.dict_of_tails,
|
|
118
|
+
dict_of_rels=self.dict_of_rels))
|
|
119
|
+
else:
|
|
120
|
+
# return training and testing graphs
|
|
121
|
+
|
|
122
|
+
assert (((sizes is not None) and len(sizes) == 2) or
|
|
123
|
+
((sizes is None) and not validation))
|
|
124
|
+
if sizes is None:
|
|
125
|
+
mask_tr, mask_te = self.get_mask(share, validation=False)
|
|
126
|
+
else:
|
|
127
|
+
mask_tr = cat([tensor([1 for _ in range(sizes[0])]),
|
|
128
|
+
tensor([0 for _ in range(sizes[1])])]).bool()
|
|
129
|
+
mask_te = ~mask_tr
|
|
130
|
+
return (self.__class__(
|
|
131
|
+
kg={'heads': self.head_idx[mask_tr],
|
|
132
|
+
'tails': self.tail_idx[mask_tr],
|
|
133
|
+
'relations': self.relations[mask_tr]},
|
|
134
|
+
ent2ix=self.ent2ix, rel2ix=self.rel2ix,
|
|
135
|
+
dict_of_heads=self.dict_of_heads,
|
|
136
|
+
dict_of_tails=self.dict_of_tails,
|
|
137
|
+
dict_of_rels=self.dict_of_rels),
|
|
138
|
+
self.__class__(
|
|
139
|
+
kg={'heads': self.head_idx[mask_te],
|
|
140
|
+
'tails': self.tail_idx[mask_te],
|
|
141
|
+
'relations': self.relations[mask_te]},
|
|
142
|
+
ent2ix=self.ent2ix, rel2ix=self.rel2ix,
|
|
143
|
+
dict_of_heads=self.dict_of_heads,
|
|
144
|
+
dict_of_tails=self.dict_of_tails,
|
|
145
|
+
dict_of_rels=self.dict_of_rels))
|
|
146
|
+
|
|
147
|
+
def keep_triples(self, indices_to_keep):
|
|
148
|
+
"""
|
|
149
|
+
Keeps only the specified triples in the knowledge graph and returns a new
|
|
150
|
+
KnowledgeGraph instance with these triples. Updates the dictionnary of facts.
|
|
151
|
+
|
|
152
|
+
Parameters
|
|
153
|
+
----------
|
|
154
|
+
indices_to_keep : list or torch.Tensor
|
|
155
|
+
Indices of triples to keep in the knowledge graph.
|
|
156
|
+
|
|
157
|
+
Returns
|
|
158
|
+
-------
|
|
159
|
+
KGATEGraph
|
|
160
|
+
A new instance of KnowledgeGraph with only the specified triples.
|
|
161
|
+
"""
|
|
162
|
+
# Create masks for indices to keep
|
|
163
|
+
mask = torch.zeros(self.n_facts, dtype=torch.bool)
|
|
164
|
+
mask[indices_to_keep] = True
|
|
165
|
+
|
|
166
|
+
# Use the mask to filter the triples to keep
|
|
167
|
+
new_heads = self.head_idx[mask]
|
|
168
|
+
new_tails = self.tail_idx[mask]
|
|
169
|
+
new_relations = self.relations[mask]
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# Create a new KGATEGraph instance
|
|
173
|
+
return self.__class__(
|
|
174
|
+
kg={'heads': new_heads, 'tails': new_tails, 'relations': new_relations},
|
|
175
|
+
ent2ix=self.ent2ix,
|
|
176
|
+
rel2ix=self.rel2ix
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
def remove_triples(self, indices_to_remove):
|
|
180
|
+
"""
|
|
181
|
+
Removes specified triples from the knowledge graph and returns a new
|
|
182
|
+
KnowledgeGraph instance without these triples.
|
|
183
|
+
|
|
184
|
+
Parameters
|
|
185
|
+
----------
|
|
186
|
+
indices_to_remove : list or torch.Tensor
|
|
187
|
+
Indices of triples to remove from the knowledge graph.
|
|
188
|
+
|
|
189
|
+
Returns
|
|
190
|
+
-------
|
|
191
|
+
KnowledgeGraph
|
|
192
|
+
A new instance of KnowledgeGraph without the specified triples.
|
|
193
|
+
"""
|
|
194
|
+
# Create masks for indices not to remove
|
|
195
|
+
mask = torch.ones(self.n_facts, dtype=torch.bool)
|
|
196
|
+
mask[indices_to_remove] = False
|
|
197
|
+
|
|
198
|
+
# Use the mask to filter out the triples
|
|
199
|
+
new_heads = self.head_idx[mask]
|
|
200
|
+
new_tails = self.tail_idx[mask]
|
|
201
|
+
new_relations = self.relations[mask]
|
|
202
|
+
|
|
203
|
+
return self.__class__(
|
|
204
|
+
kg={'heads': new_heads, 'tails': new_tails, 'relations': new_relations},
|
|
205
|
+
ent2ix=self.ent2ix,
|
|
206
|
+
rel2ix=self.rel2ix,
|
|
207
|
+
dict_of_heads=self.dict_of_heads,
|
|
208
|
+
dict_of_tails=self.dict_of_tails,
|
|
209
|
+
dict_of_rels=self.dict_of_rels
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
def add_triples(self, new_triples):
|
|
213
|
+
"""
|
|
214
|
+
Add new triples to the Knowledge Graph
|
|
215
|
+
|
|
216
|
+
Parameters
|
|
217
|
+
----------
|
|
218
|
+
new_triples : torch.Tensor
|
|
219
|
+
Tensor of shape (n, 3) where each row represent a triple (head_idx, tail_idx, rel_idx).
|
|
220
|
+
|
|
221
|
+
Returns
|
|
222
|
+
-------
|
|
223
|
+
KnowledgeGraph
|
|
224
|
+
A new instance of KnowledgeGraph with the updated triples.
|
|
225
|
+
"""
|
|
226
|
+
if not isinstance(new_triples, torch.Tensor):
|
|
227
|
+
raise TypeError("new_triples doit être un torch.Tensor.")
|
|
228
|
+
if new_triples.dim() != 2 or new_triples.size(1) != 3:
|
|
229
|
+
raise ValueError("new_triples doit avoir la forme (n, 3).")
|
|
230
|
+
|
|
231
|
+
# Check that entities and relations exist in ent2ix and rel2ix
|
|
232
|
+
max_ent_idx = max(new_triples[:, 0].max().item(), new_triples[:, 1].max().item())
|
|
233
|
+
max_rel_idx = new_triples[:, 2].max().item()
|
|
234
|
+
|
|
235
|
+
if max_ent_idx >= self.n_ent:
|
|
236
|
+
raise ValueError(f"L'indice d'entité maximal ({max_ent_idx}) dépasse le nombre d'entités ({self.n_ent}).")
|
|
237
|
+
if max_rel_idx >= self.n_rel:
|
|
238
|
+
raise ValueError(f"L'indice de relation maximal ({max_rel_idx}) dépasse le nombre de relations ({self.n_rel}).")
|
|
239
|
+
|
|
240
|
+
# Concatenate new triples to existing ones
|
|
241
|
+
updated_head_idx = torch.cat((self.head_idx, new_triples[:, 0]), dim=0)
|
|
242
|
+
updated_tail_idx = torch.cat((self.tail_idx, new_triples[:, 1]), dim=0)
|
|
243
|
+
updated_relations = torch.cat((self.relations, new_triples[:, 2]), dim=0)
|
|
244
|
+
|
|
245
|
+
# Update dict_of_heads, dict_of_tails, dict_of_rels
|
|
246
|
+
for h, t, r in new_triples.tolist():
|
|
247
|
+
self.dict_of_heads[(t, r)].add(h)
|
|
248
|
+
self.dict_of_tails[(h, r)].add(t)
|
|
249
|
+
self.dict_of_rels[(h, t)].add(r)
|
|
250
|
+
|
|
251
|
+
# Create a new instance of the class with updated triples
|
|
252
|
+
return self.__class__(
|
|
253
|
+
kg={'heads': updated_head_idx, 'tails': updated_tail_idx, 'relations': updated_relations},
|
|
254
|
+
ent2ix=self.ent2ix,
|
|
255
|
+
rel2ix=self.rel2ix,
|
|
256
|
+
dict_of_heads=self.dict_of_heads,
|
|
257
|
+
dict_of_tails=self.dict_of_tails,
|
|
258
|
+
dict_of_rels=self.dict_of_rels
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
def add_inverse_relations(self, undirected_relations):
|
|
262
|
+
"""
|
|
263
|
+
Adds inverse triples for the specified undirected relations in the knowledge graph.
|
|
264
|
+
Updates head_idx, tail_idx, relations with the inverse triples, and updates the dictionaries to include
|
|
265
|
+
both original and inverse facts in all directions.
|
|
266
|
+
|
|
267
|
+
Parameters
|
|
268
|
+
----------
|
|
269
|
+
undirected_relations: list
|
|
270
|
+
List of undirected relations for which inverse triples should be added.
|
|
271
|
+
|
|
272
|
+
Returns
|
|
273
|
+
-------
|
|
274
|
+
KnowledgeGraph, list
|
|
275
|
+
The updated KnowledgeGraph with the dictionaries and tensors modified,
|
|
276
|
+
and a list of pairs (old relation ID, new inverse relation ID).
|
|
277
|
+
"""
|
|
278
|
+
|
|
279
|
+
ix2rel = {v: k for k, v in self.rel2ix.items()}
|
|
280
|
+
|
|
281
|
+
reverse_list = []
|
|
282
|
+
|
|
283
|
+
# New triples lists
|
|
284
|
+
new_head_idx, new_tail_idx, new_relations = [], [], []
|
|
285
|
+
|
|
286
|
+
for relation_id in undirected_relations:
|
|
287
|
+
inverse_relation = f"{ix2rel[relation_id]}_inv"
|
|
288
|
+
|
|
289
|
+
# Check if the inverse relation already exists in the graph
|
|
290
|
+
if relation_id not in self.rel2ix.values():
|
|
291
|
+
logging.info(f"Relation {relation_id} not found in knowledge graph. Skipping...")
|
|
292
|
+
continue
|
|
293
|
+
|
|
294
|
+
# Create a new ID for the inverse relation
|
|
295
|
+
inverse_relation_id = len(self.rel2ix)
|
|
296
|
+
self.rel2ix[inverse_relation] = inverse_relation_id
|
|
297
|
+
|
|
298
|
+
reverse_list.append((relation_id, inverse_relation_id))
|
|
299
|
+
|
|
300
|
+
# Masks for the original relation
|
|
301
|
+
mask = (self.relations == relation_id)
|
|
302
|
+
|
|
303
|
+
# Add new inverse triples to the tensors
|
|
304
|
+
new_head_idx.append(self.tail_idx[mask])
|
|
305
|
+
new_tail_idx.append(self.head_idx[mask])
|
|
306
|
+
new_relations.append(torch.full_like(self.relations[mask], inverse_relation_id))
|
|
307
|
+
|
|
308
|
+
# Add facts to the dictionnaries
|
|
309
|
+
for i in range(len(mask)):
|
|
310
|
+
if mask[i]:
|
|
311
|
+
h = self.head_idx[i].item()
|
|
312
|
+
t = self.tail_idx[i].item()
|
|
313
|
+
|
|
314
|
+
# Add original fact (a, r, b)
|
|
315
|
+
self.dict_of_heads.setdefault((t, relation_id), set()).add(h) # (t, r) -> h
|
|
316
|
+
self.dict_of_tails.setdefault((h, relation_id), set()).add(t) # (h, r) -> t
|
|
317
|
+
self.dict_of_rels.setdefault((h, t), set()).add(relation_id) # (h, t) -> r
|
|
318
|
+
|
|
319
|
+
# Add inverse fact (b, r_inv, a)
|
|
320
|
+
self.dict_of_heads.setdefault((h, inverse_relation_id), set()).add(t) # (h, r_inv) -> t
|
|
321
|
+
self.dict_of_tails.setdefault((t, inverse_relation_id), set()).add(h) # (t, r_inv) -> h
|
|
322
|
+
self.dict_of_rels.setdefault((t, h), set()).add(inverse_relation_id) # (t, h) -> r_inv
|
|
323
|
+
|
|
324
|
+
# Ajouter les combinaisons supplémentaires (b, r, a) et (a, r_inv, b)
|
|
325
|
+
self.dict_of_heads.setdefault((t, relation_id), set()).add(h) # (t, r) -> h
|
|
326
|
+
self.dict_of_tails.setdefault((h, relation_id), set()).add(t) # (h, r) -> t
|
|
327
|
+
self.dict_of_rels.setdefault((t, h), set()).add(relation_id) # (t, h) -> r
|
|
328
|
+
|
|
329
|
+
self.dict_of_heads.setdefault((h, inverse_relation_id), set()).add(t) # (h, r_inv) -> t
|
|
330
|
+
self.dict_of_tails.setdefault((t, inverse_relation_id), set()).add(h) # (t, r_inv) -> h
|
|
331
|
+
self.dict_of_rels.setdefault((h, t), set()).add(inverse_relation_id) # (h, t) -> r_inv
|
|
332
|
+
|
|
333
|
+
# Concat new triples to existing ones
|
|
334
|
+
if new_head_idx:
|
|
335
|
+
self.head_idx = torch.cat((self.head_idx, *new_head_idx), dim=0)
|
|
336
|
+
self.tail_idx = torch.cat((self.tail_idx, *new_tail_idx), dim=0)
|
|
337
|
+
self.relations = torch.cat((self.relations, *new_relations), dim=0)
|
|
338
|
+
|
|
339
|
+
return self.__class__(
|
|
340
|
+
kg={'heads': self.head_idx, 'tails': self.tail_idx, 'relations': self.relations},
|
|
341
|
+
ent2ix=self.ent2ix,
|
|
342
|
+
rel2ix=self.rel2ix,
|
|
343
|
+
dict_of_heads=self.dict_of_heads,
|
|
344
|
+
dict_of_tails=self.dict_of_tails,
|
|
345
|
+
dict_of_rels=self.dict_of_rels
|
|
346
|
+
), reverse_list
|
|
347
|
+
|
|
348
|
+
def permute_tails(self, relation_id):
|
|
349
|
+
"""
|
|
350
|
+
Randomly permutes the `tails` for a given relation while maintaining the original degree
|
|
351
|
+
of `heads` and `tails`, ensuring there are no triples of the form (a, rel, a) where `head == tail`.
|
|
352
|
+
Updates the dictionary of facts.
|
|
353
|
+
|
|
354
|
+
Parameters
|
|
355
|
+
----------
|
|
356
|
+
relation_id: int
|
|
357
|
+
The ID of the relation for which `tails` should be permuted.
|
|
358
|
+
|
|
359
|
+
Returns
|
|
360
|
+
-------
|
|
361
|
+
KnowledgeGraph
|
|
362
|
+
A new instance of KnowledgeGraph with the `tails` permuted.
|
|
363
|
+
"""
|
|
364
|
+
|
|
365
|
+
# Clone the attributes for the new instance
|
|
366
|
+
new_head_idx = self.head_idx.clone()
|
|
367
|
+
new_tail_idx = self.tail_idx.clone()
|
|
368
|
+
new_relations = self.relations.clone()
|
|
369
|
+
|
|
370
|
+
# Mask to filter out all relations except the given one
|
|
371
|
+
mask = (new_relations == relation_id)
|
|
372
|
+
|
|
373
|
+
# Extract all head and tail indices for this relation
|
|
374
|
+
heads_for_relation = new_head_idx[mask].tolist()
|
|
375
|
+
tails_for_relation = new_tail_idx[mask].tolist()
|
|
376
|
+
|
|
377
|
+
tails_count = Counter(tails_for_relation)
|
|
378
|
+
|
|
379
|
+
permuted_tails = tails_for_relation[:]
|
|
380
|
+
random.shuffle(permuted_tails)
|
|
381
|
+
|
|
382
|
+
# Correct self-loops while preserving node degree
|
|
383
|
+
for i in range(len(permuted_tails)):
|
|
384
|
+
if heads_for_relation[i] == permuted_tails[i]:
|
|
385
|
+
# If we have a self-loop, look for another tail
|
|
386
|
+
found = False
|
|
387
|
+
for j in range(i + 1, len(permuted_tails)):
|
|
388
|
+
if heads_for_relation[j] != permuted_tails[i] and heads_for_relation[i] != permuted_tails[j]:
|
|
389
|
+
# Trade to solve the self-loop
|
|
390
|
+
permuted_tails[i], permuted_tails[j] = permuted_tails[j], permuted_tails[i]
|
|
391
|
+
found = True
|
|
392
|
+
break
|
|
393
|
+
# If no valid trade is found, go back to the beginning
|
|
394
|
+
if not found:
|
|
395
|
+
for j in range(0, i):
|
|
396
|
+
if heads_for_relation[j] != permuted_tails[i] and heads_for_relation[i] != permuted_tails[j]:
|
|
397
|
+
# Trade to solve the self-loop
|
|
398
|
+
permuted_tails[i], permuted_tails[j] = permuted_tails[j], permuted_tails[i]
|
|
399
|
+
break
|
|
400
|
+
|
|
401
|
+
permuted_tails = torch.tensor(permuted_tails, dtype=new_tail_idx.dtype)
|
|
402
|
+
|
|
403
|
+
# Replace original tails with permuted ones
|
|
404
|
+
new_tail_idx[mask] = permuted_tails
|
|
405
|
+
|
|
406
|
+
# Check if the node degree is correctly preserved
|
|
407
|
+
assert Counter(new_tail_idx[mask].tolist()) == tails_count, "Tails degree not preserved after petmutation."
|
|
408
|
+
assert all(new_head_idx[i] != new_tail_idx[i] for i in range(len(new_head_idx))), "Some triples have the same `head` and `tail` after permutation (self-loop)."
|
|
409
|
+
|
|
410
|
+
return self.__class__(
|
|
411
|
+
kg={'heads': new_head_idx, 'tails': new_tail_idx, 'relations': new_relations},
|
|
412
|
+
ent2ix=self.ent2ix,
|
|
413
|
+
rel2ix=self.rel2ix,
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def remove_duplicate_triples(self):
|
|
418
|
+
"""
|
|
419
|
+
Remove duplicate triples from a knowledge graph for each relation and keep only unique triples.
|
|
420
|
+
|
|
421
|
+
This function processes each relation separately, identifies unique triples based on head and tail indices,
|
|
422
|
+
and retains only the unique triples by filtering out duplicates.
|
|
423
|
+
|
|
424
|
+
Returns:
|
|
425
|
+
- KnowledgeGraph: A new instance of the KnowledgeGraph containing only unique triples.
|
|
426
|
+
|
|
427
|
+
The function also updates a dictionary `T` which holds pairs of head and tail indices for each relation
|
|
428
|
+
along with their original indices in the dataset.
|
|
429
|
+
|
|
430
|
+
"""
|
|
431
|
+
T = {} # Dictionary to store pairs for each relation
|
|
432
|
+
keep = torch.tensor([], dtype=torch.long) # Tensor to store indices of triples to keep
|
|
433
|
+
|
|
434
|
+
h, t, r = self.head_idx, self.tail_idx, self.relations
|
|
435
|
+
|
|
436
|
+
# Process each relation
|
|
437
|
+
for r_ in tqdm(range(self.n_rel)):
|
|
438
|
+
# Create a mask for the current relation
|
|
439
|
+
mask = (r == r_)
|
|
440
|
+
|
|
441
|
+
# Extract pairs of head and tail indices for the current relation
|
|
442
|
+
original_indices = torch.arange(h.size(0))[mask]
|
|
443
|
+
pairs = torch.stack((h[mask], t[mask]), dim=1)
|
|
444
|
+
pairs = torch.sort(pairs, dim=1).values
|
|
445
|
+
pairs = torch.cat([pairs, original_indices.unsqueeze(1)], dim=1)
|
|
446
|
+
|
|
447
|
+
# Create a dictionary entry for the relation with pairs
|
|
448
|
+
T[r_] = pairs
|
|
449
|
+
|
|
450
|
+
# Identify unique triples and their original indices
|
|
451
|
+
unique, idx, counts = torch.unique(pairs[:, :2], dim=0, sorted=True, return_inverse=True, return_counts=True)
|
|
452
|
+
_, ind_sorted = torch.sort(idx, stable=True)
|
|
453
|
+
cum_sum = counts.cumsum(0)
|
|
454
|
+
cum_sum = torch.cat((torch.tensor([0]), cum_sum[:-1]))
|
|
455
|
+
first_indices = ind_sorted[cum_sum]
|
|
456
|
+
|
|
457
|
+
# Retrieve original indices of first unique entries
|
|
458
|
+
adjusted_indices = pairs[first_indices, 2]
|
|
459
|
+
|
|
460
|
+
# Accumulate unique indices globally
|
|
461
|
+
keep = torch.cat((keep, adjusted_indices))
|
|
462
|
+
|
|
463
|
+
# Logging duplicate information
|
|
464
|
+
if len(pairs) - len(unique) > 0:
|
|
465
|
+
logging.info(f'{len(pairs) - len(unique)} duplicates found. Keeping {len(unique)} unique triplets for relation {r_}')
|
|
466
|
+
|
|
467
|
+
# Return a new KnowledgeGraph instance with only unique triples retained
|
|
468
|
+
return self.keep_triples(keep)
|
|
469
|
+
|
|
470
|
+
def get_pairs(self, r, type='ht'):
|
|
471
|
+
mask = (self.relations == r)
|
|
472
|
+
|
|
473
|
+
if type == 'ht':
|
|
474
|
+
return set((i.item(), j.item()) for i, j in cat(
|
|
475
|
+
(self.head_idx[mask].view(-1, 1),
|
|
476
|
+
self.tail_idx[mask].view(-1, 1)), dim=1))
|
|
477
|
+
else:
|
|
478
|
+
assert type == 'th'
|
|
479
|
+
return set((j.item(), i.item()) for i, j in cat(
|
|
480
|
+
(self.head_idx[mask].view(-1, 1),
|
|
481
|
+
self.tail_idx[mask].view(-1, 1)), dim=1))
|
|
482
|
+
|
|
483
|
+
def duplicates(self, theta1=0.8, theta2=0.8, counts=False, reverses=None):
|
|
484
|
+
"""Return the duplicate and reverse duplicate relations as explained
|
|
485
|
+
in paper by Akrami et al.
|
|
486
|
+
|
|
487
|
+
References
|
|
488
|
+
----------
|
|
489
|
+
* Farahnaz Akrami, Mohammed Samiul Saeef, Quingheng Zhang.
|
|
490
|
+
`Realistic Re-evaluation of Knowledge Graph Completion Methods:
|
|
491
|
+
An Experimental Study. <https://arxiv.org/pdf/2003.08001.pdf>`_
|
|
492
|
+
SIGMOD’20, June 14–19, 2020, Portland, OR, USA
|
|
493
|
+
|
|
494
|
+
Parameters
|
|
495
|
+
----------
|
|
496
|
+
kg_tr: torchkge.data_structures.KnowledgeGraph
|
|
497
|
+
Train set
|
|
498
|
+
kg_val: torchkge.data_structures.KnowledgeGraph
|
|
499
|
+
Validation set
|
|
500
|
+
kg_te: torchkge.data_structures.KnowledgeGraph
|
|
501
|
+
Test set
|
|
502
|
+
theta1: float
|
|
503
|
+
First threshold (see paper).
|
|
504
|
+
theta2: float
|
|
505
|
+
Second threshold (see paper).
|
|
506
|
+
counts: bool
|
|
507
|
+
Should the triplets involving (reverse) duplicate relations be
|
|
508
|
+
counted in all sets.
|
|
509
|
+
reverses: list
|
|
510
|
+
List of known reverse relations.
|
|
511
|
+
|
|
512
|
+
Returns
|
|
513
|
+
-------
|
|
514
|
+
duplicates: list
|
|
515
|
+
List of pairs giving duplicate relations.
|
|
516
|
+
rev_duplicates: list
|
|
517
|
+
List of pairs giving reverse duplicate relations.
|
|
518
|
+
"""
|
|
519
|
+
|
|
520
|
+
if reverses is None:
|
|
521
|
+
reverses = []
|
|
522
|
+
|
|
523
|
+
T = dict()
|
|
524
|
+
T_inv = dict()
|
|
525
|
+
lengths = dict()
|
|
526
|
+
|
|
527
|
+
h, t, r = self.head_idx, self.tail_idx, self.relations
|
|
528
|
+
|
|
529
|
+
for r_ in tqdm(range(self.n_rel)):
|
|
530
|
+
mask = (r == r_)
|
|
531
|
+
lengths[r_] = mask.sum().item()
|
|
532
|
+
|
|
533
|
+
pairs = cat((h[mask].view(-1, 1), t[mask].view(-1, 1)), dim=1)
|
|
534
|
+
|
|
535
|
+
T[r_] = set([(h_.item(), t_.item()) for h_, t_ in pairs])
|
|
536
|
+
T_inv[r_] = set([(t_.item(), h_.item()) for h_, t_ in pairs])
|
|
537
|
+
|
|
538
|
+
logging.info('Finding duplicate relations')
|
|
539
|
+
|
|
540
|
+
duplicates = []
|
|
541
|
+
rev_duplicates = []
|
|
542
|
+
|
|
543
|
+
iter_ = list(combinations(range(self.n_rel), 2))
|
|
544
|
+
|
|
545
|
+
for r1, r2 in tqdm(iter_):
|
|
546
|
+
a = len(T[r1].intersection(T[r2])) / lengths[r1]
|
|
547
|
+
b = len(T[r1].intersection(T[r2])) / lengths[r2]
|
|
548
|
+
|
|
549
|
+
if a > theta1 and b > theta2:
|
|
550
|
+
duplicates.append((r1, r2))
|
|
551
|
+
|
|
552
|
+
if (r1, r2) not in reverses:
|
|
553
|
+
a = len(T[r1].intersection(T_inv[r2])) / lengths[r1]
|
|
554
|
+
b = len(T[r1].intersection(T_inv[r2])) / lengths[r2]
|
|
555
|
+
|
|
556
|
+
if a > theta1 and b > theta2:
|
|
557
|
+
rev_duplicates.append((r1, r2))
|
|
558
|
+
|
|
559
|
+
logging.info('Duplicate relations: {}'.format(len(duplicates)))
|
|
560
|
+
logging.info('Reverse duplicate relations: '
|
|
561
|
+
'{}\n'.format(len(rev_duplicates)))
|
|
562
|
+
|
|
563
|
+
return duplicates, rev_duplicates
|
|
564
|
+
|
|
565
|
+
def cartesian_product_relations(self, theta=0.8):
|
|
566
|
+
"""Return the cartesian product relations as explained in paper by
|
|
567
|
+
Akrami et al.
|
|
568
|
+
|
|
569
|
+
References
|
|
570
|
+
----------
|
|
571
|
+
* Farahnaz Akrami, Mohammed Samiul Saeef, Quingheng Zhang.
|
|
572
|
+
`Realistic Re-evaluation of Knowledge Graph Completion Methods: An
|
|
573
|
+
Experimental Study. <https://arxiv.org/pdf/2003.08001.pdf>`_
|
|
574
|
+
SIGMOD’20, June 14–19, 2020, Portland, OR, USA
|
|
575
|
+
|
|
576
|
+
Parameters
|
|
577
|
+
----------
|
|
578
|
+
kg: torchkge.data_structures.KnowledgeGraph
|
|
579
|
+
theta: float
|
|
580
|
+
Threshold used to compute the cartesian product relations.
|
|
581
|
+
|
|
582
|
+
Returns
|
|
583
|
+
-------
|
|
584
|
+
selected_relations: list
|
|
585
|
+
List of relations index that are cartesian product relations
|
|
586
|
+
(see paper for details).
|
|
587
|
+
|
|
588
|
+
"""
|
|
589
|
+
selected_relations = []
|
|
590
|
+
|
|
591
|
+
h, t, r = self.head_idx, self.tail_idx, self.relations
|
|
592
|
+
|
|
593
|
+
S = dict()
|
|
594
|
+
O = dict()
|
|
595
|
+
lengths = dict()
|
|
596
|
+
|
|
597
|
+
for r_ in tqdm(range(self.n_rel)):
|
|
598
|
+
mask = (r == r_)
|
|
599
|
+
lengths[r_] = mask.sum().item()
|
|
600
|
+
|
|
601
|
+
S[r_] = set(h_.item() for h_ in h[mask])
|
|
602
|
+
O[r_] = set(t_.item() for t_ in t[mask])
|
|
603
|
+
|
|
604
|
+
if lengths[r_] / (len(S[r_]) * len(O[r_])) > theta:
|
|
605
|
+
selected_relations.append(r_)
|
|
606
|
+
|
|
607
|
+
return selected_relations
|