KGATE 0.2.0__tar.gz → 0.2.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: KGATE
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Knowledge Graph Autoencoder Training Environment, bridging PyG encoders and TorchKGE decoders.
5
5
  License: MIT
6
6
  Keywords: Knowledge Graph,Knowledge Graph Embedding,Autoencoder,Machine Learning,Link Prediction
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "KGATE"
3
- version = "0.2.0"
3
+ version = "0.2.2"
4
4
  description = "Knowledge Graph Autoencoder Training Environment, bridging PyG encoders and TorchKGE decoders."
5
5
  authors = [
6
6
  {name = "Benjamin Loire", email = "benjamin.loire@univ-amu.fr"},
@@ -0,0 +1,5 @@
1
+ from .knowledgegraph import KnowledgeGraph
2
+ from .kgate import Architect
3
+ from .utils import init_embedding, read_training_metrics
4
+ from .grid_search import run_grid_search
5
+ from .evaluators import LinkPredictionEvaluator, TripletClassificationEvaluator
@@ -86,7 +86,7 @@ n_filters = 3
86
86
  # Supported options are :
87
87
  # - Positional : proposed by Socher et al. 2011, replaces either the head or tail of a triplet by another entity in the same place with the same relation.
88
88
  # - Uniform : proposed by Bordes et al. 2013, replaces either the head or tail by another entity at random following an uniform distribution.
89
- # - Bernouilli : proposed by Wang et al. 2014, replaces either the head or tail using probabilities taking relations into account.
89
+ # - Bernoulli : proposed by Wang et al. 2014, replaces either the head or tail using probabilities taking relations into account.
90
90
  # - Mixed : proposed by Brière et al. 2025, combines the three negative samplers above, sampling n_neg negative samples for each triplet.
91
91
  name = "Positional"
92
92
 
@@ -19,7 +19,7 @@ class ConvKB(ConvKBModel):
19
19
 
20
20
  concat = cat((h,r,t), dim=1)
21
21
 
22
- return self.output(self.convlayer(concat)).reshape(b_size, -1)[:, 1]
22
+ return self.output(self.convlayer(concat).reshape(b_size, -1))[:, 1]
23
23
 
24
24
  def get_embeddings(self):
25
25
  return None
@@ -47,5 +47,6 @@ class ConvKB(ConvKBModel):
47
47
  candidates = relation_embeddings.weight.data
48
48
 
49
49
  candidates = candidates.unsqueeze(0).expand(b_size, -1, -1)
50
+ candidates = candidates.view(b_size, -1, 1, self.emb_dim)
50
51
 
51
52
  return h, t, r, candidates
@@ -14,22 +14,22 @@ from tqdm.autonotebook import tqdm
14
14
 
15
15
  import torch.nn as nn
16
16
 
17
- from torchkge.evaluation import LinkPredictionEvaluator, TripletClassificationEvaluator
17
+ import torchkge.evaluation as eval
18
18
  from torchkge.exceptions import NotYetEvaluatedError
19
- from torchkge.utils import get_rank, filter_scores
19
+ from torchkge.utils import get_rank
20
20
  from torchkge.data_structures import SmallKG
21
21
  from torchkge.models import Model
22
22
 
23
23
  from torch_geometric.utils import k_hop_subgraph
24
24
 
25
25
  from .knowledgegraph import KnowledgeGraph
26
- from .utils import HeteroMappings
26
+ from .utils import filter_scores
27
27
  from .samplers import PositionalNegativeSampler
28
28
  from .encoders import GNN, DefaultEncoder
29
29
 
30
30
  from typing import Dict, Literal
31
31
 
32
- class KLinkPredictionEvaluator(LinkPredictionEvaluator):
32
+ class LinkPredictionEvaluator(eval.LinkPredictionEvaluator):
33
33
  """Evaluate performance of given embedding using link prediction method.
34
34
 
35
35
  References
@@ -85,6 +85,7 @@ class KLinkPredictionEvaluator(LinkPredictionEvaluator):
85
85
  relation_embeddings: nn.Embedding,
86
86
  verbose: bool=True):
87
87
  """
88
+ Run the Link Prediction evaluation.
88
89
 
89
90
  Parameters
90
91
  ----------
@@ -114,16 +115,13 @@ class KLinkPredictionEvaluator(LinkPredictionEvaluator):
114
115
  device = relation_embeddings.weight.device
115
116
  use_cuda = relation_embeddings.weight.is_cuda
116
117
 
117
- if use_cuda:
118
- dataloader = DataLoader(knowledge_graph, batch_size=b_size)
119
- self.rank_true_heads = self.rank_true_heads.cuda()
120
- self.rank_true_tails = self.rank_true_tails.cuda()
121
- self.filt_rank_true_heads = self.filt_rank_true_heads.cuda()
122
- self.filt_rank_true_tails = self.filt_rank_true_tails.cuda()
123
- edgelist = knowledge_graph.edgelist.cuda()
124
- else:
125
- dataloader = DataLoader(knowledge_graph, batch_size=b_size)
126
-
118
+ dataloader = DataLoader(knowledge_graph, batch_size=b_size)
119
+ self.rank_true_heads = self.rank_true_heads.to(device)
120
+ self.rank_true_tails = self.rank_true_tails.to(device)
121
+ self.filt_rank_true_heads = self.filt_rank_true_heads.to(device)
122
+ self.filt_rank_true_tails = self.filt_rank_true_tails.to(device)
123
+ edgelist = knowledge_graph.edgelist.to(device)
124
+
127
125
  embeddings = node_embeddings.weight.data
128
126
 
129
127
  for i, batch in tqdm(enumerate(dataloader), total=len(dataloader),
@@ -161,8 +159,8 @@ class KLinkPredictionEvaluator(LinkPredictionEvaluator):
161
159
  scores = scores,
162
160
  edgelist = self.full_edgelist.to(device),
163
161
  missing = "tail",
164
- ent_idx=h_idx,
165
- r_idx=r_idx,
162
+ idx_1=h_idx,
163
+ idx_2=r_idx,
166
164
  true_idx=t_idx
167
165
  )
168
166
  self.rank_true_tails[i * b_size: (i + 1) * b_size] = get_rank(scores, t_idx).detach()
@@ -173,8 +171,8 @@ class KLinkPredictionEvaluator(LinkPredictionEvaluator):
173
171
  scores = scores,
174
172
  edgelist = self.full_edgelist.to(device),
175
173
  missing = "head",
176
- ent_idx=t_idx,
177
- r_idx=r_idx,
174
+ idx_1=t_idx,
175
+ idx_2=r_idx,
178
176
  true_idx=h_idx
179
177
  )
