dicee.models ============ .. py:module:: dicee.models Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/dicee/models/adopt/index /autoapi/dicee/models/base_model/index /autoapi/dicee/models/clifford/index /autoapi/dicee/models/complex/index /autoapi/dicee/models/dualE/index /autoapi/dicee/models/ensemble/index /autoapi/dicee/models/function_space/index /autoapi/dicee/models/octonion/index /autoapi/dicee/models/pykeen_models/index /autoapi/dicee/models/quaternion/index /autoapi/dicee/models/real/index /autoapi/dicee/models/static_funcs/index /autoapi/dicee/models/transformers/index Classes ------- .. autoapisummary:: dicee.models.ADOPT dicee.models.BaseKGELightning dicee.models.BaseKGE dicee.models.IdentityClass dicee.models.BaseKGE dicee.models.DistMult dicee.models.TransE dicee.models.Shallom dicee.models.Pyke dicee.models.BaseKGE dicee.models.ConEx dicee.models.AConEx dicee.models.ComplEx dicee.models.BaseKGE dicee.models.IdentityClass dicee.models.QMult dicee.models.ConvQ dicee.models.AConvQ dicee.models.BaseKGE dicee.models.IdentityClass dicee.models.OMult dicee.models.ConvO dicee.models.AConvO dicee.models.Keci dicee.models.CKeci dicee.models.DeCaL dicee.models.BaseKGE dicee.models.PykeenKGE dicee.models.BaseKGE dicee.models.FMult dicee.models.GFMult dicee.models.FMult2 dicee.models.LFMult1 dicee.models.LFMult dicee.models.DualE Functions --------- .. autoapisummary:: dicee.models.quaternion_mul dicee.models.quaternion_mul_with_unit_norm dicee.models.octonion_mul dicee.models.octonion_mul_norm Package Contents ---------------- .. py:class:: ADOPT(params: torch.optim.optimizer.ParamsT, lr: Union[float, torch.Tensor] = 0.001, betas: Tuple[float, float] = (0.9, 0.9999), eps: float = 1e-06, clip_lambda: Optional[Callable[[int], float]] = lambda step: step**0.25, weight_decay: float = 0.0, decouple: bool = False, *, foreach: Optional[bool] = None, maximize: bool = False, capturable: bool = False, differentiable: bool = False, fused: Optional[bool] = None) Bases: :py:obj:`torch.optim.optimizer.Optimizer` Base class for all optimizers. .. warning:: Parameters need to be specified as collections that have a deterministic ordering that is consistent between runs. Examples of objects that don't satisfy those properties are sets and iterators over values of dictionaries. :param params: an iterable of :class:`torch.Tensor` s or :class:`dict` s. Specifies what Tensors should be optimized. :type params: iterable :param defaults: (dict): a dict containing default values of optimization options (used when a parameter group doesn't specify them). .. py:attribute:: clip_lambda .. py:method:: __setstate__(state) .. py:method:: step(closure=None) Perform a single optimization step. :param closure: A closure that reevaluates the model and returns the loss. :type closure: Callable, optional .. py:class:: BaseKGELightning(*args, **kwargs) Bases: :py:obj:`lightning.LightningModule` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: training_step_outputs :value: [] .. py:method:: mem_of_model() -> Dict Size of model in MB and number of params .. py:method:: training_step(batch, batch_idx=None) Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger. :param batch: The output of your data iterable, normally a :class:`~torch.utils.data.DataLoader`. :param batch_idx: The index of this batch. :param dataloader_idx: The index of the dataloader that produced this batch. (only if multiple dataloaders used) :returns: - :class:`~torch.Tensor` - The loss tensor - ``dict`` - A dictionary which can include any keys, but must include the key ``'loss'`` in the case of automatic optimization. - ``None`` - In automatic optimization, this will skip to the next batch (but is not supported for multi-GPU, TPU, or DeepSpeed). For manual optimization, this has no special meaning, as returning the loss is not required. In this step you'd normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something model specific. Example:: def training_step(self, batch, batch_idx): x, y, z = batch out = self.encoder(x) loss = self.loss(out, x) return loss To use multiple optimizers, you can switch to 'manual optimization' and control their stepping: .. code-block:: python def __init__(self): super().__init__() self.automatic_optimization = False # Multiple optimizers (e.g.: GANs) def training_step(self, batch, batch_idx): opt1, opt2 = self.optimizers() # do training_step with encoder ... opt1.step() # do training_step with decoder ... opt2.step() .. note:: When ``accumulate_grad_batches`` > 1, the loss returned here will be automatically normalized by ``accumulate_grad_batches`` internally. .. py:method:: loss_function(yhat_batch: torch.FloatTensor, y_batch: torch.FloatTensor) :param yhat_batch: :param y_batch: .. py:method:: on_train_epoch_end(*args, **kwargs) Called in the training loop at the very end of the epoch. To access all batch outputs at the end of the epoch, you can cache step outputs as an attribute of the :class:`~lightning.pytorch.LightningModule` and access them in this hook: .. code-block:: python class MyLightningModule(L.LightningModule): def __init__(self): super().__init__() self.training_step_outputs = [] def training_step(self): loss = ... self.training_step_outputs.append(loss) return loss def on_train_epoch_end(self): # do something with all training_step outputs, for example: epoch_mean = torch.stack(self.training_step_outputs).mean() self.log("training_epoch_mean", epoch_mean) # free up the memory self.training_step_outputs.clear() .. py:method:: test_epoch_end(outputs: List[Any]) .. py:method:: test_dataloader() -> None An iterable or collection of iterables specifying test samples. For more information about multiple dataloaders, see this :ref:`section `. For data processing use the following pattern: - download in :meth:`prepare_data` - process and split in :meth:`setup` However, the above are only necessary for distributed processing. .. warning:: do not assign state in prepare_data - :meth:`~lightning.pytorch.trainer.trainer.Trainer.test` - :meth:`prepare_data` - :meth:`setup` .. note:: Lightning tries to add the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself. .. note:: If you don't need a test dataset and a :meth:`test_step`, you don't need to implement this method. .. py:method:: val_dataloader() -> None An iterable or collection of iterables specifying validation samples. For more information about multiple dataloaders, see this :ref:`section `. The dataloader you return will not be reloaded unless you set :paramref:`~lightning.pytorch.trainer.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer. It's recommended that all data downloads and preparation happen in :meth:`prepare_data`. - :meth:`~lightning.pytorch.trainer.trainer.Trainer.fit` - :meth:`~lightning.pytorch.trainer.trainer.Trainer.validate` - :meth:`prepare_data` - :meth:`setup` .. note:: Lightning tries to add the correct sampler for distributed and arbitrary hardware There is no need to set it yourself. .. note:: If you don't need a validation dataset and a :meth:`validation_step`, you don't need to implement this method. .. py:method:: predict_dataloader() -> None An iterable or collection of iterables specifying prediction samples. For more information about multiple dataloaders, see this :ref:`section `. It's recommended that all data downloads and preparation happen in :meth:`prepare_data`. - :meth:`~lightning.pytorch.trainer.trainer.Trainer.predict` - :meth:`prepare_data` - :meth:`setup` .. note:: Lightning tries to add the correct sampler for distributed and arbitrary hardware There is no need to set it yourself. :returns: A :class:`torch.utils.data.DataLoader` or a sequence of them specifying prediction samples. .. py:method:: train_dataloader() -> None An iterable or collection of iterables specifying training samples. For more information about multiple dataloaders, see this :ref:`section `. The dataloader you return will not be reloaded unless you set :paramref:`~lightning.pytorch.trainer.trainer.Trainer.reload_dataloaders_every_n_epochs` to a positive integer. For data processing use the following pattern: - download in :meth:`prepare_data` - process and split in :meth:`setup` However, the above are only necessary for distributed processing. .. warning:: do not assign state in prepare_data - :meth:`~lightning.pytorch.trainer.trainer.Trainer.fit` - :meth:`prepare_data` - :meth:`setup` .. note:: Lightning tries to add the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself. .. py:method:: configure_optimizers(parameters=None) Choose what optimizers and learning-rate schedulers to use in your optimization. Normally you'd need one. But in the case of GANs or similar you might have multiple. Optimization with multiple optimizers only works in the manual optimization mode. :returns: Any of these 6 options. - **Single optimizer**. - **List or Tuple** of optimizers. - **Two lists** - The first list has multiple optimizers, and the second has multiple LR schedulers (or multiple ``lr_scheduler_config``). - **Dictionary**, with an ``"optimizer"`` key, and (optionally) a ``"lr_scheduler"`` key whose value is a single LR scheduler or ``lr_scheduler_config``. - **None** - Fit will run without any optimizer. The ``lr_scheduler_config`` is a dictionary which contains the scheduler and its associated configuration. The default configuration is shown below. .. code-block:: python lr_scheduler_config = { # REQUIRED: The scheduler instance "scheduler": lr_scheduler, # The unit of the scheduler's step size, could also be 'step'. # 'epoch' updates the scheduler on epoch end whereas 'step' # updates it after a optimizer update. "interval": "epoch", # How many epochs/steps should pass between calls to # `scheduler.step()`. 1 corresponds to updating the learning # rate after every epoch/step. "frequency": 1, # Metric to monitor for schedulers like `ReduceLROnPlateau` "monitor": "val_loss", # If set to `True`, will enforce that the value specified 'monitor' # is available when the scheduler is updated, thus stopping # training if not found. If set to `False`, it will only produce a warning "strict": True, # If using the `LearningRateMonitor` callback to monitor the # learning rate progress, this keyword can be used to specify # a custom logged name "name": None, } When there are schedulers in which the ``.step()`` method is conditioned on a value, such as the :class:`torch.optim.lr_scheduler.ReduceLROnPlateau` scheduler, Lightning requires that the ``lr_scheduler_config`` contains the keyword ``"monitor"`` set to the metric name that the scheduler should be conditioned on. .. testcode:: # The ReduceLROnPlateau scheduler requires a monitor def configure_optimizers(self): optimizer = Adam(...) return { "optimizer": optimizer, "lr_scheduler": { "scheduler": ReduceLROnPlateau(optimizer, ...), "monitor": "metric_to_track", "frequency": "indicates how often the metric is updated", # If "monitor" references validation metrics, then "frequency" should be set to a # multiple of "trainer.check_val_every_n_epoch". }, } # In the case of two optimizers, only one using the ReduceLROnPlateau scheduler def configure_optimizers(self): optimizer1 = Adam(...) optimizer2 = SGD(...) scheduler1 = ReduceLROnPlateau(optimizer1, ...) scheduler2 = LambdaLR(optimizer2, ...) return ( { "optimizer": optimizer1, "lr_scheduler": { "scheduler": scheduler1, "monitor": "metric_to_track", }, }, {"optimizer": optimizer2, "lr_scheduler": scheduler2}, ) Metrics can be made available to monitor by simply logging it using ``self.log('metric_to_track', metric_val)`` in your :class:`~lightning.pytorch.core.LightningModule`. .. note:: Some things to know: - Lightning calls ``.backward()`` and ``.step()`` automatically in case of automatic optimization. - If a learning rate scheduler is specified in ``configure_optimizers()`` with key ``"interval"`` (default "epoch") in the scheduler configuration, Lightning will call the scheduler's ``.step()`` method automatically in case of automatic optimization. - If you use 16-bit precision (``precision=16``), Lightning will automatically handle the optimizer. - If you use :class:`torch.optim.LBFGS`, Lightning handles the closure function automatically for you. - If you use multiple optimizers, you will have to switch to 'manual optimization' mode and step them yourself. - If you need to control how often the optimizer steps, override the :meth:`optimizer_step` hook. .. py:class:: BaseKGE(args: dict) Bases: :py:obj:`BaseKGELightning` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: args .. py:attribute:: embedding_dim :value: None .. py:attribute:: num_entities :value: None .. py:attribute:: num_relations :value: None .. py:attribute:: num_tokens :value: None .. py:attribute:: learning_rate :value: None .. py:attribute:: apply_unit_norm :value: None .. py:attribute:: input_dropout_rate :value: None .. py:attribute:: hidden_dropout_rate :value: None .. py:attribute:: optimizer_name :value: None .. py:attribute:: feature_map_dropout_rate :value: None .. py:attribute:: kernel_size :value: None .. py:attribute:: num_of_output_channels :value: None .. py:attribute:: weight_decay :value: None .. py:attribute:: loss .. py:attribute:: selected_optimizer :value: None .. py:attribute:: normalizer_class :value: None .. py:attribute:: normalize_head_entity_embeddings .. py:attribute:: normalize_relation_embeddings .. py:attribute:: normalize_tail_entity_embeddings .. py:attribute:: hidden_normalizer .. py:attribute:: param_init .. py:attribute:: input_dp_ent_real .. py:attribute:: input_dp_rel_real .. py:attribute:: hidden_dropout .. py:attribute:: loss_history :value: [] .. py:attribute:: byte_pair_encoding .. py:attribute:: max_length_subword_tokens .. py:attribute:: block_size .. py:method:: forward_byte_pair_encoded_k_vs_all(x: torch.LongTensor) :param x: :type x: B x 2 x T .. py:method:: forward_byte_pair_encoded_triple(x: Tuple[torch.LongTensor, torch.LongTensor]) byte pair encoded neural link predictors :param -------: .. py:method:: init_params_with_sanity_checking() .. py:method:: forward(x: Union[torch.LongTensor, Tuple[torch.LongTensor, torch.LongTensor]], y_idx: torch.LongTensor = None) :param x: :param y_idx: :param ordered_bpe_entities: .. py:method:: forward_triples(x: torch.LongTensor) -> torch.Tensor :param x: .. py:method:: forward_k_vs_all(*args, **kwargs) .. py:method:: forward_k_vs_sample(*args, **kwargs) .. py:method:: get_triple_representation(idx_hrt) .. py:method:: get_head_relation_representation(indexed_triple) .. py:method:: get_sentence_representation(x: torch.LongTensor) :param x shape (b: :param 3: :param t): .. py:method:: get_bpe_head_and_relation_representation(x: torch.LongTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor] :param x: :type x: B x 2 x T .. py:method:: get_embeddings() -> Tuple[numpy.ndarray, numpy.ndarray] .. py:class:: IdentityClass(args=None) Bases: :py:obj:`torch.nn.Module` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: args :value: None .. py:method:: __call__(x) .. py:method:: forward(x) :staticmethod: .. py:class:: BaseKGE(args: dict) Bases: :py:obj:`BaseKGELightning` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: args .. py:attribute:: embedding_dim :value: None .. py:attribute:: num_entities :value: None .. py:attribute:: num_relations :value: None .. py:attribute:: num_tokens :value: None .. py:attribute:: learning_rate :value: None .. py:attribute:: apply_unit_norm :value: None .. py:attribute:: input_dropout_rate :value: None .. py:attribute:: hidden_dropout_rate :value: None .. py:attribute:: optimizer_name :value: None .. py:attribute:: feature_map_dropout_rate :value: None .. py:attribute:: kernel_size :value: None .. py:attribute:: num_of_output_channels :value: None .. py:attribute:: weight_decay :value: None .. py:attribute:: loss .. py:attribute:: selected_optimizer :value: None .. py:attribute:: normalizer_class :value: None .. py:attribute:: normalize_head_entity_embeddings .. py:attribute:: normalize_relation_embeddings .. py:attribute:: normalize_tail_entity_embeddings .. py:attribute:: hidden_normalizer .. py:attribute:: param_init .. py:attribute:: input_dp_ent_real .. py:attribute:: input_dp_rel_real .. py:attribute:: hidden_dropout .. py:attribute:: loss_history :value: [] .. py:attribute:: byte_pair_encoding .. py:attribute:: max_length_subword_tokens .. py:attribute:: block_size .. py:method:: forward_byte_pair_encoded_k_vs_all(x: torch.LongTensor) :param x: :type x: B x 2 x T .. py:method:: forward_byte_pair_encoded_triple(x: Tuple[torch.LongTensor, torch.LongTensor]) byte pair encoded neural link predictors :param -------: .. py:method:: init_params_with_sanity_checking() .. py:method:: forward(x: Union[torch.LongTensor, Tuple[torch.LongTensor, torch.LongTensor]], y_idx: torch.LongTensor = None) :param x: :param y_idx: :param ordered_bpe_entities: .. py:method:: forward_triples(x: torch.LongTensor) -> torch.Tensor :param x: .. py:method:: forward_k_vs_all(*args, **kwargs) .. py:method:: forward_k_vs_sample(*args, **kwargs) .. py:method:: get_triple_representation(idx_hrt) .. py:method:: get_head_relation_representation(indexed_triple) .. py:method:: get_sentence_representation(x: torch.LongTensor) :param x shape (b: :param 3: :param t): .. py:method:: get_bpe_head_and_relation_representation(x: torch.LongTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor] :param x: :type x: B x 2 x T .. py:method:: get_embeddings() -> Tuple[numpy.ndarray, numpy.ndarray] .. py:class:: DistMult(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Embedding Entities and Relations for Learning and Inference in Knowledge Bases https://arxiv.org/abs/1412.6575 .. py:attribute:: name :value: 'DistMult' .. py:method:: k_vs_all_score(emb_h: torch.FloatTensor, emb_r: torch.FloatTensor, emb_E: torch.FloatTensor) :param emb_h: :param emb_r: :param emb_E: .. py:method:: forward_k_vs_all(x: torch.LongTensor) .. py:method:: forward_k_vs_sample(x: torch.LongTensor, target_entity_idx: torch.LongTensor) .. py:method:: score(h, r, t) .. py:class:: TransE(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Translating Embeddings for Modeling Multi-relational Data https://proceedings.neurips.cc/paper/2013/file/1cecc7a77928ca8133fa24680a88d2f9-Paper.pdf .. py:attribute:: name :value: 'TransE' .. py:attribute:: margin :value: 4 .. py:method:: score(head_ent_emb, rel_ent_emb, tail_ent_emb) .. py:method:: forward_k_vs_all(x: torch.Tensor) -> torch.FloatTensor .. py:class:: Shallom(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` A shallow neural model for relation prediction (https://arxiv.org/abs/2101.09090) .. py:attribute:: name :value: 'Shallom' .. py:attribute:: shallom .. py:method:: get_embeddings() -> Tuple[numpy.ndarray, None] .. py:method:: forward_k_vs_all(x) -> torch.FloatTensor .. py:method:: forward_triples(x) -> torch.FloatTensor :param x: :return: .. py:class:: Pyke(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` A Physical Embedding Model for Knowledge Graphs .. py:attribute:: name :value: 'Pyke' .. py:attribute:: dist_func .. py:attribute:: margin :value: 1.0 .. py:method:: forward_triples(x: torch.LongTensor) :param x: .. py:class:: BaseKGE(args: dict) Bases: :py:obj:`BaseKGELightning` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: args .. py:attribute:: embedding_dim :value: None .. py:attribute:: num_entities :value: None .. py:attribute:: num_relations :value: None .. py:attribute:: num_tokens :value: None .. py:attribute:: learning_rate :value: None .. py:attribute:: apply_unit_norm :value: None .. py:attribute:: input_dropout_rate :value: None .. py:attribute:: hidden_dropout_rate :value: None .. py:attribute:: optimizer_name :value: None .. py:attribute:: feature_map_dropout_rate :value: None .. py:attribute:: kernel_size :value: None .. py:attribute:: num_of_output_channels :value: None .. py:attribute:: weight_decay :value: None .. py:attribute:: loss .. py:attribute:: selected_optimizer :value: None .. py:attribute:: normalizer_class :value: None .. py:attribute:: normalize_head_entity_embeddings .. py:attribute:: normalize_relation_embeddings .. py:attribute:: normalize_tail_entity_embeddings .. py:attribute:: hidden_normalizer .. py:attribute:: param_init .. py:attribute:: input_dp_ent_real .. py:attribute:: input_dp_rel_real .. py:attribute:: hidden_dropout .. py:attribute:: loss_history :value: [] .. py:attribute:: byte_pair_encoding .. py:attribute:: max_length_subword_tokens .. py:attribute:: block_size .. py:method:: forward_byte_pair_encoded_k_vs_all(x: torch.LongTensor) :param x: :type x: B x 2 x T .. py:method:: forward_byte_pair_encoded_triple(x: Tuple[torch.LongTensor, torch.LongTensor]) byte pair encoded neural link predictors :param -------: .. py:method:: init_params_with_sanity_checking() .. py:method:: forward(x: Union[torch.LongTensor, Tuple[torch.LongTensor, torch.LongTensor]], y_idx: torch.LongTensor = None) :param x: :param y_idx: :param ordered_bpe_entities: .. py:method:: forward_triples(x: torch.LongTensor) -> torch.Tensor :param x: .. py:method:: forward_k_vs_all(*args, **kwargs) .. py:method:: forward_k_vs_sample(*args, **kwargs) .. py:method:: get_triple_representation(idx_hrt) .. py:method:: get_head_relation_representation(indexed_triple) .. py:method:: get_sentence_representation(x: torch.LongTensor) :param x shape (b: :param 3: :param t): .. py:method:: get_bpe_head_and_relation_representation(x: torch.LongTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor] :param x: :type x: B x 2 x T .. py:method:: get_embeddings() -> Tuple[numpy.ndarray, numpy.ndarray] .. py:class:: ConEx(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Convolutional ComplEx Knowledge Graph Embeddings .. py:attribute:: name :value: 'ConEx' .. py:attribute:: conv2d .. py:attribute:: fc_num_input .. py:attribute:: fc1 .. py:attribute:: norm_fc1 .. py:attribute:: bn_conv2d .. py:attribute:: feature_map_dropout .. py:method:: residual_convolution(C_1: Tuple[torch.Tensor, torch.Tensor], C_2: Tuple[torch.Tensor, torch.Tensor]) -> torch.FloatTensor Compute residual score of two complex-valued embeddings. :param C_1: a tuple of two pytorch tensors that corresponds complex-valued embeddings :param C_2: a tuple of two pytorch tensors that corresponds complex-valued embeddings :return: .. py:method:: forward_k_vs_all(x: torch.Tensor) -> torch.FloatTensor .. py:method:: forward_triples(x: torch.Tensor) -> torch.FloatTensor :param x: .. py:method:: forward_k_vs_sample(x: torch.Tensor, target_entity_idx: torch.Tensor) .. py:class:: AConEx(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Additive Convolutional ComplEx Knowledge Graph Embeddings .. py:attribute:: name :value: 'AConEx' .. py:attribute:: conv2d .. py:attribute:: fc_num_input .. py:attribute:: fc1 .. py:attribute:: norm_fc1 .. py:attribute:: bn_conv2d .. py:attribute:: feature_map_dropout .. py:method:: residual_convolution(C_1: Tuple[torch.Tensor, torch.Tensor], C_2: Tuple[torch.Tensor, torch.Tensor]) -> torch.FloatTensor Compute residual score of two complex-valued embeddings. :param C_1: a tuple of two pytorch tensors that corresponds complex-valued embeddings :param C_2: a tuple of two pytorch tensors that corresponds complex-valued embeddings :return: .. py:method:: forward_k_vs_all(x: torch.Tensor) -> torch.FloatTensor .. py:method:: forward_triples(x: torch.Tensor) -> torch.FloatTensor :param x: .. py:method:: forward_k_vs_sample(x: torch.Tensor, target_entity_idx: torch.Tensor) .. py:class:: ComplEx(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: name :value: 'ComplEx' .. py:method:: score(head_ent_emb: torch.FloatTensor, rel_ent_emb: torch.FloatTensor, tail_ent_emb: torch.FloatTensor) :staticmethod: .. py:method:: k_vs_all_score(emb_h: torch.FloatTensor, emb_r: torch.FloatTensor, emb_E: torch.FloatTensor) :staticmethod: :param emb_h: :param emb_r: :param emb_E: .. py:method:: forward_k_vs_all(x: torch.LongTensor) -> torch.FloatTensor .. py:method:: forward_k_vs_sample(x: torch.LongTensor, target_entity_idx: torch.LongTensor) .. py:function:: quaternion_mul(*, Q_1, Q_2) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor] Perform quaternion multiplication :param Q_1: :param Q_2: :return: .. py:class:: BaseKGE(args: dict) Bases: :py:obj:`BaseKGELightning` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: args .. py:attribute:: embedding_dim :value: None .. py:attribute:: num_entities :value: None .. py:attribute:: num_relations :value: None .. py:attribute:: num_tokens :value: None .. py:attribute:: learning_rate :value: None .. py:attribute:: apply_unit_norm :value: None .. py:attribute:: input_dropout_rate :value: None .. py:attribute:: hidden_dropout_rate :value: None .. py:attribute:: optimizer_name :value: None .. py:attribute:: feature_map_dropout_rate :value: None .. py:attribute:: kernel_size :value: None .. py:attribute:: num_of_output_channels :value: None .. py:attribute:: weight_decay :value: None .. py:attribute:: loss .. py:attribute:: selected_optimizer :value: None .. py:attribute:: normalizer_class :value: None .. py:attribute:: normalize_head_entity_embeddings .. py:attribute:: normalize_relation_embeddings .. py:attribute:: normalize_tail_entity_embeddings .. py:attribute:: hidden_normalizer .. py:attribute:: param_init .. py:attribute:: input_dp_ent_real .. py:attribute:: input_dp_rel_real .. py:attribute:: hidden_dropout .. py:attribute:: loss_history :value: [] .. py:attribute:: byte_pair_encoding .. py:attribute:: max_length_subword_tokens .. py:attribute:: block_size .. py:method:: forward_byte_pair_encoded_k_vs_all(x: torch.LongTensor) :param x: :type x: B x 2 x T .. py:method:: forward_byte_pair_encoded_triple(x: Tuple[torch.LongTensor, torch.LongTensor]) byte pair encoded neural link predictors :param -------: .. py:method:: init_params_with_sanity_checking() .. py:method:: forward(x: Union[torch.LongTensor, Tuple[torch.LongTensor, torch.LongTensor]], y_idx: torch.LongTensor = None) :param x: :param y_idx: :param ordered_bpe_entities: .. py:method:: forward_triples(x: torch.LongTensor) -> torch.Tensor :param x: .. py:method:: forward_k_vs_all(*args, **kwargs) .. py:method:: forward_k_vs_sample(*args, **kwargs) .. py:method:: get_triple_representation(idx_hrt) .. py:method:: get_head_relation_representation(indexed_triple) .. py:method:: get_sentence_representation(x: torch.LongTensor) :param x shape (b: :param 3: :param t): .. py:method:: get_bpe_head_and_relation_representation(x: torch.LongTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor] :param x: :type x: B x 2 x T .. py:method:: get_embeddings() -> Tuple[numpy.ndarray, numpy.ndarray] .. py:class:: IdentityClass(args=None) Bases: :py:obj:`torch.nn.Module` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: args :value: None .. py:method:: __call__(x) .. py:method:: forward(x) :staticmethod: .. py:function:: quaternion_mul_with_unit_norm(*, Q_1, Q_2) .. py:class:: QMult(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: name :value: 'QMult' .. py:attribute:: explicit :value: True .. py:method:: quaternion_multiplication_followed_by_inner_product(h, r, t) :param h: shape: (`*batch_dims`, dim) The head representations. :param r: shape: (`*batch_dims`, dim) The head representations. :param t: shape: (`*batch_dims`, dim) The tail representations. :return: Triple scores. .. py:method:: quaternion_normalizer(x: torch.FloatTensor) -> torch.FloatTensor :staticmethod: Normalize the length of relation vectors, if the forward constraint has not been applied yet. Absolute value of a quaternion .. math:: |a + bi + cj + dk| = \sqrt{a^2 + b^2 + c^2 + d^2} L2 norm of quaternion vector: .. math:: \|x\|^2 = \sum_{i=1}^d |x_i|^2 = \sum_{i=1}^d (x_i.re^2 + x_i.im_1^2 + x_i.im_2^2 + x_i.im_3^2) :param x: The vector. :return: The normalized vector. .. py:method:: score(head_ent_emb: torch.FloatTensor, rel_ent_emb: torch.FloatTensor, tail_ent_emb: torch.FloatTensor) .. py:method:: k_vs_all_score(bpe_head_ent_emb, bpe_rel_ent_emb, E) :param bpe_head_ent_emb: :param bpe_rel_ent_emb: :param E: .. py:method:: forward_k_vs_all(x) :param x: .. py:method:: forward_k_vs_sample(x, target_entity_idx) Completed. Given a head entity and a relation (h,r), we compute scores for all possible triples,i.e., [score(h,r,x)|x \in Entities] => [0.0,0.1,...,0.8], shape=> (1, |Entities|) Given a batch of head entities and relations => shape (size of batch,| Entities|) .. py:class:: ConvQ(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Convolutional Quaternion Knowledge Graph Embeddings .. py:attribute:: name :value: 'ConvQ' .. py:attribute:: entity_embeddings .. py:attribute:: relation_embeddings .. py:attribute:: conv2d .. py:attribute:: fc_num_input .. py:attribute:: fc1 .. py:attribute:: bn_conv1 .. py:attribute:: bn_conv2 .. py:attribute:: feature_map_dropout .. py:method:: residual_convolution(Q_1, Q_2) .. py:method:: forward_triples(indexed_triple: torch.Tensor) -> torch.Tensor :param x: .. py:method:: forward_k_vs_all(x: torch.Tensor) Given a head entity and a relation (h,r), we compute scores for all entities. [score(h,r,x)|x \in Entities] => [0.0,0.1,...,0.8], shape=> (1, |Entities|) Given a batch of head entities and relations => shape (size of batch,| Entities|) .. py:class:: AConvQ(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Additive Convolutional Quaternion Knowledge Graph Embeddings .. py:attribute:: name :value: 'AConvQ' .. py:attribute:: entity_embeddings .. py:attribute:: relation_embeddings .. py:attribute:: conv2d .. py:attribute:: fc_num_input .. py:attribute:: fc1 .. py:attribute:: bn_conv1 .. py:attribute:: bn_conv2 .. py:attribute:: feature_map_dropout .. py:method:: residual_convolution(Q_1, Q_2) .. py:method:: forward_triples(indexed_triple: torch.Tensor) -> torch.Tensor :param x: .. py:method:: forward_k_vs_all(x: torch.Tensor) Given a head entity and a relation (h,r), we compute scores for all entities. [score(h,r,x)|x \in Entities] => [0.0,0.1,...,0.8], shape=> (1, |Entities|) Given a batch of head entities and relations => shape (size of batch,| Entities|) .. py:class:: BaseKGE(args: dict) Bases: :py:obj:`BaseKGELightning` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: args .. py:attribute:: embedding_dim :value: None .. py:attribute:: num_entities :value: None .. py:attribute:: num_relations :value: None .. py:attribute:: num_tokens :value: None .. py:attribute:: learning_rate :value: None .. py:attribute:: apply_unit_norm :value: None .. py:attribute:: input_dropout_rate :value: None .. py:attribute:: hidden_dropout_rate :value: None .. py:attribute:: optimizer_name :value: None .. py:attribute:: feature_map_dropout_rate :value: None .. py:attribute:: kernel_size :value: None .. py:attribute:: num_of_output_channels :value: None .. py:attribute:: weight_decay :value: None .. py:attribute:: loss .. py:attribute:: selected_optimizer :value: None .. py:attribute:: normalizer_class :value: None .. py:attribute:: normalize_head_entity_embeddings .. py:attribute:: normalize_relation_embeddings .. py:attribute:: normalize_tail_entity_embeddings .. py:attribute:: hidden_normalizer .. py:attribute:: param_init .. py:attribute:: input_dp_ent_real .. py:attribute:: input_dp_rel_real .. py:attribute:: hidden_dropout .. py:attribute:: loss_history :value: [] .. py:attribute:: byte_pair_encoding .. py:attribute:: max_length_subword_tokens .. py:attribute:: block_size .. py:method:: forward_byte_pair_encoded_k_vs_all(x: torch.LongTensor) :param x: :type x: B x 2 x T .. py:method:: forward_byte_pair_encoded_triple(x: Tuple[torch.LongTensor, torch.LongTensor]) byte pair encoded neural link predictors :param -------: .. py:method:: init_params_with_sanity_checking() .. py:method:: forward(x: Union[torch.LongTensor, Tuple[torch.LongTensor, torch.LongTensor]], y_idx: torch.LongTensor = None) :param x: :param y_idx: :param ordered_bpe_entities: .. py:method:: forward_triples(x: torch.LongTensor) -> torch.Tensor :param x: .. py:method:: forward_k_vs_all(*args, **kwargs) .. py:method:: forward_k_vs_sample(*args, **kwargs) .. py:method:: get_triple_representation(idx_hrt) .. py:method:: get_head_relation_representation(indexed_triple) .. py:method:: get_sentence_representation(x: torch.LongTensor) :param x shape (b: :param 3: :param t): .. py:method:: get_bpe_head_and_relation_representation(x: torch.LongTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor] :param x: :type x: B x 2 x T .. py:method:: get_embeddings() -> Tuple[numpy.ndarray, numpy.ndarray] .. py:class:: IdentityClass(args=None) Bases: :py:obj:`torch.nn.Module` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: args :value: None .. py:method:: __call__(x) .. py:method:: forward(x) :staticmethod: .. py:function:: octonion_mul(*, O_1, O_2) .. py:function:: octonion_mul_norm(*, O_1, O_2) .. py:class:: OMult(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: name :value: 'OMult' .. py:method:: octonion_normalizer(emb_rel_e0, emb_rel_e1, emb_rel_e2, emb_rel_e3, emb_rel_e4, emb_rel_e5, emb_rel_e6, emb_rel_e7) :staticmethod: .. py:method:: score(head_ent_emb: torch.FloatTensor, rel_ent_emb: torch.FloatTensor, tail_ent_emb: torch.FloatTensor) .. py:method:: k_vs_all_score(bpe_head_ent_emb, bpe_rel_ent_emb, E) .. py:method:: forward_k_vs_all(x) Completed. Given a head entity and a relation (h,r), we compute scores for all possible triples,i.e., [score(h,r,x)|x \in Entities] => [0.0,0.1,...,0.8], shape=> (1, |Entities|) Given a batch of head entities and relations => shape (size of batch,| Entities|) .. py:class:: ConvO(args: dict) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: name :value: 'ConvO' .. py:attribute:: conv2d .. py:attribute:: fc_num_input .. py:attribute:: fc1 .. py:attribute:: bn_conv2d .. py:attribute:: norm_fc1 .. py:attribute:: feature_map_dropout .. py:method:: octonion_normalizer(emb_rel_e0, emb_rel_e1, emb_rel_e2, emb_rel_e3, emb_rel_e4, emb_rel_e5, emb_rel_e6, emb_rel_e7) :staticmethod: .. py:method:: residual_convolution(O_1, O_2) .. py:method:: forward_triples(x: torch.Tensor) -> torch.Tensor :param x: .. py:method:: forward_k_vs_all(x: torch.Tensor) Given a head entity and a relation (h,r), we compute scores for all entities. [score(h,r,x)|x \in Entities] => [0.0,0.1,...,0.8], shape=> (1, |Entities|) Given a batch of head entities and relations => shape (size of batch,| Entities|) .. py:class:: AConvO(args: dict) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Additive Convolutional Octonion Knowledge Graph Embeddings .. py:attribute:: name :value: 'AConvO' .. py:attribute:: conv2d .. py:attribute:: fc_num_input .. py:attribute:: fc1 .. py:attribute:: bn_conv2d .. py:attribute:: norm_fc1 .. py:attribute:: feature_map_dropout .. py:method:: octonion_normalizer(emb_rel_e0, emb_rel_e1, emb_rel_e2, emb_rel_e3, emb_rel_e4, emb_rel_e5, emb_rel_e6, emb_rel_e7) :staticmethod: .. py:method:: residual_convolution(O_1, O_2) .. py:method:: forward_triples(x: torch.Tensor) -> torch.Tensor :param x: .. py:method:: forward_k_vs_all(x: torch.Tensor) Given a head entity and a relation (h,r), we compute scores for all entities. [score(h,r,x)|x \in Entities] => [0.0,0.1,...,0.8], shape=> (1, |Entities|) Given a batch of head entities and relations => shape (size of batch,| Entities|) .. py:class:: Keci(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: name :value: 'Keci' .. py:attribute:: p .. py:attribute:: q .. py:attribute:: r .. py:attribute:: requires_grad_for_interactions :value: True .. py:method:: compute_sigma_pp(hp, rp) Compute sigma_{pp} = \sum_{i=1}^{p-1} \sum_{k=i+1}^p (h_i r_k - h_k r_i) e_i e_k sigma_{pp} captures the interactions between along p bases For instance, let p e_1, e_2, e_3, we compute interactions between e_1 e_2, e_1 e_3 , and e_2 e_3 This can be implemented with a nested two for loops results = [] for i in range(p - 1): for k in range(i + 1, p): results.append(hp[:, :, i] * rp[:, :, k] - hp[:, :, k] * rp[:, :, i]) sigma_pp = torch.stack(results, dim=2) assert sigma_pp.shape == (b, r, int((p * (p - 1)) / 2)) Yet, this computation would be quite inefficient. Instead, we compute interactions along all p, e.g., e1e1, e1e2, e1e3, e2e1, e2e2, e2e3, e3e1, e3e2, e3e3 Then select the triangular matrix without diagonals: e1e2, e1e3, e2e3. .. py:method:: compute_sigma_qq(hq, rq) Compute sigma_{qq} = \sum_{j=1}^{p+q-1} \sum_{k=j+1}^{p+q} (h_j r_k - h_k r_j) e_j e_k sigma_{q} captures the interactions between along q bases For instance, let q e_1, e_2, e_3, we compute interactions between e_1 e_2, e_1 e_3 , and e_2 e_3 This can be implemented with a nested two for loops results = [] for j in range(q - 1): for k in range(j + 1, q): results.append(hq[:, :, j] * rq[:, :, k] - hq[:, :, k] * rq[:, :, j]) sigma_qq = torch.stack(results, dim=2) assert sigma_qq.shape == (b, r, int((q * (q - 1)) / 2)) Yet, this computation would be quite inefficient. Instead, we compute interactions along all p, e.g., e1e1, e1e2, e1e3, e2e1, e2e2, e2e3, e3e1, e3e2, e3e3 Then select the triangular matrix without diagonals: e1e2, e1e3, e2e3. .. py:method:: compute_sigma_pq(*, hp, hq, rp, rq) \sum_{i=1}^{p} \sum_{j=p+1}^{p+q} (h_i r_j - h_j r_i) e_i e_j results = [] sigma_pq = torch.zeros(b, r, p, q) for i in range(p): for j in range(q): sigma_pq[:, :, i, j] = hp[:, :, i] * rq[:, :, j] - hq[:, :, j] * rp[:, :, i] print(sigma_pq.shape) .. py:method:: apply_coefficients(hp, hq, rp, rq) Multiplying a base vector with its scalar coefficient .. py:method:: clifford_multiplication(h0, hp, hq, r0, rp, rq) Compute our CL multiplication h = h_0 + \sum_{i=1}^p h_i e_i + \sum_{j=p+1}^{p+q} h_j e_j r = r_0 + \sum_{i=1}^p r_i e_i + \sum_{j=p+1}^{p+q} r_j e_j ei ^2 = +1 for i =< i =< p ej ^2 = -1 for p < j =< p+q ei ej = -eje1 for i eq j h r = sigma_0 + sigma_p + sigma_q + sigma_{pp} + sigma_{q}+ sigma_{pq} where (1) sigma_0 = h_0 r_0 + \sum_{i=1}^p (h_0 r_i) e_i - \sum_{j=p+1}^{p+q} (h_j r_j) e_j (2) sigma_p = \sum_{i=1}^p (h_0 r_i + h_i r_0) e_i (3) sigma_q = \sum_{j=p+1}^{p+q} (h_0 r_j + h_j r_0) e_j (4) sigma_{pp} = \sum_{i=1}^{p-1} \sum_{k=i+1}^p (h_i r_k - h_k r_i) e_i e_k (5) sigma_{qq} = \sum_{j=1}^{p+q-1} \sum_{k=j+1}^{p+q} (h_j r_k - h_k r_j) e_j e_k (6) sigma_{pq} = \sum_{i=1}^{p} \sum_{j=p+1}^{p+q} (h_i r_j - h_j r_i) e_i e_j .. py:method:: construct_cl_multivector(x: torch.FloatTensor, r: int, p: int, q: int) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor] Construct a batch of multivectors Cl_{p,q}(\mathbb{R}^d) Parameter --------- x: torch.FloatTensor with (n,d) shape :returns: * **a0** (*torch.FloatTensor with (n,r) shape*) * **ap** (*torch.FloatTensor with (n,r,p) shape*) * **aq** (*torch.FloatTensor with (n,r,q) shape*) .. py:method:: forward_k_vs_with_explicit(x: torch.Tensor) .. py:method:: k_vs_all_score(bpe_head_ent_emb, bpe_rel_ent_emb, E) .. py:method:: forward_k_vs_all(x: torch.Tensor) -> torch.FloatTensor Kvsall training (1) Retrieve real-valued embedding vectors for heads and relations \mathbb{R}^d . (2) Construct head entity and relation embeddings according to Cl_{p,q}(\mathbb{R}^d) . (3) Perform Cl multiplication (4) Inner product of (3) and all entity embeddings forward_k_vs_with_explicit and this funcitons are identical Parameter --------- x: torch.LongTensor with (n,2) shape :rtype: torch.FloatTensor with (n, |E|) shape .. py:method:: construct_batch_selected_cl_multivector(x: torch.FloatTensor, r: int, p: int, q: int) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor] Construct a batch of batchs multivectors Cl_{p,q}(\mathbb{R}^d) Parameter --------- x: torch.FloatTensor with (n,k, d) shape :returns: * **a0** (*torch.FloatTensor with (n,k, m) shape*) * **ap** (*torch.FloatTensor with (n,k, m, p) shape*) * **aq** (*torch.FloatTensor with (n,k, m, q) shape*) .. py:method:: forward_k_vs_sample(x: torch.LongTensor, target_entity_idx: torch.LongTensor) -> torch.FloatTensor Parameter --------- x: torch.LongTensor with (n,2) shape target_entity_idx: torch.LongTensor with (n, k ) shape k denotes the selected number of examples. :rtype: torch.FloatTensor with (n, k) shape .. py:method:: score(h, r, t) .. py:method:: forward_triples(x: torch.Tensor) -> torch.FloatTensor Parameter --------- x: torch.LongTensor with (n,3) shape :rtype: torch.FloatTensor with (n) shape .. py:class:: CKeci(args) Bases: :py:obj:`Keci` Without learning dimension scaling .. py:attribute:: name :value: 'CKeci' .. py:attribute:: requires_grad_for_interactions :value: False .. py:class:: DeCaL(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: name :value: 'DeCaL' .. py:attribute:: entity_embeddings .. py:attribute:: relation_embeddings .. py:attribute:: p .. py:attribute:: q .. py:attribute:: r .. py:attribute:: re .. py:method:: forward_triples(x: torch.Tensor) -> torch.FloatTensor Parameter --------- x: torch.LongTensor with (n, ) shape :rtype: torch.FloatTensor with (n) shape .. py:method:: cl_pqr(a: torch.tensor) -> torch.tensor Input: tensor(batch_size, emb_dim) ---> output: tensor with 1+p+q+r components with size (batch_size, emb_dim/(1+p+q+r)) each. 1) takes a tensor of size (batch_size, emb_dim), split it into 1 + p + q +r components, hence 1+p+q+r must be a divisor of the emb_dim. 2) Return a list of the 1+p+q+r components vectors, each are tensors of size (batch_size, emb_dim/(1+p+q+r)) .. py:method:: compute_sigmas_single(list_h_emb, list_r_emb, list_t_emb) here we compute all the sums with no others vectors interaction taken with the scalar product with t, that is, .. math:: s0 = h_0r_0t_0 s1 = \sum_{i=1}^{p}h_ir_it_0 s2 = \sum_{j=p+1}^{p+q}h_jr_jt_0 s3 = \sum_{i=1}^{q}(h_0r_it_i + h_ir_0t_i) s4 = \sum_{i=p+1}^{p+q}(h_0r_it_i + h_ir_0t_i) s5 = \sum_{i=p+q+1}^{p+q+r}(h_0r_it_i + h_ir_0t_i) and return: .. math:: sigma_0t = \sigma_0 \cdot t_0 = s0 + s1 -s2 s3, s4 and s5 .. py:method:: compute_sigmas_multivect(list_h_emb, list_r_emb) Here we compute and return all the sums with vectors interaction for the same and different bases. For same bases vectors interaction we have .. math:: \sigma_pp = \sum_{i=1}^{p-1}\sum_{i'=i+1}^{p}(h_ir_{i'}-h_{i'}r_i) (models the interactions between e_i and e_i' for 1 <= i, i' <= p) \sigma_qq = \sum_{j=p+1}^{p+q-1}\sum_{j'=j+1}^{p+q}(h_jr_{j'}-h_{j'} (models the interactions between e_j and e_j' for p+1 <= j, j' <= p+q) \sigma_rr = \sum_{k=p+q+1}^{p+q+r-1}\sum_{k'=k+1}^{p}(h_kr_{k'}-h_{k'}r_k) (models the interactions between e_k and e_k' for p+q+1 <= k, k' <= p+q+r) For different base vector interactions, we have .. math:: \sigma_pq = \sum_{i=1}^{p}\sum_{j=p+1}^{p+q}(h_ir_j - h_jr_i) (interactionsn between e_i and e_j for 1<=i <=p and p+1<= j <= p+q) \sigma_pr = \sum_{i=1}^{p}\sum_{k=p+q+1}^{p+q+r}(h_ir_k - h_kr_i) (interactionsn between e_i and e_k for 1<=i <=p and p+q+1<= k <= p+q+r) \sigma_qr = \sum_{j=p+1}^{p+q}\sum_{j=p+q+1}^{p+q+r}(h_jr_k - h_kr_j) (interactionsn between e_j and e_k for p+1 <= j <=p+q and p+q+1<= j <= p+q+r) .. py:method:: forward_k_vs_all(x: torch.Tensor) -> torch.FloatTensor Kvsall training (1) Retrieve real-valued embedding vectors for heads and relations (2) Construct head entity and relation embeddings according to Cl_{p,q, r}(\mathbb{R}^d) . (3) Perform Cl multiplication (4) Inner product of (3) and all entity embeddings forward_k_vs_with_explicit and this funcitons are identical Parameter --------- x: torch.LongTensor with (n, ) shape :rtype: torch.FloatTensor with (n, |E|) shape .. py:method:: apply_coefficients(h0, hp, hq, hk, r0, rp, rq, rk) Multiplying a base vector with its scalar coefficient .. py:method:: construct_cl_multivector(x: torch.FloatTensor, re: int, p: int, q: int, r: int) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor] Construct a batch of multivectors Cl_{p,q,r}(\mathbb{R}^d) Parameter --------- x: torch.FloatTensor with (n,d) shape :returns: * **a0** (*torch.FloatTensor*) * **ap** (*torch.FloatTensor*) * **aq** (*torch.FloatTensor*) * **ar** (*torch.FloatTensor*) .. py:method:: compute_sigma_pp(hp, rp) Compute .. math:: \sigma_{p,p}^* = \sum_{i=1}^{p-1}\sum_{i'=i+1}^{p}(x_iy_{i'}-x_{i'}y_i) \sigma_{pp} captures the interactions between along p bases For instance, let p e_1, e_2, e_3, we compute interactions between e_1 e_2, e_1 e_3 , and e_2 e_3 This can be implemented with a nested two for loops results = [] for i in range(p - 1): for k in range(i + 1, p): results.append(hp[:, :, i] * rp[:, :, k] - hp[:, :, k] * rp[:, :, i]) sigma_pp = torch.stack(results, dim=2) assert sigma_pp.shape == (b, r, int((p * (p - 1)) / 2)) Yet, this computation would be quite inefficient. Instead, we compute interactions along all p, e.g., e1e1, e1e2, e1e3, e2e1, e2e2, e2e3, e3e1, e3e2, e3e3 Then select the triangular matrix without diagonals: e1e2, e1e3, e2e3. .. py:method:: compute_sigma_qq(hq, rq) Compute .. math:: \sigma_{q,q}^* = \sum_{j=p+1}^{p+q-1}\sum_{j'=j+1}^{p+q}(x_jy_{j'}-x_{j'}y_j) Eq. 16 sigma_{q} captures the interactions between along q bases For instance, let q e_1, e_2, e_3, we compute interactions between e_1 e_2, e_1 e_3 , and e_2 e_3 This can be implemented with a nested two for loops results = [] for j in range(q - 1): for k in range(j + 1, q): results.append(hq[:, :, j] * rq[:, :, k] - hq[:, :, k] * rq[:, :, j]) sigma_qq = torch.stack(results, dim=2) assert sigma_qq.shape == (b, r, int((q * (q - 1)) / 2)) Yet, this computation would be quite inefficient. Instead, we compute interactions along all p, e.g., e1e1, e1e2, e1e3, e2e1, e2e2, e2e3, e3e1, e3e2, e3e3 Then select the triangular matrix without diagonals: e1e2, e1e3, e2e3. .. py:method:: compute_sigma_rr(hk, rk) .. math:: \sigma_{r,r}^* = \sum_{k=p+q+1}^{p+q+r-1}\sum_{k'=k+1}^{p}(x_ky_{k'}-x_{k'}y_k) .. py:method:: compute_sigma_pq(*, hp, hq, rp, rq) Compute .. math:: \sum_{i=1}^{p} \sum_{j=p+1}^{p+q} (h_i r_j - h_j r_i) e_i e_j results = [] sigma_pq = torch.zeros(b, r, p, q) for i in range(p): for j in range(q): sigma_pq[:, :, i, j] = hp[:, :, i] * rq[:, :, j] - hq[:, :, j] * rp[:, :, i] print(sigma_pq.shape) .. py:method:: compute_sigma_pr(*, hp, hk, rp, rk) Compute .. math:: \sum_{i=1}^{p} \sum_{j=p+1}^{p+q} (h_i r_j - h_j r_i) e_i e_j results = [] sigma_pq = torch.zeros(b, r, p, q) for i in range(p): for j in range(q): sigma_pq[:, :, i, j] = hp[:, :, i] * rq[:, :, j] - hq[:, :, j] * rp[:, :, i] print(sigma_pq.shape) .. py:method:: compute_sigma_qr(*, hq, hk, rq, rk) .. math:: \sum_{i=1}^{p} \sum_{j=p+1}^{p+q} (h_i r_j - h_j r_i) e_i e_j results = [] sigma_pq = torch.zeros(b, r, p, q) for i in range(p): for j in range(q): sigma_pq[:, :, i, j] = hp[:, :, i] * rq[:, :, j] - hq[:, :, j] * rp[:, :, i] print(sigma_pq.shape) .. py:class:: BaseKGE(args: dict) Bases: :py:obj:`BaseKGELightning` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: args .. py:attribute:: embedding_dim :value: None .. py:attribute:: num_entities :value: None .. py:attribute:: num_relations :value: None .. py:attribute:: num_tokens :value: None .. py:attribute:: learning_rate :value: None .. py:attribute:: apply_unit_norm :value: None .. py:attribute:: input_dropout_rate :value: None .. py:attribute:: hidden_dropout_rate :value: None .. py:attribute:: optimizer_name :value: None .. py:attribute:: feature_map_dropout_rate :value: None .. py:attribute:: kernel_size :value: None .. py:attribute:: num_of_output_channels :value: None .. py:attribute:: weight_decay :value: None .. py:attribute:: loss .. py:attribute:: selected_optimizer :value: None .. py:attribute:: normalizer_class :value: None .. py:attribute:: normalize_head_entity_embeddings .. py:attribute:: normalize_relation_embeddings .. py:attribute:: normalize_tail_entity_embeddings .. py:attribute:: hidden_normalizer .. py:attribute:: param_init .. py:attribute:: input_dp_ent_real .. py:attribute:: input_dp_rel_real .. py:attribute:: hidden_dropout .. py:attribute:: loss_history :value: [] .. py:attribute:: byte_pair_encoding .. py:attribute:: max_length_subword_tokens .. py:attribute:: block_size .. py:method:: forward_byte_pair_encoded_k_vs_all(x: torch.LongTensor) :param x: :type x: B x 2 x T .. py:method:: forward_byte_pair_encoded_triple(x: Tuple[torch.LongTensor, torch.LongTensor]) byte pair encoded neural link predictors :param -------: .. py:method:: init_params_with_sanity_checking() .. py:method:: forward(x: Union[torch.LongTensor, Tuple[torch.LongTensor, torch.LongTensor]], y_idx: torch.LongTensor = None) :param x: :param y_idx: :param ordered_bpe_entities: .. py:method:: forward_triples(x: torch.LongTensor) -> torch.Tensor :param x: .. py:method:: forward_k_vs_all(*args, **kwargs) .. py:method:: forward_k_vs_sample(*args, **kwargs) .. py:method:: get_triple_representation(idx_hrt) .. py:method:: get_head_relation_representation(indexed_triple) .. py:method:: get_sentence_representation(x: torch.LongTensor) :param x shape (b: :param 3: :param t): .. py:method:: get_bpe_head_and_relation_representation(x: torch.LongTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor] :param x: :type x: B x 2 x T .. py:method:: get_embeddings() -> Tuple[numpy.ndarray, numpy.ndarray] .. py:class:: PykeenKGE(args: dict) Bases: :py:obj:`dicee.models.base_model.BaseKGE` A class for using knowledge graph embedding models implemented in Pykeen Notes: Pykeen_DistMult: C Pykeen_ComplEx: Pykeen_QuatE: Pykeen_MuRE: Pykeen_CP: Pykeen_HolE: Pykeen_HolE: Pykeen_HolE: Pykeen_TransD: Pykeen_TransE: Pykeen_TransF: Pykeen_TransH: Pykeen_TransR: .. py:attribute:: model_kwargs .. py:attribute:: name .. py:attribute:: model .. py:attribute:: loss_history :value: [] .. py:attribute:: args .. py:attribute:: entity_embeddings :value: None .. py:attribute:: relation_embeddings :value: None .. py:method:: forward_k_vs_all(x: torch.LongTensor) # => Explicit version by this we can apply bn and dropout # (1) Retrieve embeddings of heads and relations + apply Dropout & Normalization if given. h, r = self.get_head_relation_representation(x) # (2) Reshape (1). if self.last_dim > 0: h = h.reshape(len(x), self.embedding_dim, self.last_dim) r = r.reshape(len(x), self.embedding_dim, self.last_dim) # (3) Reshape all entities. if self.last_dim > 0: t = self.entity_embeddings.weight.reshape(self.num_entities, self.embedding_dim, self.last_dim) else: t = self.entity_embeddings.weight # (4) Call the score_t from interactions to generate triple scores. return self.interaction.score_t(h=h, r=r, all_entities=t, slice_size=1) .. py:method:: forward_triples(x: torch.LongTensor) -> torch.FloatTensor # => Explicit version by this we can apply bn and dropout # (1) Retrieve embeddings of heads, relations and tails and apply Dropout & Normalization if given. h, r, t = self.get_triple_representation(x) # (2) Reshape (1). if self.last_dim > 0: h = h.reshape(len(x), self.embedding_dim, self.last_dim) r = r.reshape(len(x), self.embedding_dim, self.last_dim) t = t.reshape(len(x), self.embedding_dim, self.last_dim) # (3) Compute the triple score return self.interaction.score(h=h, r=r, t=t, slice_size=None, slice_dim=0) .. py:method:: forward_k_vs_sample(x: torch.LongTensor, target_entity_idx) :abstractmethod: .. py:class:: BaseKGE(args: dict) Bases: :py:obj:`BaseKGELightning` Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:: import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 20, 5) self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x)) Submodules assigned in this way will be registered, and will also have their parameters converted when you call :meth:`to`, etc. .. note:: As per the example above, an ``__init__()`` call to the parent class must be made before assignment on the child. :ivar training: Boolean represents whether this module is in training or evaluation mode. :vartype training: bool .. py:attribute:: args .. py:attribute:: embedding_dim :value: None .. py:attribute:: num_entities :value: None .. py:attribute:: num_relations :value: None .. py:attribute:: num_tokens :value: None .. py:attribute:: learning_rate :value: None .. py:attribute:: apply_unit_norm :value: None .. py:attribute:: input_dropout_rate :value: None .. py:attribute:: hidden_dropout_rate :value: None .. py:attribute:: optimizer_name :value: None .. py:attribute:: feature_map_dropout_rate :value: None .. py:attribute:: kernel_size :value: None .. py:attribute:: num_of_output_channels :value: None .. py:attribute:: weight_decay :value: None .. py:attribute:: loss .. py:attribute:: selected_optimizer :value: None .. py:attribute:: normalizer_class :value: None .. py:attribute:: normalize_head_entity_embeddings .. py:attribute:: normalize_relation_embeddings .. py:attribute:: normalize_tail_entity_embeddings .. py:attribute:: hidden_normalizer .. py:attribute:: param_init .. py:attribute:: input_dp_ent_real .. py:attribute:: input_dp_rel_real .. py:attribute:: hidden_dropout .. py:attribute:: loss_history :value: [] .. py:attribute:: byte_pair_encoding .. py:attribute:: max_length_subword_tokens .. py:attribute:: block_size .. py:method:: forward_byte_pair_encoded_k_vs_all(x: torch.LongTensor) :param x: :type x: B x 2 x T .. py:method:: forward_byte_pair_encoded_triple(x: Tuple[torch.LongTensor, torch.LongTensor]) byte pair encoded neural link predictors :param -------: .. py:method:: init_params_with_sanity_checking() .. py:method:: forward(x: Union[torch.LongTensor, Tuple[torch.LongTensor, torch.LongTensor]], y_idx: torch.LongTensor = None) :param x: :param y_idx: :param ordered_bpe_entities: .. py:method:: forward_triples(x: torch.LongTensor) -> torch.Tensor :param x: .. py:method:: forward_k_vs_all(*args, **kwargs) .. py:method:: forward_k_vs_sample(*args, **kwargs) .. py:method:: get_triple_representation(idx_hrt) .. py:method:: get_head_relation_representation(indexed_triple) .. py:method:: get_sentence_representation(x: torch.LongTensor) :param x shape (b: :param 3: :param t): .. py:method:: get_bpe_head_and_relation_representation(x: torch.LongTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor] :param x: :type x: B x 2 x T .. py:method:: get_embeddings() -> Tuple[numpy.ndarray, numpy.ndarray] .. py:class:: FMult(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Learning Knowledge Neural Graphs .. py:attribute:: name :value: 'FMult' .. py:attribute:: entity_embeddings .. py:attribute:: relation_embeddings .. py:attribute:: k .. py:attribute:: num_sample :value: 50 .. py:attribute:: gamma .. py:attribute:: roots .. py:attribute:: weights .. py:method:: compute_func(weights: torch.FloatTensor, x) -> torch.FloatTensor .. py:method:: chain_func(weights, x: torch.FloatTensor) .. py:method:: forward_triples(idx_triple: torch.Tensor) -> torch.Tensor :param x: .. py:class:: GFMult(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Learning Knowledge Neural Graphs .. py:attribute:: name :value: 'GFMult' .. py:attribute:: entity_embeddings .. py:attribute:: relation_embeddings .. py:attribute:: k .. py:attribute:: num_sample :value: 250 .. py:attribute:: roots .. py:attribute:: weights .. py:method:: compute_func(weights: torch.FloatTensor, x) -> torch.FloatTensor .. py:method:: chain_func(weights, x: torch.FloatTensor) .. py:method:: forward_triples(idx_triple: torch.Tensor) -> torch.Tensor :param x: .. py:class:: FMult2(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Learning Knowledge Neural Graphs .. py:attribute:: name :value: 'FMult2' .. py:attribute:: n_layers :value: 3 .. py:attribute:: k .. py:attribute:: n :value: 50 .. py:attribute:: score_func :value: 'compositional' .. py:attribute:: discrete_points .. py:attribute:: entity_embeddings .. py:attribute:: relation_embeddings .. py:method:: build_func(Vec) .. py:method:: build_chain_funcs(list_Vec) .. py:method:: compute_func(W, b, x) -> torch.FloatTensor .. py:method:: function(list_W, list_b) .. py:method:: trapezoid(list_W, list_b) .. py:method:: forward_triples(idx_triple: torch.Tensor) -> torch.Tensor :param x: .. py:class:: LFMult1(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Embedding with trigonometric functions. We represent all entities and relations in the complex number space as: f(x) = \sum_{k=0}^{k=d-1}wk e^{kix}. and use the three differents scoring function as in the paper to evaluate the score .. py:attribute:: name :value: 'LFMult1' .. py:attribute:: entity_embeddings .. py:attribute:: relation_embeddings .. py:method:: forward_triples(idx_triple) :param x: .. py:method:: tri_score(h, r, t) .. py:method:: vtp_score(h, r, t) .. py:class:: LFMult(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Embedding with polynomial functions. We represent all entities and relations in the polynomial space as: f(x) = \sum_{i=0}^{d-1} a_k x^{i%d} and use the three differents scoring function as in the paper to evaluate the score. We also consider combining with Neural Networks. .. py:attribute:: name :value: 'LFMult' .. py:attribute:: entity_embeddings .. py:attribute:: relation_embeddings .. py:attribute:: degree .. py:attribute:: m .. py:attribute:: x_values .. py:method:: forward_triples(idx_triple) :param x: .. py:method:: construct_multi_coeff(x) .. py:method:: poly_NN(x, coefh, coefr, coeft) Constructing a 2 layers NN to represent the embeddings. h = \sigma(wh^T x + bh ), r = \sigma(wr^T x + br ), t = \sigma(wt^T x + bt ) .. py:method:: linear(x, w, b) .. py:method:: scalar_batch_NN(a, b, c) element wise multiplication between a,b and c: Inputs : a, b, c ====> torch.tensor of size batch_size x m x d Output : a tensor of size batch_size x d .. py:method:: tri_score(coeff_h, coeff_r, coeff_t) this part implement the trilinear scoring techniques: score(h,r,t) = \int_{0}{1} h(x)r(x)t(x) dx = \sum_{i,j,k = 0}^{d-1} \dfrac{a_i*b_j*c_k}{1+(i+j+k)%d} 1. generate the range for i,j and k from [0 d-1] 2. perform \dfrac{a_i*b_j*c_k}{1+(i+j+k)%d} in parallel for every batch 3. take the sum over each batch .. py:method:: vtp_score(h, r, t) this part implement the vector triple product scoring techniques: score(h,r,t) = \int_{0}{1} h(x)r(x)t(x) dx = \sum_{i,j,k = 0}^{d-1} \dfrac{a_i*c_j*b_k - b_i*c_j*a_k}{(1+(i+j)%d)(1+k)} 1. generate the range for i,j and k from [0 d-1] 2. Compute the first and second terms of the sum 3. Multiply with then denominator and take the sum 4. take the sum over each batch .. py:method:: comp_func(h, r, t) this part implement the function composition scoring techniques: i.e. score = .. py:method:: polynomial(coeff, x, degree) This function takes a matrix tensor of coefficients (coeff), a tensor vector of points x and range of integer [0,1,...d] and return a vector tensor (coeff[0][0] + coeff[0][1]x +...+ coeff[0][d]x^d, coeff[1][0] + coeff[1][1]x +...+ coeff[1][d]x^d) .... .. py:method:: pop(coeff, x, degree) This function allow us to evaluate the composition of two polynomes without for loops :) it takes a matrix tensor of coefficients (coeff), a matrix tensor of points x and range of integer [0,1,...d] and return a tensor (coeff[0][0] + coeff[0][1]x +...+ coeff[0][d]x^d, coeff[1][0] + coeff[1][1]x +...+ coeff[1][d]x^d) .... .. py:class:: DualE(args) Bases: :py:obj:`dicee.models.base_model.BaseKGE` Dual Quaternion Knowledge Graph Embeddings (https://ojs.aaai.org/index.php/AAAI/article/download/16850/16657) .. py:attribute:: name :value: 'DualE' .. py:attribute:: entity_embeddings .. py:attribute:: relation_embeddings .. py:attribute:: num_ent :value: None .. py:method:: kvsall_score(e_1_h, e_2_h, e_3_h, e_4_h, e_5_h, e_6_h, e_7_h, e_8_h, e_1_t, e_2_t, e_3_t, e_4_t, e_5_t, e_6_t, e_7_t, e_8_t, r_1, r_2, r_3, r_4, r_5, r_6, r_7, r_8) -> torch.tensor KvsAll scoring function Input --------- x: torch.LongTensor with (n, ) shape Output ------- torch.FloatTensor with (n) shape .. py:method:: forward_triples(idx_triple: torch.tensor) -> torch.tensor Negative Sampling forward pass: Input --------- x: torch.LongTensor with (n, ) shape Output ------- torch.FloatTensor with (n) shape .. py:method:: forward_k_vs_all(x) KvsAll forward pass Input --------- x: torch.LongTensor with (n, ) shape Output ------- torch.FloatTensor with (n) shape .. py:method:: T(x: torch.tensor) -> torch.tensor Transpose function Input: Tensor with shape (nxm) Output: Tensor with shape (mxn)