Skip to content

KGEModel

KGEModel(num_nodes: int, num_relations: int, hidden_features_dim: int)

Bases: Module

Base class of the knowledge graph embedding models.

Subclasses implement the scoring function __call__() (higher is more plausible) and the training objective loss(). Scoring functions broadcast over their inputs, so test() scores many candidate tails at once.

Parameters:

Name Type Description Default
num_nodes int

The number of nodes (entities) in the graph.

required
num_relations int

The number of relations in the graph.

required
hidden_features_dim int

The size of the embeddings.

required

Methods:

Name Description
__call__

Returns the score of the given triplets.

loss

Returns the loss of the given (positive) triplets, against negative

loader

Returns a mini-batch loader of triplets.

test

Evaluates the model with the Mean Rank, the MRR and the Hits@k of

random_sample

Samples negative triplets by replacing the head of the first half

Source code in mlx_graphs/nn/models/kge.py
def __init__(self, num_nodes: int, num_relations: int, hidden_features_dim: int):
    super().__init__()
    self.num_nodes = num_nodes
    self.num_relations = num_relations
    self.hidden_features_dim = hidden_features_dim
    self.node_emb = nn.Embedding(num_nodes, hidden_features_dim)
    self.rel_emb = nn.Embedding(num_relations, hidden_features_dim)

__call__

__call__(head_index: array, rel_type: array, tail_index: array) -> array

Returns the score of the given triplets.

Parameters:

Name Type Description Default
head_index array

The head indices

required
rel_type array

The relation types

required
tail_index array

The tail indices

required

Returns:

Type Description
array

The scores, with the broadcast shape of the inputs.

Source code in mlx_graphs/nn/models/kge.py
def __call__(
    self, head_index: mx.array, rel_type: mx.array, tail_index: mx.array
) -> mx.array:
    """Returns the score of the given triplets.

    Args:
        head_index: The head indices
        rel_type: The relation types
        tail_index: The tail indices

    Returns:
        The scores, with the broadcast shape of the inputs.
    """
    raise NotImplementedError

loss

loss(head_index: array, rel_type: array, tail_index: array) -> array

Returns the loss of the given (positive) triplets, against negative triplets drawn with random_sample().

Parameters:

Name Type Description Default
head_index array

The head indices

required
rel_type array

The relation types

required
tail_index array

The tail indices

required
Source code in mlx_graphs/nn/models/kge.py
def loss(
    self, head_index: mx.array, rel_type: mx.array, tail_index: mx.array
) -> mx.array:
    """Returns the loss of the given (positive) triplets, against negative
    triplets drawn with :meth:`random_sample`.

    Args:
        head_index: The head indices
        rel_type: The relation types
        tail_index: The tail indices
    """
    raise NotImplementedError

loader

loader(
    head_index: array, rel_type: array, tail_index: array, **kwargs
) -> KGTripletLoader

Returns a mini-batch loader of triplets.

Parameters:

Name Type Description Default
head_index array

The head indices

required
rel_type array

The relation types

required
tail_index array

The tail indices

required
**kwargs

Arguments of KGTripletLoader: batch_size, shuffle and drop_last.

{}
Source code in mlx_graphs/nn/models/kge.py
def loader(
    self,
    head_index: mx.array,
    rel_type: mx.array,
    tail_index: mx.array,
    **kwargs,
) -> KGTripletLoader:
    """Returns a mini-batch loader of triplets.

    Args:
        head_index: The head indices
        rel_type: The relation types
        tail_index: The tail indices
        **kwargs: Arguments of :class:`KGTripletLoader`: ``batch_size``,
            ``shuffle`` and ``drop_last``.
    """
    return KGTripletLoader(head_index, rel_type, tail_index, **kwargs)

test

test(
    head_index: array,
    rel_type: array,
    tail_index: array,
    batch_size: int,
    k: int = 10,
    log: bool = True,
) -> Tuple[float, float, float]

Evaluates the model with the Mean Rank, the MRR and the Hits@k of the true tail among all the possible tail entities.

The rank of a triplet is the position (0 for the best) of the true tail among all entities sorted by decreasing score, as in PyG (argsort(descending=True)). Entities whose score ties with the true tail's are ordered by index, as a stable sort would: PyG's unstable sort orders them arbitrarily, so its ranks may differ from these when scores tie.