180
178
  self.rank_true_heads[i * b_size: (i + 1) * b_size] = get_rank(scores, h_idx).detach()
@@ -188,28 +186,8 @@ class KLinkPredictionEvaluator(LinkPredictionEvaluator):
188
186
  self.filt_rank_true_heads = self.filt_rank_true_heads.cpu()
189
187
  self.filt_rank_true_tails = self.filt_rank_true_tails.cpu()
190
188
 
191
- def filter_scores(scores, edgelist: Tensor, missing: Literal["head","tail"], ent_idx: Tensor, r_idx: Tensor, true_idx: Tensor):
192
- b_size = scores.shape[0]
193
- filt_scores = scores.clone()
194
-
195
- e_idx = 0 if missing == "tail" else 1
196
- m_idx = 1 - e_idx
197
-
198
- ent_mask = torch.isin(edgelist[e_idx], ent_idx)
199
- rel_mask = torch.isin(edgelist[2], r_idx)
200
- for i in range(b_size):
201
- true_mask = torch.isin(edgelist[m_idx], true_idx[i])
202
- true_targets = edgelist[m_idx,
203
- ent_mask &
204
- rel_mask &
205
- ~ true_mask
206
- ]
207
- filt_scores[i, true_targets] = - float('Inf')
208
-
209
- return filt_scores
210
-
211
189
 
