KGATE 0.3.0__tar.gz → 0.3.2__tar.gz
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-0.3.0 → kgate-0.3.2}/PKG-INFO +1 -1
- {kgate-0.3.0 → kgate-0.3.2}/pyproject.toml +1 -1
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/architect.py +40 -47
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/config_template.toml +1 -3
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/decoders/bilinear.py +1 -1
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/decoders/translational.py +1 -1
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/inference.py +177 -107
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/preprocessing.py +41 -57
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/samplers.py +14 -9
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/utils.py +2 -2
- {kgate-0.3.0 → kgate-0.3.2}/LICENSE +0 -0
- {kgate-0.3.0 → kgate-0.3.2}/README.md +0 -0
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/__init__.py +0 -0
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/cli.py +0 -0
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/data_leakage.py +0 -0
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/decoders/__init__.py +0 -0
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/decoders/convolutional.py +0 -0
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/encoders.py +0 -0
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/evaluators.py +0 -0
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/grid_search.py +0 -0
- {kgate-0.3.0 → kgate-0.3.2}/src/kgate/knowledgegraph.py +0 -0
|
@@ -13,11 +13,18 @@ from collections.abc import Callable
|
|
|
13
13
|
from glob import glob
|
|
14
14
|
from inspect import signature
|
|
15
15
|
from pathlib import Path
|
|
16
|
-
from typing import Tuple, Dict, List, Any, Set, Literal
|
|
16
|
+
from typing import Tuple, Dict, List, Any, Set, Literal, Optional
|
|
17
17
|
|
|
18
18
|
import pandas as pd
|
|
19
19
|
import numpy as np
|
|
20
|
-
import
|
|
20
|
+
import tomli_w
|
|
21
|
+
|
|
22
|
+
from torchkge import KnowledgeGraph
|
|
23
|
+
from torchkge.models import Model
|
|
24
|
+
import torchkge.sampling as sampling
|
|
25
|
+
from torchkge.utils import MarginLoss, BinaryCrossEntropyLoss
|
|
26
|
+
|
|
27
|
+
from torch_geometric.utils import k_hop_subgraph
|
|
21
28
|
|
|
22
29
|
import torch
|
|
23
30
|
from torch import tensor, Tensor
|
|
@@ -219,7 +226,7 @@ class Architect(Module):
|
|
|
219
226
|
|
|
220
227
|
self.metadata = None
|
|
221
228
|
if metadata is None:
|
|
222
|
-
metadata = self.config["metadata_csv"]
|
|
229
|
+
metadata = self.config["metadata_csv"] if self.config["metadata_csv"] != "" else None
|
|
223
230
|
self.set_metadata(metadata = metadata)
|
|
224
231
|
|
|
225
232
|
run_kg_preprocessing: bool = self.config["run_kg_preprocessing"]
|
|
@@ -341,7 +348,7 @@ class Architect(Module):
|
|
|
341
348
|
|
|
342
349
|
self.metadata = metadata
|
|
343
350
|
case os.PathLike:
|
|
344
|
-
if
|
|
351
|
+
if Path(metadata).exists():
|
|
345
352
|
# Fuzzy identification of separator.
|
|
346
353
|
# TODO: find a cleaner way to do it
|
|
347
354
|
for separator in SUPPORTED_SEPARATORS:
|
|
@@ -354,7 +361,7 @@ class Architect(Module):
|
|
|
354
361
|
if self.metadata is None:
|
|
355
362
|
raise ValueError(f"The metadata csv file uses a non supported separator. Supported separators are '{'\', \''.join(SUPPORTED_SEPARATORS)}'.")
|
|
356
363
|
case _:
|
|
357
|
-
|
|
364
|
+
return
|
|
358
365
|
|
|
359
366
|
if self.metadata is not None and hasattr(self, "kg_train"):
|
|
360
367
|
for knowledge_graph in (self.kg_train, self.kg_val, self.kg_test):
|
|
@@ -1045,61 +1052,47 @@ class Architect(Module):
|
|
|
1045
1052
|
|
|
1046
1053
|
self.eval()
|
|
1047
1054
|
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1055
|
+
target_edges: List[str] = self.config["evaluation"]["target_edges"]
|
|
1056
|
+
metrics_file: Path = Path(self.config["output_directory"], "evaluation_metrics.toml")
|
|
1057
|
+
|
|
1058
|
+
target_edges_result = {}
|
|
1052
1059
|
|
|
1053
1060
|
all_edges: Set[Any] = set(self.kg_test.edge_to_index.keys())
|
|
1054
|
-
remaining_edges = all_edges - set(
|
|
1061
|
+
remaining_edges = all_edges - set(target_edges)
|
|
1055
1062
|
remaining_edges = list(remaining_edges)
|
|
1063
|
+
|
|
1064
|
+
triplet_count_target_edges = 0
|
|
1065
|
+
|
|
1066
|
+
if len(remaining_edges) != len(all_edges):
|
|
1067
|
+
metrics_sum_target_edges, triplet_count_target_edges, individual_metrics_target_edges, group_metrics_target_edges = self.calculate_metrics_for_edges(self.kg_test, target_edges)
|
|
1068
|
+
|
|
1069
|
+
target_edges_result = {
|
|
1070
|
+
"target_edges": {
|
|
1071
|
+
"Global_metrics": metrics_sum_target_edges,
|
|
1072
|
+
"Individual_metrics": individual_metrics_target_edges
|
|
1073
|
+
},
|
|
1074
|
+
}
|
|
1056
1075
|
|
|
1057
|
-
|
|
1058
|
-
self.kg_test, list_rel_1)
|
|
1059
|
-
total_metrics_sum_list_2, triplet_count_list_2, individual_metrics_list_2, group_metrics_list_2 = self.calculate_metrics_for_edges(
|
|
1060
|
-
self.kg_test, list_rel_2)
|
|
1061
|
-
total_metrics_sum_remaining, triplet_count_remaining, individual_metrics_remaining, group_metrics_remaining = self.calculate_metrics_for_edges(
|
|
1062
|
-
self.kg_test, remaining_edges)
|
|
1076
|
+
total_metrics_sum_remaining, triplet_count_remaining, individual_metrics_remaining, group_metrics_remaining = self.calculate_metrics_for_edges(self.kg_test, remaining_edges)
|
|
1063
1077
|
|
|
1064
|
-
global_metrics = (
|
|
1078
|
+
global_metrics = (group_metrics_remaining + total_metrics_sum_remaining) / (triplet_count_target_edges + triplet_count_remaining)
|
|
1065
1079
|
|
|
1066
1080
|
logging.info(f"Final Test metrics with best model: {global_metrics}")
|
|
1067
1081
|
|
|
1068
1082
|
results = {
|
|
1069
1083
|
"Global_metrics": global_metrics,
|
|
1070
|
-
|
|
1071
|
-
"Global_metrics": group_metrics_list_1,
|
|
1072
|
-
"Individual_metrics": individual_metrics_list_1
|
|
1073
|
-
},
|
|
1074
|
-
"target_edges": {
|
|
1075
|
-
"Global_metrics": group_metrics_list_2,
|
|
1076
|
-
"Individual_metrics": individual_metrics_list_2
|
|
1077
|
-
},
|
|
1084
|
+
**target_edges_result, # if there is no target edges, don't add the block
|
|
1078
1085
|
"remaining_edges": {
|
|
1079
1086
|
"Global_metrics": group_metrics_remaining,
|
|
1080
1087
|
"Individual_metrics": individual_metrics_remaining
|
|
1081
1088
|
},
|
|
1082
1089
|
"target_edges_by_frequency": {}
|
|
1083
1090
|
}
|
|
1084
|
-
|
|
1085
|
-
for i in range(len(list_rel_2)):
|
|
1086
|
-
edge: str = list_rel_2[i]
|
|
1087
|
-
threshold: int = thresholds[i]
|
|
1088
|
-
frequent_indices, infrequent_indices = self.categorize_test_nodes(edge, threshold)
|
|
1089
|
-
frequent_metrics, infrequent_metrics = self.calculate_metrics_for_categories(frequent_indices, infrequent_indices)
|
|
1090
|
-
logging.info(f"Metrics for frequent nodes (threshold={threshold}) in edge {edge}: {frequent_metrics}")
|
|
1091
|
-
logging.info(f"Metrics for infrequent nodes (threshold={threshold}) in edge {edge}: {infrequent_metrics}")
|
|
1092
|
-
|
|
1093
|
-
results["target_edges_by_frequency"][edge] = {
|
|
1094
|
-
"Frequent_metrics": frequent_metrics,
|
|
1095
|
-
"Infrequent_metrics": infrequent_metrics,
|
|
1096
|
-
"Threshold": threshold
|
|
1097
|
-
}
|
|
1098
|
-
|
|
1091
|
+
|
|
1099
1092
|
self.test_results = results
|
|
1100
1093
|
|
|
1101
|
-
with open(metrics_file, "
|
|
1102
|
-
|
|
1094
|
+
with open(metrics_file, "wb") as file:
|
|
1095
|
+
tomli_w.dump(results, file)
|
|
1103
1096
|
|
|
1104
1097
|
logging.info(f"Evaluation results stored in {metrics_file}")
|
|
1105
1098
|
|
|
@@ -1435,15 +1428,15 @@ class Architect(Module):
|
|
|
1435
1428
|
|
|
1436
1429
|
with torch.no_grad():
|
|
1437
1430
|
# TODO: use not the whole graphindices but the unique nodes instead
|
|
1438
|
-
for i in range(full_kg.graphindices.shape[1] //
|
|
1439
|
-
input = self.kg_train.get_encoder_input(full_kg.graphindices[:, i *
|
|
1431
|
+
for i in range(full_kg.graphindices.shape[1] // self.train_batch_size + 1):
|
|
1432
|
+
input = self.kg_train.get_encoder_input(full_kg.graphindices[:, i * self.train_batch_size : (i + 1) * self.train_batch_size].to(self.device), self.node_embeddings)
|
|
1440
1433
|
|
|
1441
1434
|
encoder_output: Dict[str, Tensor] = self.encoder(input.x_dict, input.edge_index)
|
|
1442
1435
|
|
|
1443
1436
|
for node_type, indices in input.mapping.items():
|
|
1444
1437
|
node_embeddings[indices] = encoder_output[node_type].cpu()
|
|
1445
1438
|
else:
|
|
1446
|
-
node_embeddings = self.node_embeddings.
|
|
1439
|
+
node_embeddings = self.node_embeddings[0].data.cpu()
|
|
1447
1440
|
|
|
1448
1441
|
edge_embeddings = self.edge_embeddings.weight.data.cpu()
|
|
1449
1442
|
|
|
@@ -1695,8 +1688,8 @@ class Architect(Module):
|
|
|
1695
1688
|
|
|
1696
1689
|
for edge_name in edge_indices:
|
|
1697
1690
|
# Get triplets associated with index
|
|
1698
|
-
|
|
1699
|
-
indices_to_keep = torch.nonzero(kg.edge_indices ==
|
|
1691
|
+
edge_index = kg.edge_to_index.get(edge_name)
|
|
1692
|
+
indices_to_keep = torch.nonzero(kg.edge_indices == edge_index, as_tuple = False).squeeze()
|
|
1700
1693
|
|
|
1701
1694
|
if indices_to_keep.numel() == 0:
|
|
1702
1695
|
continue # Skip to next edge if no triplet found
|
|
@@ -165,9 +165,7 @@ pretrained_embeddings = "auto"
|
|
|
165
165
|
# - Triplet Classification: Discriminates between true and false triplets
|
|
166
166
|
objective = "Link Prediction"
|
|
167
167
|
|
|
168
|
-
|
|
169
|
-
target_edges = []
|
|
170
|
-
thresholds = [10]
|
|
168
|
+
target_edges = []
|
|
171
169
|
|
|
172
170
|
[data_leakage]
|
|
173
171
|
# Set of options to run data leakage examination
|
|
@@ -1012,4 +1012,4 @@ class ComplEx(BilinearDecoder):
|
|
|
1012
1012
|
).sum(dim = 2)
|
|
1013
1013
|
|
|
1014
1014
|
else:
|
|
1015
|
-
raise ValueError("None of the embeddings have a shape adapted to be inferred. Shapes must be of 3 for `head_embeddings`, `tail_embeddings` and `edge_embeddings`.")
|
|
1015
|
+
raise ValueError("None of the embeddings have a shape adapted to be inferred. Shapes must be of 3 for `head_embeddings`, `tail_embeddings` and `edge_embeddings`.")
|
|
@@ -1540,4 +1540,4 @@ class TorusE(TranslationalDecoder):
|
|
|
1540
1540
|
|
|
1541
1541
|
candidates = candidates.unsqueeze(0).expand(batch_size, -1, -1)
|
|
1542
1542
|
|
|
1543
|
-
return head_embeddings, tail_embeddings, edge_embeddings_inferred, candidates
|
|
1543
|
+
return head_embeddings, tail_embeddings, edge_embeddings_inferred, candidates
|
|
@@ -17,35 +17,50 @@ from .utils import filter_scores
|
|
|
17
17
|
|
|
18
18
|
class Inference_KG(Dataset):
|
|
19
19
|
"""
|
|
20
|
+
<span style="color:#8B0000">
|
|
21
|
+
<strong>Description</strong>
|
|
22
|
+
</span>
|
|
23
|
+
|
|
20
24
|
Subset of a KG used for inference.
|
|
21
25
|
|
|
22
|
-
This class inherits from the PyTorch `utils.data.Dataset`
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
Arguments
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
26
|
+
This class inherits from the PyTorch [`utils.data.Dataset`](https://docs.pytorch.org/tutorials/beginner/basics/data_tutorial.html)
|
|
27
|
+
|
|
28
|
+
<span style="color:#8B0000">
|
|
29
|
+
<strong>Arguments</strong>
|
|
30
|
+
</span>
|
|
31
|
+
|
|
32
|
+
**first_index_tensor** *(torch.Tensor)*
|
|
33
|
+
: The first tensor with indices of the edges or nodes (from the knowledge graph).
|
|
34
|
+
|
|
35
|
+
**second_index_tensor** *(torch.Tensor)*
|
|
36
|
+
: The second tensor with indices of the edges or nodes (from the knowledge graph).
|
|
37
|
+
|
|
38
|
+
<span style="color:#8B0000">
|
|
39
|
+
<strong>Attributes</strong>
|
|
40
|
+
</span>
|
|
41
|
+
|
|
42
|
+
**first_index_tensor** *(torch.Tensor)*
|
|
43
|
+
: The first tensor with indices of the edges or nodes (from the knowledge graph).
|
|
44
|
+
|
|
45
|
+
**second_index_tensor** *(torch.Tensor)*
|
|
46
|
+
: The second tensor with indices of the edges or nodes (from the knowledge graph).
|
|
38
47
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
48
|
+
<span style="color:#8B0000">
|
|
49
|
+
<strong>Raises</strong>
|
|
50
|
+
</span>
|
|
51
|
+
|
|
52
|
+
**AssertionError**
|
|
53
|
+
: Both index tensors must be of the same size.
|
|
54
|
+
|
|
55
|
+
<span style="color:#8B0000">
|
|
56
|
+
<strong>Notes</strong>
|
|
57
|
+
</span>
|
|
58
|
+
|
|
59
|
+
Either both tensors are nodes, or they are node and edge.
|
|
60
|
+
|
|
61
|
+
The `__getitem__` method allows to call an `Inference_KG` object with an index, giving back a tuple containing the corresponding values of both tensors.
|
|
62
|
+
|
|
63
|
+
---
|
|
49
64
|
|
|
50
65
|
"""
|
|
51
66
|
def __init__(self,
|
|
@@ -69,17 +84,25 @@ class Inference_KG(Dataset):
|
|
|
69
84
|
|
|
70
85
|
class EdgeInference:
|
|
71
86
|
"""
|
|
87
|
+
<span style="color:#8B0000">
|
|
88
|
+
<strong>Description</strong>
|
|
89
|
+
</span>
|
|
90
|
+
|
|
72
91
|
Use trained embedding model to infer missing edges in triplets.
|
|
73
92
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
93
|
+
<span style="color:#8B0000">
|
|
94
|
+
<strong>Arguments</strong>
|
|
95
|
+
</span>
|
|
96
|
+
|
|
97
|
+
**kg** *(KnowledgeGraph)*
|
|
98
|
+
: Knowledge graph on which the inference will be done.
|
|
78
99
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
100
|
+
<span style="color:#8B0000">
|
|
101
|
+
<strong>Attributes</strong>
|
|
102
|
+
</span>
|
|
103
|
+
|
|
104
|
+
**kg** *(KnowledgeGraph)*
|
|
105
|
+
: Knowledge graph on which the inference will be done.
|
|
83
106
|
|
|
84
107
|
"""
|
|
85
108
|
def __init__(self, kg: KnowledgeGraph):
|
|
@@ -98,38 +121,59 @@ class EdgeInference:
|
|
|
98
121
|
verbose: bool = True,
|
|
99
122
|
**_):
|
|
100
123
|
"""
|
|
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
|
-
|
|
124
|
+
<span style="color:#8B0000">
|
|
125
|
+
<strong>Description</strong>
|
|
126
|
+
</span>
|
|
127
|
+
|
|
128
|
+
*Missing documentation*
|
|
129
|
+
% TODO.What_the_function_does_about_globally
|
|
130
|
+
|
|
131
|
+
<span style="color:#8B0000">
|
|
132
|
+
<strong>Arguments</strong>
|
|
133
|
+
</span>
|
|
134
|
+
|
|
135
|
+
**head_indices** *(torch.Tensor)*
|
|
136
|
+
: The indices of the head nodes (from the knowledge graph).
|
|
137
|
+
|
|
138
|
+
**tail_indices** *(torch.Tensor)*
|
|
139
|
+
: The indices of the tail nodes (from the knowledge graph).
|
|
140
|
+
|
|
141
|
+
**top_k** *(int, keyword-only)*
|
|
142
|
+
: Indicate the number of top predictions to return.
|
|
143
|
+
|
|
144
|
+
**batch_size** *(int, keyword-only)*
|
|
145
|
+
: Size of the current batch.
|
|
146
|
+
|
|
147
|
+
**encoder** *(DefaultEncoder or GNN, keyword-only)*
|
|
148
|
+
: Encoder model to embed the nodes. Deactivated with DefaultEncoder.
|
|
149
|
+
|
|
150
|
+
**decoder** *(BilinearDecoder or ConvolutionalDecoder or TranslationalDecoder)*
|
|
151
|
+
: Decoder model to evaluate.
|
|
152
|
+
|
|
153
|
+
**node_embeddings** *(nn.ParameterList, keyword-only)*
|
|
154
|
+
: A list containing all embeddings for each node type.
|
|
155
|
+
: keys: node type index
|
|
156
|
+
: values: tensors of shape (node_count, embedding_dimensions)
|
|
157
|
+
|
|
158
|
+
**edge_embeddings** *(nn.Embedding, keyword-only)*
|
|
159
|
+
: A tensor containing one embedding by edge type, of shape (edge_count, embedding_dimensions).
|
|
160
|
+
|
|
161
|
+
**verbose** *(bool, default to True, keyword-only)*
|
|
162
|
+
: Indicate whether a progress bar should be displayed during evaluation.
|
|
163
|
+
|
|
164
|
+
<span style="color:#8B0000">
|
|
165
|
+
<strong>Returns</strong>
|
|
166
|
+
</span>
|
|
167
|
+
|
|
168
|
+
**predictions** *(torch.Tensor)*
|
|
169
|
+
: *Missing documentation*
|
|
170
|
+
% TODO.What_that_variable_is_or_does
|
|
171
|
+
|
|
172
|
+
**scores** *(torch.Tensor, shape [batch_size, n])*
|
|
173
|
+
: Tensor with -Inf values for all true nodes/edges indices except the ones being predicted.
|
|
132
174
|
|
|
175
|
+
---
|
|
176
|
+
|
|
133
177
|
"""
|
|
134
178
|
with torch.no_grad():
|
|
135
179
|
device = edge_embeddings.weight.device
|
|
@@ -188,17 +232,25 @@ class EdgeInference:
|
|
|
188
232
|
|
|
189
233
|
class NodeInference:
|
|
190
234
|
"""
|
|
191
|
-
|
|
235
|
+
<span style="color:#8B0000">
|
|
236
|
+
<strong>Description</strong>
|
|
237
|
+
</span>
|
|
238
|
+
|
|
239
|
+
Use trained embedding model to infer missing nodes in triplets.
|
|
192
240
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
Knowledge graph on which the inference will be done.
|
|
241
|
+
<span style="color:#8B0000">
|
|
242
|
+
<strong>Arguments</strong>
|
|
243
|
+
</span>
|
|
197
244
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
245
|
+
**kg** *(KnowledgeGraph)*
|
|
246
|
+
: Knowledge graph on which the inference will be done.
|
|
247
|
+
|
|
248
|
+
<span style="color:#8B0000">
|
|
249
|
+
<strong>Attributes</strong>
|
|
250
|
+
</span>
|
|
251
|
+
|
|
252
|
+
**kg** *(KnowledgeGraph)*
|
|
253
|
+
: Knowledge graph on which the inference will be done.
|
|
202
254
|
|
|
203
255
|
"""
|
|
204
256
|
def __init__(self, kg: KnowledgeGraph):
|
|
@@ -219,41 +271,59 @@ class NodeInference:
|
|
|
219
271
|
verbose: bool = True,
|
|
220
272
|
**_):
|
|
221
273
|
"""
|
|
274
|
+
<span style="color:#8B0000">
|
|
275
|
+
<strong>Description</strong>
|
|
276
|
+
</span>
|
|
277
|
+
|
|
222
278
|
Predict the missing node of a triplet where either head and edge or edge and tail are known.
|
|
223
279
|
|
|
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
|
-
|
|
280
|
+
<span style="color:#8B0000">
|
|
281
|
+
<strong>Arguments</strong>
|
|
282
|
+
</span>
|
|
283
|
+
|
|
284
|
+
**node_indices** *(torch.Tensor)*
|
|
285
|
+
: The indices of nodes (from the knowledge graph).
|
|
286
|
+
|
|
287
|
+
**edge_indices** *(torch.Tensor)*
|
|
288
|
+
: The indices of edges (from the knowledge graph).
|
|
289
|
+
|
|
290
|
+
**top_k** *(int, keyword-only)*
|
|
291
|
+
: Indicate the number of top predictions to return.
|
|
292
|
+
|
|
293
|
+
**missing_triplet_part** *(Literal["head", "tail"], keyword-only)*
|
|
294
|
+
: String indicating if the missing nodes are the heads or the tails.
|
|
295
|
+
|
|
296
|
+
**batch_size** *(int, keyword-only)*
|
|
297
|
+
: Size of the current batch.
|
|
298
|
+
|
|
299
|
+
**encoder** *(DefaultEncoder or GNN, keyword-only)*
|
|
300
|
+
: Encoder model to embed the nodes. Deactivated with DefaultEncoder.
|
|
301
|
+
|
|
302
|
+
**decoder** *(BilinearDecoder or ConvolutionalDecoder or TranslationalDecoder, keyword-only)*
|
|
303
|
+
: Decoder model to evaluate.
|
|
304
|
+
|
|
305
|
+
**node_embeddings** *(nn.ParameterList, keyword-only)*
|
|
306
|
+
: A list containing all embeddings for each node type.
|
|
307
|
+
: keys: node type index
|
|
308
|
+
: values: tensors of shape (node_count, embedding_dimensions)
|
|
309
|
+
|
|
310
|
+
**edge_embeddings** *(nn.Embedding, keyword-only)*
|
|
311
|
+
: A tensor containing one embedding by edge type, of shape (edge_count, embedding_dimensions).
|
|
312
|
+
|
|
313
|
+
**verbose** *(bool, default to True, keyword-only)*
|
|
314
|
+
: Indicate whether a progress bar should be displayed during evaluation.
|
|
315
|
+
|
|
316
|
+
<span style="color:#8B0000">
|
|
317
|
+
<strong>Returns</strong>
|
|
318
|
+
</span>
|
|
319
|
+
|
|
320
|
+
**predictions** *(torch.Tensor)*
|
|
321
|
+
% TODO.What_that_variable_is_or_does
|
|
322
|
+
*Missing documentation*
|
|
323
|
+
|
|
324
|
+
**scores** *(torch.Tensor, shape [batch_size, n])*
|
|
325
|
+
: Tensor with -Inf values for all true nodes/edges indices except the ones being predicted.
|
|
326
|
+
|
|
257
327
|
"""
|
|
258
328
|
with torch.no_grad():
|
|
259
329
|
device = edge_embeddings.weight.device
|
|
@@ -6,7 +6,7 @@ Knowledge Graph preprocessing functions to run before any training procedure.
|
|
|
6
6
|
import logging
|
|
7
7
|
import pickle
|
|
8
8
|
from pathlib import Path
|
|
9
|
-
from typing import Tuple, List, Set
|
|
9
|
+
from typing import Tuple, List, Set, Literal
|
|
10
10
|
|
|
11
11
|
import pandas as pd
|
|
12
12
|
|
|
@@ -468,31 +468,32 @@ def clean_datasets( kg_train: KnowledgeGraph,
|
|
|
468
468
|
|
|
469
469
|
return kg_train
|
|
470
470
|
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
471
|
+
def clean_cartesians(
|
|
472
|
+
kg_train: KnowledgeGraph,
|
|
473
|
+
kg_test: KnowledgeGraph,
|
|
474
|
+
known_cartesian: List[int],
|
|
475
|
+
node_position: Literal["head", "tail"] = "head"
|
|
476
|
+
) -> Tuple[KnowledgeGraph, KnowledgeGraph]:
|
|
477
477
|
"""
|
|
478
|
-
Transfer cartesian product triplets from
|
|
478
|
+
Transfer cartesian product triplets from train set to test set to prevent data leakage.
|
|
479
479
|
For each node (head or tail) involved in a cartesian product edge in the test set,
|
|
480
|
-
all corresponding triplets in the
|
|
480
|
+
all corresponding triplets in the train set are moved to the test set.
|
|
481
481
|
|
|
482
482
|
Arguments
|
|
483
483
|
---------
|
|
484
|
-
|
|
484
|
+
kg_train: KnowledgeGraph
|
|
485
485
|
Train set knowledge graph to be cleaned.
|
|
486
486
|
Will be modified by removing cartesian product triplets.
|
|
487
|
-
|
|
487
|
+
kg_test: KnowledgeGraph
|
|
488
488
|
Test set knowledge graph to be augmented.
|
|
489
489
|
Will receive the transferred cartesian product triplets.
|
|
490
|
-
known_cartesian:
|
|
490
|
+
known_cartesian: list
|
|
491
491
|
List of edge indices that represent cartesian product relationships.
|
|
492
|
-
These are edges where if (head,
|
|
493
|
-
for many other tail
|
|
494
|
-
|
|
492
|
+
These are edges where if (head, edge, tail_1) exists, then (head, edge, tail_2) likely exists
|
|
493
|
+
for many other tail node tail_2 (or vice versa for tail-based cartesian products).
|
|
494
|
+
node_position: Literal["head", "tail"], optional
|
|
495
495
|
Either "head" or "tail" to specify which node type to consider for cartesian products.
|
|
496
|
+
Default is "head".
|
|
496
497
|
|
|
497
498
|
Returns
|
|
498
499
|
-------
|
|
@@ -502,57 +503,40 @@ def clean_cartesians(kg_first: KnowledgeGraph,
|
|
|
502
503
|
Augmented test set knowledge graph, with the transferred triplets added.
|
|
503
504
|
|
|
504
505
|
"""
|
|
505
|
-
assert
|
|
506
|
+
assert node_position in ["head", "tail"], "node_position must be either 'head' or 'tail'"
|
|
506
507
|
|
|
507
508
|
for edge_index in known_cartesian:
|
|
508
|
-
# Find all nodes in test set that participate in the cartesian
|
|
509
|
-
mask = (
|
|
510
|
-
if
|
|
511
|
-
|
|
509
|
+
# Find all nodes in test set that participate in the cartesian edge
|
|
510
|
+
mask = (kg_test.edge_indices == edge_index)
|
|
511
|
+
if node_position == "head":
|
|
512
|
+
cartesian_nodes = kg_test.head_indices[mask].view(-1,1)
|
|
512
513
|
# Find matching triplets in train set with same head and edge
|
|
513
|
-
|
|
514
|
-
for
|
|
515
|
-
mask = (
|
|
516
|
-
|
|
517
|
-
if
|
|
518
|
-
|
|
519
|
-
|
|
514
|
+
all_triplet_indices_to_move = []
|
|
515
|
+
for node in cartesian_nodes:
|
|
516
|
+
mask = (kg_train.head_indices == node) & (kg_train.edge_indices == edge_index)
|
|
517
|
+
triplet_indices = mask.nonzero().squeeze()
|
|
518
|
+
if triplet_indices.dim() == 0:
|
|
519
|
+
triplet_indices = triplet_indices.unsqueeze(0)
|
|
520
|
+
all_triplet_indices_to_move.extend(triplet_indices.tolist())
|
|
520
521
|
else: # tail
|
|
521
|
-
|
|
522
|
+
cartesian_nodes = kg_test.tail_indices[mask].view(-1,1)
|
|
522
523
|
# Find matching triplets in train set with same tail and edge
|
|
523
|
-
|
|
524
|
-
for
|
|
525
|
-
mask = (
|
|
526
|
-
|
|
527
|
-
if
|
|
528
|
-
|
|
529
|
-
|
|
524
|
+
all_triplet_indices_to_move = []
|
|
525
|
+
for node in cartesian_nodes:
|
|
526
|
+
mask = (kg_train.tail_indices == node) & (kg_train.edge_indices == edge_index)
|
|
527
|
+
triplet_indices = mask.nonzero().squeeze()
|
|
528
|
+
if triplet_indices.dim() == 0:
|
|
529
|
+
triplet_indices = triplet_indices.unsqueeze(0)
|
|
530
|
+
all_triplet_indices_to_move.extend(triplet_indices.tolist())
|
|
530
531
|
|
|
531
|
-
if
|
|
532
|
+
if all_triplet_indices_to_move:
|
|
532
533
|
# Extract the triplets to be transferred
|
|
533
|
-
triplets_to_move =
|
|
534
|
-
kg_first.head_indices[all_indices_to_move],
|
|
535
|
-
kg_first.edge_indices[all_indices_to_move],
|
|
536
|
-
kg_first.tail_indices[all_indices_to_move]
|
|
537
|
-
], dim = 1)
|
|
534
|
+
triplets_to_move = kg_train.graphindices[:,all_triplet_indices_to_move]
|
|
538
535
|
|
|
539
536
|
# Remove identified triplets from train set
|
|
540
|
-
|
|
537
|
+
kg_train = kg_train.remove_triplets(torch.tensor(all_triplet_indices_to_move, dtype = torch.long))
|
|
541
538
|
|
|
542
539
|
# Add transferred triplets to test set while preserving KG structure
|
|
543
|
-
|
|
544
|
-
"heads": torch.cat([kg_second.head_indices, triplets_to_move[:, 0]]),
|
|
545
|
-
"tails": torch.cat([kg_second.tail_indices, triplets_to_move[:, 2]]),
|
|
546
|
-
"edges": torch.cat([kg_second.edge_indices, triplets_to_move[:, 1]]),
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
kg_second = kg_second.__class__(
|
|
550
|
-
kg = kg_second_dictionnary,
|
|
551
|
-
node_to_index = kg_second.node_to_index,
|
|
552
|
-
edge_to_index = kg_first.edge_to_index,
|
|
553
|
-
dict_of_heads = kg_second.dict_of_heads,
|
|
554
|
-
dict_of_tails = kg_second.dict_of_tails,
|
|
555
|
-
dict_of_rels = kg_second.dict_of_rels
|
|
556
|
-
)
|
|
540
|
+
kg_test.add_triplets(triplets_to_move)
|
|
557
541
|
|
|
558
|
-
return
|
|
542
|
+
return kg_train, kg_test
|
|
@@ -11,7 +11,7 @@ The modifications are licensed under the BSD license according to the source lic
|
|
|
11
11
|
|
|
12
12
|
"""
|
|
13
13
|
|
|
14
|
-
from typing import Dict, Set, Tuple, List
|
|
14
|
+
from typing import Dict, Set, Tuple, List, Optional
|
|
15
15
|
from collections import defaultdict
|
|
16
16
|
|
|
17
17
|
import torch
|
|
@@ -36,7 +36,7 @@ class NegativeSampler:
|
|
|
36
36
|
|
|
37
37
|
def corrupt_batch( self,
|
|
38
38
|
batch: torch.Tensor,
|
|
39
|
-
negative_triplet_count = None
|
|
39
|
+
negative_triplet_count: Optional[int] = None
|
|
40
40
|
) -> Tensor:
|
|
41
41
|
"""
|
|
42
42
|
For each true triplet, produce a corrupted one not different from
|
|
@@ -104,7 +104,7 @@ class UniformNegativeSampler(NegativeSampler):
|
|
|
104
104
|
"""
|
|
105
105
|
def __init__(self,
|
|
106
106
|
knowledge_graph: KnowledgeGraph,
|
|
107
|
-
negative_triplet_count = 1):
|
|
107
|
+
negative_triplet_count: int = 1):
|
|
108
108
|
|
|
109
109
|
self.knowledge_graph = knowledge_graph
|
|
110
110
|
self.index_to_node_type: Dict[int, str] = {value: key for key, value in self.knowledge_graph.node_type_to_index.items()}
|
|
@@ -115,7 +115,7 @@ class UniformNegativeSampler(NegativeSampler):
|
|
|
115
115
|
|
|
116
116
|
def corrupt_batch( self,
|
|
117
117
|
batch: torch.Tensor,
|
|
118
|
-
negative_triplet_count = None
|
|
118
|
+
negative_triplet_count: Optional[int] = None
|
|
119
119
|
) -> Tensor:
|
|
120
120
|
"""
|
|
121
121
|
For each true triplet, produce a corrupted one not different from
|
|
@@ -141,6 +141,8 @@ class UniformNegativeSampler(NegativeSampler):
|
|
|
141
141
|
"""
|
|
142
142
|
device = batch.device
|
|
143
143
|
batch_size = batch.shape[1]
|
|
144
|
+
negative_triplet_count = negative_triplet_count or self.negative_triplet_count
|
|
145
|
+
|
|
144
146
|
negative_triplet_heads = batch[0].repeat(negative_triplet_count)
|
|
145
147
|
negative_triplet_tails = batch[1].repeat(negative_triplet_count)
|
|
146
148
|
negative_triplet_edges = batch[2].repeat(negative_triplet_count)
|
|
@@ -149,10 +151,10 @@ class UniformNegativeSampler(NegativeSampler):
|
|
|
149
151
|
device = device) / 2).double()
|
|
150
152
|
corrupted_head_count = int(mask.sum().item())
|
|
151
153
|
|
|
152
|
-
negative_triplet_heads[mask == 1] = randint(1, self.node_count,
|
|
154
|
+
negative_triplet_heads[mask == 1] = randint(1, self.knowledge_graph.node_count,
|
|
153
155
|
(corrupted_head_count,),
|
|
154
156
|
device = device)
|
|
155
|
-
negative_triplet_tails[mask == 0] = randint(1, self.node_count,
|
|
157
|
+
negative_triplet_tails[mask == 0] = randint(1, self.knowledge_graph.node_count,
|
|
156
158
|
(batch_size * negative_triplet_count - corrupted_head_count,),
|
|
157
159
|
device = device)
|
|
158
160
|
|
|
@@ -274,7 +276,7 @@ class BernoulliNegativeSampler(NegativeSampler):
|
|
|
274
276
|
|
|
275
277
|
def corrupt_batch( self,
|
|
276
278
|
batch: torch.LongTensor,
|
|
277
|
-
negative_triplet_count: int =
|
|
279
|
+
negative_triplet_count: int | None = None):
|
|
278
280
|
"""
|
|
279
281
|
For each true triplet, produce a corrupted one not different from
|
|
280
282
|
any other true triplet. If `heads` and `tails` are cuda objects,
|
|
@@ -286,7 +288,7 @@ class BernoulliNegativeSampler(NegativeSampler):
|
|
|
286
288
|
Tensor containing the integer key of heads, tails, edges and triplets
|
|
287
289
|
of the edges in the current batch.
|
|
288
290
|
Here, batch_size is batch.shape[1].
|
|
289
|
-
negative_triplet_count: int, optional, default to
|
|
291
|
+
negative_triplet_count: int, optional, default to None
|
|
290
292
|
Number of negative samples to create from each triplet.
|
|
291
293
|
|
|
292
294
|
Returns
|
|
@@ -299,6 +301,9 @@ class BernoulliNegativeSampler(NegativeSampler):
|
|
|
299
301
|
"""
|
|
300
302
|
device = batch.device
|
|
301
303
|
batch_size = batch.shape[1]
|
|
304
|
+
|
|
305
|
+
negative_triplet_count = negative_triplet_count or self.negative_triplet_count
|
|
306
|
+
|
|
302
307
|
negative_triplet_heads = batch[0].repeat(negative_triplet_count)
|
|
303
308
|
negative_triplet_tails = batch[1].repeat(negative_triplet_count)
|
|
304
309
|
negative_triplet_edges = batch[2]
|
|
@@ -468,7 +473,7 @@ class PositionalNegativeSampler(BernoulliNegativeSampler):
|
|
|
468
473
|
|
|
469
474
|
def corrupt_batch( self,
|
|
470
475
|
batch: Tensor,
|
|
471
|
-
|
|
476
|
+
negative_triplet_count: Optional[int] = None
|
|
472
477
|
) -> Tensor:
|
|
473
478
|
"""
|
|
474
479
|
For each true triplet, produce a corrupted one not different from
|
|
@@ -683,7 +683,7 @@ def get_average_heads_per_tail( graphindices: Tensor
|
|
|
683
683
|
Returns
|
|
684
684
|
-------
|
|
685
685
|
average_heads_per_tail: Dict[float,float]
|
|
686
|
-
Keys:
|
|
686
|
+
Keys: edge indices
|
|
687
687
|
Values: average number of heads per tail
|
|
688
688
|
|
|
689
689
|
"""
|
|
@@ -708,7 +708,7 @@ def get_average_tails_per_head( graphindices: Tensor
|
|
|
708
708
|
Returns
|
|
709
709
|
-------
|
|
710
710
|
average_tails_per_head: Dict[float,float]
|
|
711
|
-
Keys:
|
|
711
|
+
Keys: edge indices; Values: average number of tails per head
|
|
712
712
|
|
|
713
713
|
"""
|
|
714
714
|
dataframe = pd.DataFrame(graphindices.T.cpu().numpy(), columns = ["head", "tail", "edge", "triplet"])
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|