Parameters:

Name Type Description Default
head_index array

The head indices

required
rel_type array

The relation types

required
tail_index array

The tail indices

required
batch_size int

Maximum number of scores computed at once. Triplets are evaluated by chunks of max(1, batch_size // num_nodes).

required
k int

The \(k\) of Hits@\(k\). Default: 10

10
log bool

Whether to show a progress bar. Default: True

True

Returns:

Type Description
Tuple[float, float, float]

A tuple (mean_rank, mrr, hits_at_k).

Source code in mlx_graphs/nn/models/kge.py
def test(
    self,
    head_index: mx.array,
    rel_type: mx.array,
    tail_index: mx.array,
    batch_size: int,
    k: int = 10,
    log: bool = True,
) -> Tuple[float, float, float]:
    """Evaluates the model with the Mean Rank, the MRR and the Hits@k of
    the true tail among all the possible tail entities.

    The rank of a triplet is the position (0 for the best) of the true
    tail among all entities sorted by decreasing score, as in PyG
    (``argsort(descending=True)``). Entities whose score ties with the
    true tail's are ordered by index, as a stable sort would: PyG's
    unstable sort orders them arbitrarily, so its ranks may differ from
    these when scores tie.

    Args:
        head_index: The head indices
        rel_type: The relation types
        tail_index: The tail indices
        batch_size: Maximum number of scores computed at once. Triplets are
            evaluated by chunks of ``max(1, batch_size // num_nodes)``.
        k: The :math:`k` of Hits@:math:`k`. Default: ``10``
        log: Whether to show a progress bar. Default: ``True``

    Returns:
        A tuple ``(mean_rank, mrr, hits_at_k)``.
    """
    head_index = head_index.reshape(-1)
    rel_type = rel_type.reshape(-1)
    tail_index = tail_index.reshape(-1)
    num_triplets = head_index.size
    chunk = max(1, batch_size // self.num_nodes)
    candidates = mx.arange(self.num_nodes)[None, :]

    ranks = []
    starts = range(0, num_triplets, chunk)
    for start in tqdm(starts) if log else starts:
        h = head_index[start : start + chunk, None]
        r = rel_type[start : start + chunk, None]
        t = tail_index[start : start + chunk, None]
        scores = mx.stop_gradient(self(h, r, candidates))  # [chunk, num_nodes]
        true_scores = mx.take_along_axis(scores, t, axis=1)
        # position of the true tail in a stable descending argsort
        ahead = (scores > true_scores) | (
            (scores == true_scores) & (candidates < t)
        )
        rank = ahead.sum(axis=1)
        mx.eval(rank)
        ranks.append(rank)

    ranks = mx.concatenate(ranks).astype(mx.float32)
    mean_rank = float(ranks.mean().item())
    mrr = float((1.0 / (ranks + 1)).mean().item())
    hits_at_k = float((ranks < k).astype(mx.float32).mean().item())
    return mean_rank, mrr, hits_at_k

random_sample

random_sample(
    head_index: array, rel_type: array, tail_index: array
) -> Triplets

Samples negative triplets by replacing the head of the first half of the triplets, and the tail of the second half, with random nodes.

Parameters:

Name Type Description Default
head_index array

The head indices

required
rel_type array

The relation types

required
tail_index array

The tail indices

required
Source code in mlx_graphs/nn/models/kge.py
def random_sample(
    self, head_index: mx.array, rel_type: mx.array, tail_index: mx.array
) -> Triplets:
    """Samples negative triplets by replacing the head of the first half
    of the triplets, and the tail of the second half, with random nodes.

    Args:
        head_index: The head indices
        rel_type: The relation types
        tail_index: The tail indices
    """
    num_negatives = head_index.size // 2
    rnd_index = mx.random.randint(0, self.num_nodes, head_index.shape).astype(
        head_index.dtype
    )
    first_half = mx.arange(head_index.size).reshape(head_index.shape) < (
        num_negatives
    )
    head_index = mx.where(first_half, rnd_index, head_index)
    tail_index = mx.where(first_half, tail_index, rnd_index)
    return head_index, rel_type, tail_index

from mlx_graphs.nn import KGEModel · mlx_graphs/nn/models/kge.py