212
- class KTripletClassificationEvaluator(TripletClassificationEvaluator):
190
+ class TripletClassificationEvaluator(eval.TripletClassificationEvaluator):
213
191
  """Evaluate performance of given embedding using triplet classification
214
192
  method.
215
193
 
@@ -1,6 +1,6 @@
1
1
  import optuna
2
2
  from .kgate import Architect
3
- from .data_structures import KGATEGraph
3
+ from .knowledgegraph import KnowledgeGraph
4
4
  from .utils import parse_config
5
5
  import pandas as pd
6
6
  from torchkge import KnowledgeGraph
@@ -14,7 +14,7 @@ logging.basicConfig(
14
14
  format="%(asctime)s - %(levelname)s - %(message)s"
15
15
  )
16
16
 
17
- def run_grid_search(config_path: str, n_trials: int = 10, kg: Tuple[KGATEGraph,KGATEGraph,KGATEGraph] | KnowledgeGraph | None = None, df: pd.DataFrame | None = None):
17
+ def run_grid_search(config_path: str, n_trials: int = 10, kg: Tuple[KnowledgeGraph,KnowledgeGraph,KnowledgeGraph] | KnowledgeGraph | None = None, df: pd.DataFrame | None = None):
18
18
  """Run a grid search hyperparameter optimization according to the given configuration.
19
19
 
20
20
  To register a hyperparameter in the grid search optimization, set it as a list in the configuration.
@@ -0,0 +1,232 @@
1
+ import torchkge.inference as infer
2
+ from torchkge.models import Model
3
+ from tqdm.autonotebook import tqdm
4
+ from torch import tensor, nn, Tensor
5
+ import torch
6
+ from typing import Dict, Literal
7
+ from .utils import filter_scores
8
+ from .encoders import DefaultEncoder, GNN
9
+ from .knowledgegraph import KnowledgeGraph
10
+ from torch.utils.data import DataLoader, Dataset
11
+ from torch_geometric.utils import k_hop_subgraph
12
+
13
+ class Inference_KG(Dataset):
14
+ def __init__(self, idx_1:Tensor, idx_2:Tensor):
15
+ assert idx_1.size() == idx_2.size(), "Both index tensors must be of the same size for inference."
16
+ self.id1 = idx_1
17
+ self.id2 = idx_2
18
+
19
+ def __len__(self):
20
+ return self.id1.size(0)
21
+
22
+ def __getitem__(self, idx: int):
23
+ return (self.id1[idx], self.id2[idx])
24
+
25
+
26
+ class RelationInference(infer.RelationInference):
27
+ """Use trained embedding model to infer missing relations in triples.
28
+
29
+ Parameters
30
+ ----------
31
+ model: torchkge.models.interfaces.Model
32
+ Embedding model inheriting from the right interface.
33
+ entities1: `torch.Tensor`, shape: (n_facts), dtype: `torch.long`
34
+ List of the indices of known entities 1.
35
+ entities2: `torch.Tensor`, shape: (n_facts), dtype: `torch.long`
36
+ List of the indices of known entities 2.
37
+ top_k: int
38
+ Indicates the number of top predictions to return.
39
+ dictionary: dict, optional (default=None)
40
+ Dictionary of possible relations. It is used to filter predictions
41
+ that are known to be True in the training set in order to return
42
+ only new facts.
43
+
44
+ Attributes
45
+ ----------
46
+ model: torchkge.models.interfaces.Model
47
+ Embedding model inheriting from the right interface.
48
+ entities1: `torch.Tensor`, shape: (n_facts), dtype: `torch.long`
49
+ List of the indices of known entities 1.
50
+ entities2: `torch.Tensor`, shape: (n_facts), dtype: `torch.long`
51
+ List of the indices of known entities 2.
52
+ top_k: int
53
+ Indicates the number of top predictions to return.
54
+ dictionary: dict, optional (default=None)
55
+ Dictionary of possible relations. It is used to filter predictions
56
+ that are known to be True in the training set in order to return
57
+ only new facts.
58
+ predictions: `torch.Tensor`, shape: (n_facts, self.top_k), dtype: `torch.long`
59
+ List of the indices of predicted relations for each test fact.
60
+ scores: `torch.Tensor`, shape: (n_facts, self.top_k), dtype: `torch.float`
61
+ List of the scores of resulting triples for each test fact.
62
+ """
63
+
64
+ def __init__(self, knowledge_graph: KnowledgeGraph):
65
+ self.knowledge_graph = knowledge_graph
66
+
67
+ def evaluate(self,
68
+ h_idx: Tensor,
69
+ t_idx: Tensor,
70
+ *,
71
+ top_k: int,
72
+ b_size: int,
73
+ encoder: DefaultEncoder | GNN,
74
+ decoder: Model,
75
+ node_embeddings: nn.ParameterList | nn.Embedding,
76
+ relation_embeddings: nn.Embedding,
77
+ verbose:bool=True,
78
+ **_):
79
+
80
+ with torch.no_grad():
81
+ use_cuda = relation_embeddings.weight.is_cuda
82
+ device = relation_embeddings.weight.device
83
+
84
+ inference_kg = Inference_KG(h_idx, t_idx)
85
+
86
+ dataloader = DataLoader(inference_kg, batch_size=b_size)
87
+
88
+ predictions = torch.empty(size=(len(h_idx), top_k), device=device).long()
89
+ embeddings = node_embeddings.weight.data
90
+
91
+ for i, batch in tqdm(enumerate(dataloader), total=len(dataloader),
92
+ unit="batch", disable=(not verbose),
93
+ desc="Inference"):
94
+ h_idx, t_idx = batch[0], batch[1]
95
+
96
+ if isinstance(encoder, GNN):
97
+ seed_nodes = batch.unique()
98
+ num_hops = encoder.n_layers
99
+ edge_index = self.knowledge_graph.edge_index
100
+
101
+ _,_,_, edge_mask = k_hop_subgraph(
102
+ node_idx = seed_nodes,
103
+ num_hops = num_hops,
104
+ edge_index = edge_index
105
+ )
106
+
107
+ input = self.knowledge_graph.get_encoder_input(self.knowledge_graph.edgelist[:, edge_mask], node_embeddings)
108
+ encoder_output: Dict[str, Tensor] = encoder(input.x_dict, input.edge_index)
109
+
110
+ for node_type, idx in input.mapping.items():
111
+ embeddings[idx] = encoder_output[node_type]
112
+
113
+
114
+
115
+ h_emb, t_emb, _, candidates = decoder.inference_prepare_candidates(h_idx = h_idx,
116
+ t_idx = t_idx,
117
+ r_idx = tensor([]).long(),
118
+ node_embeddings = embeddings,
119
+ relation_embeddings = relation_embeddings,
120
+ entities=False)
121
+ scores = decoder.inference_scoring_function(h_emb, t_emb, candidates)
122
+
123
+ scores = filter_scores(scores, self.knowledge_graph.edgelist, "rel", h_idx, t_idx, None)
124
+
125
+ scores, indices = scores.sort(descending=True)
126
+
127
+ predictions[i * b_size: (i + 1) * b_size] = indices[:, :top_k]
128
+ scores[i * b_size, (i + 1) * b_size] = scores[:, :top_k]
129
+
130
+ return predictions.cpu(), scores.cpu()
131
+
132
+ class EntityInference(infer.EntityInference):
133
+ """Use trained embedding model to infer missing entities in triples.
134
+
135
+ Attributes
136
+ ----------
137
+ model: torchkge.models.interfaces.Model
138
+ Embedding model inheriting from the right interface.
139
+ known_entities: `torch.Tensor`, shape: (n_facts), dtype: `torch.long`
140
+ List of the indices of known entities.
141
+ known_relations: `torch.Tensor`, shape: (n_facts), dtype: `torch.long`
142
+ List of the indices of known relations.
143
+ top_k: int
144
+ Indicates the number of top predictions to return.
145
+ missing: str
146
+ String indicating if the missing entities are the heads or the tails.
147
+ dictionary: dict, optional (default=None)
148
+ Dictionary of possible heads or tails (depending on the value of `missing`).
149
+ It is used to filter predictions that are known to be True in the training set
150
+ in order to return only new facts.
151
+ predictions: `torch.Tensor`, shape: (n_facts, self.top_k), dtype: `torch.long`
152
+ List of the indices of predicted entities for each test fact.
153
+ scores: `torch.Tensor`, shape: (n_facts, self.top_k), dtype: `torch.float`
154
+ List of the scores of resulting triples for each test fact.
155
+
156
+ """
157
+ def __init__(self, knowledge_graph: KnowledgeGraph):
158
+ self.knowledge_graph = knowledge_graph
159
+
160
+ def evaluate(self,
161
+ ent_idx: Tensor,
162
+ rel_idx: Tensor,
163
+ *,
164
+ top_k: int,
165
+ missing: Literal["head","tail"],
166
+ b_size: int,
167
+ encoder: DefaultEncoder | GNN,
168
+ decoder: Model,
169
+ node_embeddings: nn.Embedding | nn.ParameterList,
170
+ relation_embeddings: nn.Embedding,
171
+ verbose:bool=True,
172
+ **_):
173
+ with torch.no_grad():
174
+ device = relation_embeddings.weight.device
175
+
176
+ inference_kg = Inference_KG(ent_idx, rel_idx)
177
+
178
+ dataloader = DataLoader(inference_kg, batch_size=b_size)
179
+
180
+ predictions = torch.empty(size=(len(ent_idx), top_k), device=device).long()
181
+ scores = torch.empty(size=(len(ent_idx), top_k), device=device).long()
182
+ embeddings = node_embeddings.weight.data
183
+
184
+ for i, batch in tqdm(enumerate(dataloader), total=len(dataloader),
185
+ unit="batch", disable=(not verbose),
186
+ desc="Inference"):
187
+
188
+ known_ents, known_rels = batch[0], batch[1]
189
+
190
+ if isinstance(encoder, GNN):
191
+ seed_nodes = known_ents.unique()
192
+ num_hops = encoder.n_layers
193
+ edge_index = self.knowledge_graph.edge_index
194
+
195
+ _,_,_, edge_mask = k_hop_subgraph(
196
+ node_idx = seed_nodes,
197
+ num_hops = num_hops,
198
+ edge_index = edge_index
199
+ )
200
+
201
+ input = self.knowledge_graph.get_encoder_input(self.knowledge_graph.edgelist[:, edge_mask], node_embeddings)
202
+ encoder_output: Dict[str, Tensor] = encoder(input.x_dict, input.edge_index)
203
+
204
+ for node_type, idx in input.mapping.items():
205
+ embeddings[idx] = encoder_output[node_type]
206
+
207
+ if missing == "head":
208
+ _, t_emb, rel_emb, candidates = decoder.inference_prepare_candidates(h_idx = tensor([], device=device).long(),
209
+ t_idx = known_ents.to(device),
210
+ r_idx = known_rels.to(device),
211
+ node_embeddings = embeddings,
212
+ relation_embeddings = relation_embeddings,
213
+ entities=True)
214
+ batch_scores = decoder.inference_scoring_function(candidates, t_emb, rel_emb)
215
+ else:
216
+ h_emb, _, rel_emb, candidates = decoder.inference_prepare_candidates(h_idx = known_ents.to(device),
217
+ t_idx = tensor([], device=device).long(),
218
+ r_idx = known_rels.to(device),
219
+ node_embeddings = embeddings,
220
+ relation_embeddings = relation_embeddings,
221
+ entities=True)
222
+ batch_scores = decoder.inference_scoring_function(h_emb, candidates, rel_emb)
223
+
224
+ batch_scores = filter_scores(batch_scores, self.knowledge_graph.edgelist, missing, known_ents, known_rels, None)
225
+
226
+ batch_scores, indices = batch_scores.sort(descending=True)
227
+ b_size = min(b_size, len(batch_scores))
228
+
229
+ predictions[i * b_size: (i+1)*b_size] = indices[:, :top_k]
230
+ scores[i*b_size: (i+1)*b_size] = batch_scores[:, :top_k]
231
+
232
+ return predictions.cpu(), scores.cpu()
@@ -9,14 +9,14 @@ from torch import tensor, long, stack, Tensor
9
9
  from torch.nn import Parameter
10
10
  from torch.nn.functional import normalize
11
11
  from torch.utils.data import DataLoader
12
- from .utils import parse_config, load_knowledge_graph, set_random_seeds, find_best_model, HeteroMappings, init_embedding, plot_learning_curves
12
+ from .utils import parse_config, load_knowledge_graph, set_random_seeds, find_best_model, merge_kg, init_embedding, plot_learning_curves
13
13
  from .preprocessing import prepare_knowledge_graph, SUPPORTED_SEPARATORS
14
14
  from .encoders import *
15
15
  from .decoders import *
16
16
  from .knowledgegraph import KnowledgeGraph
17
17
  from .samplers import PositionalNegativeSampler, BernoulliNegativeSampler, UniformNegativeSampler, MixedNegativeSampler
18
- from .evaluators import KLinkPredictionEvaluator, KTripletClassificationEvaluator
19
- from .inference import KEntityInference, KRelationInference
18
+ from .evaluators import LinkPredictionEvaluator, TripletClassificationEvaluator
19
+ from .inference import EntityInference, RelationInference
20
20
  from torchkge.utils import MarginLoss, BinaryCrossEntropyLoss
21
21
  import logging
22
22
  import warnings
@@ -169,7 +169,7 @@ class Architect(Model):
169
169
  self.optimizer: optim.Optimizer = None
170
170
  self.sampler: sampling.NegativeSampler = None
171
171
  self.scheduler: lr_scheduler.LRScheduler | None = None
172
- self.evaluator: KLinkPredictionEvaluator | KTripletClassificationEvaluator = None
172
+ self.evaluator: LinkPredictionEvaluator | TripletClassificationEvaluator = None
173
173
  self.node_embeddings: nn.ParameterList | nn.Embedding
174
174
 
175
175
 
@@ -435,7 +435,7 @@ class Architect(Model):
435
435
  logging.info(f"Scheduler '{scheduler_type}' initialized with parameters: {scheduler_params}")
436
436
  return scheduler
437
437
 
438
- def initialize_evaluator(self) -> KLinkPredictionEvaluator | KTripletClassificationEvaluator:
438
+ def initialize_evaluator(self) -> LinkPredictionEvaluator | TripletClassificationEvaluator:
439
439
  """Set the task for which the model will be evaluated on using the validation set.
440
440
 
441
441
  Options are Link Prediction or Triplet Classification.
@@ -457,13 +457,16 @@ class Architect(Model):
457
457
  case "Link Prediction":
458
458
  full_edgelist = torch.cat([
459
459
  self.kg_train.edgelist,
460
+ self.kg_train.removed_triples,
460
461
  self.kg_val.edgelist,
461
- self.kg_test.edgelist
462
+ self.kg_val.removed_triples,
463
+ self.kg_test.edgelist,
464
+ self.kg_test.removed_triples
462
465
  ], dim=1)
463
- evaluator = KLinkPredictionEvaluator(full_edgelist=full_edgelist)
466
+ evaluator = LinkPredictionEvaluator(full_edgelist=full_edgelist)
464
467
  self.validation_metric = "MRR"
465
468
  case "Triplet Classification":
466
- evaluator = KTripletClassificationEvaluator(architect=self, kg_val = self.kg_val, kg_test=self.kg_test)
469
+ evaluator = TripletClassificationEvaluator(architect=self, kg_val = self.kg_val, kg_test=self.kg_test)
467
470
  self.validation_metric = "Accuracy"
468
471
  case _:
469
472
  raise NotImplementedError(f"The requested evaluator {self.config["evaluation"]["objective"]} is not implemented.")
@@ -505,9 +508,10 @@ class Architect(Model):
505
508
  for node in current_attribute.index:
506
509
  node_idx = self.kg_train.ent2ix[node]
507
510
  nt_idx = self.kg_train.node_types[node_idx]
511
+ local_idx = self.kg_train.glob2loc[node_idx]
508
512
  assert nt_idx == self.kg_train.nt2ix[node_type], f"The entity {node} is given as {node_type} but registered as {ix2nt[str(nt_idx)]} in the KG."
509
513
 
510
- input_features[node_idx] = tensor(current_attribute[node,:], dtype=torch.double)
514
+ input_features[local_idx] = tensor(current_attribute.loc[node], dtype=torch.double)
511
515
 
512
516
  self.node_embeddings.append(Parameter(input_features).to(self.device))
513
517
  else:
@@ -726,7 +730,7 @@ class Architect(Model):
726
730
 
727
731
  return results
728
732
 
729
- def infer(self, heads:List[str]=[], rels:List[str]=[], tails:List[str]=[], topk:int=100):
733
+ def infer(self, heads:List[str]=[], rels:List[str]=[], tails:List[str]=[], top_k:int=100):
730
734
  """Infer missing entities or relations, depending on the given parameters"""
731
735
  if not sum([len(arr) > 0 for arr in [heads,rels,tails]]) == 2:
732
736
  raise ValueError("To infer missing elements, exactly 2 lists must be given between heads, relations or tails.")
@@ -737,30 +741,43 @@ class Architect(Model):
737
741
 
738
742
  infer_heads, infer_rels, infer_tails = len(heads) == 0, len(rels) == 0, len(tails) == 0
739
743
 
744
+ full_kg = merge_kg([self.kg_train, self.kg_val, self.kg_test], True)
745
+
740
746
  if infer_tails:
741
- known_heads = tensor([idx for ent, idx in self.kg_train.ent2ix.items() if ent in heads]).long()
742
- known_rels = tensor([idx for rel, idx in self.kg_train.rel2ix.items() if rel in rels]).long()
743
- inference = KEntityInference(self.decoder, known_heads, known_rels, missing = "tails", dictionary=self.kg_train.dict_of_heads, top_k=topk)
747
+ known_1 = tensor([self.kg_train.ent2ix[head] for head in heads]).long()
748
+ known_2 = tensor([self.kg_train.rel2ix[rel] for rel in rels]).long()
749
+ missing = "tail"
750
+ inference = EntityInference(full_kg)
744
751
  elif infer_heads:
745
- known_tails = tensor([idx for ent, idx in self.kg_train.ent2ix.items() if ent in tails])
746
- known_rels = tensor([idx for rel, idx in self.kg_train.rel2ix.items() if rel in rels])
747
- inference = KEntityInference(self.decoder, known_tails, known_rels, missing = "heads", dictionary=self.kg_train.dict_of_tails, top_k=topk)
752
+ known_1 = tensor([self.kg_train.ent2ix[tail] for tail in tails]).long()
753
+ known_2 = tensor([self.kg_train.rel2ix[rel] for rel in rels]).long()
754
+ missing = "head"
755
+ inference = EntityInference(full_kg)
748
756
  elif infer_rels:
749
- known_heads = tensor([idx for ent, idx in self.kg_train.ent2ix.items() if ent in heads])
750
- known_tails = tensor([idx for ent, idx in self.kg_train.ent2ix.items() if ent in tails])
751
- inference = KRelationInference(self.decoder, known_heads, known_tails, dictionary=self.kg_train.dict_of_rels, top_k=topk)
752
-
753
- embeddings = self.encoder.forward(self.node_embeddings, self.mappings)
754
-
755
- inference.evaluate(self.eval_batch_size, embeddings, self.rel_emb, self.mappings)
757
+ known_1 = tensor([self.kg_train.ent2ix[head] for head in heads]).long()
758
+ known_2 = tensor([self.kg_train.ent2ix[tail] for tail in tails]).long()
759
+ missing = "rel"
760
+ inference = RelationInference(full_kg)
761
+
762
+ predictions, scores = inference.evaluate(
763
+ known_1,
764
+ known_2,
765
+ encoder = self.encoder,
766
+ decoder = self.decoder,
767
+ top_k = top_k,
768
+ missing = missing,
769
+ b_size = self.eval_batch_size,
770
+ node_embeddings=self.node_embeddings,
771
+ relation_embeddings=self.rel_emb
772
+ )
756
773
 
757
774
  ix2ent = {v: k for k, v in self.kg_train.ent2ix.items()}
758
- pred_idx = inference.predictions.reshape(-1).T
775
+ pred_idx = predictions.reshape(-1).T
759
776
  pred_names = np.vectorize(ix2ent.get)(pred_idx)
760
777
 
761
- scores = inference.scores.reshape(-1).T
762
-
763
- self.predictions = pd.DataFrame([pred_names,scores], columns= ["Prediction","Score"])
778
+ scores = scores.reshape(-1).T
779
+ print(pred_idx, scores)
780
+ return pd.DataFrame([pred_names,scores], columns= ["Prediction","Score"])
764
781
 
765
782
  def load_best_model(self):
766
783
  _, nt_count = self.kg_train.node_types.unique(return_counts=True)
@@ -909,7 +926,7 @@ class Architect(Model):
909
926
 
910
927
 
911
928
  if not isinstance(self.encoder, GNN):
912
- self.node_embeddings.weight.data = normalize(self.node_embeddings.weight.data, p=2, dim=1)
929
+ self.node_embeddings.weight.data = normalize(self.node_embeddings.weight.data, p=2, dim=1)
913
930
 
914
931
  logging.debug(f"Normalized all embeddings")
915
932
 
@@ -941,11 +958,11 @@ class Architect(Model):
941
958
  logging.info(f"Evaluating on validation set at epoch {engine.state.epoch}...")
942
959
  self.eval() # Set the model to evaluation mode
943
960
  with torch.no_grad():
944
- if isinstance(self.evaluator,KLinkPredictionEvaluator):
961
+ if isinstance(self.evaluator,LinkPredictionEvaluator):
945
962
  metric = self.link_pred(self.kg_val)
946
963
  engine.state.metrics["val_metrics"] = metric
947
964
  logging.info(f"Validation MRR: {metric}")
948
- elif isinstance(self.evaluator, KTripletClassificationEvaluator):
965
+ elif isinstance(self.evaluator, TripletClassificationEvaluator):
949
966
  metric = self.triplet_classif(self.kg_val, self.kg_test)
950
967
  engine.state.metrics["val_metrics"] = metric
951
968
  logging.info(f"Validation Accuracy: {metric}")
@@ -1041,9 +1058,9 @@ class Architect(Model):
1041
1058
 
1042
1059
  new_kg = kg.keep_triples(indices_to_keep)
1043
1060
 
1044
- if isinstance(self.evaluator, KLinkPredictionEvaluator):
1061
+ if isinstance(self.evaluator, LinkPredictionEvaluator):
1045
1062
  test_metrics = self.link_pred(new_kg)
1046
- elif isinstance(self.evaluator, KTripletClassificationEvaluator):
1063
+ elif isinstance(self.evaluator, TripletClassificationEvaluator):
1047
1064
  test_metrics = self.triplet_classif(kg_val = self.kg_val, kg_test = new_kg)
1048
1065
 
1049
1066
  # Save each relation's MRR
@@ -1081,10 +1098,10 @@ class Architect(Model):
1081
1098
  kg_infrequent = self.kg_test.keep_triples(infrequent_indices)
1082
1099
 
1083
1100
  # Compute each category's MRR
1084
- if isinstance(self.evaluator, KLinkPredictionEvaluator):
1101
+ if isinstance(self.evaluator, LinkPredictionEvaluator):
1085
1102
  frequent_metrics = self.link_pred(kg_frequent) if frequent_indices else 0
1086
1103
  infrequent_metrics = self.link_pred(kg_infrequent) if infrequent_indices else 0
1087
- elif isinstance(self.evaluator, KTripletClassificationEvaluator):
1104
+ elif isinstance(self.evaluator, TripletClassificationEvaluator):
1088
1105
  frequent_metrics = self.triplet_classif(self.kg_val, kg_frequent) if frequent_indices else 0
1089
1106
  infrequent_metrics = self.triplet_classif(self.kg_val, kg_infrequent) if infrequent_indices else 0
1090
1107
  return frequent_metrics, infrequent_metrics
@@ -1092,7 +1109,7 @@ class Architect(Model):
1092
1109
  def link_pred(self, kg: KnowledgeGraph) -> float:
1093
1110
  """Link prediction evaluation on test set."""
1094
1111
  # Test MRR measure
1095
- if not isinstance(self.evaluator, KLinkPredictionEvaluator):
1112
+ if not isinstance(self.evaluator, LinkPredictionEvaluator):
1096
1113
  raise ValueError(f"Wrong evaluator called. Calling Link Prediction method for {type(self.evaluator)} evaluator.")
1097
1114
 
1098
1115
  self.evaluator.evaluate(b_size = self.eval_batch_size,
@@ -1108,7 +1125,7 @@ class Architect(Model):
1108
1125
 
1109
1126
  def triplet_classif(self, kg_val: KnowledgeGraph, kg_test: KnowledgeGraph) -> float:
1110
1127
  """Triplet Classification evaluation"""
1111
- if not isinstance(self.evaluator, KTripletClassificationEvaluator):
1128
+ if not isinstance(self.evaluator, TripletClassificationEvaluator):
1112
1129
  raise ValueError(f"Wrong evaluator called. Calling Triplet Classification method for {type(self.evaluator)} evaluator.")
1113
1130
 
1114
1131
  self.evaluator.evaluate(b_size=self.eval_batch_size, knowledge_graph=kg_val)