Skip to content

TGBNegativeEdgeSampler

TGBNegativeEdgeSampler(dataset_name: str)

The precomputed negative edges of the validation and test events of a TGB link property prediction dataset, as py-tgb's tgb.linkproppred.negative_sampler.NegativeEdgeSampler.

Each positive event (src, dst, t) of the validation and test sets is evaluated against a fixed list of negative destinations (one-vs-many), which mixes historical and random destinations (TGB's "hist_rnd" strategy). The sets are loaded with load_eval_set() (or the load_val_ns / load_test_ns methods of the dataset) and queried with query_batch(), or with query_batch_array() to get a padded array.

Parameters:

Name Type Description Default
dataset_name str

Name of the TGB dataset

required

Methods:

Name Description
load_eval_set

Loads the negative samples of a split.

reset_eval_set

Unloads the negative samples of a split.

query_batch

Negative destinations of each positive edge, as py-tgb.

query_batch_array

Negative destinations of each positive edge as a padded array.

Source code in mlx_graphs/datasets/tgb.py
def __init__(self, dataset_name: str):
    self.dataset_name = dataset_name
    self.eval_set: dict[str, Optional[dict]] = {}

load_eval_set

load_eval_set(fname: str, split_mode: str = 'val')

Loads the negative samples of a split.

Parameters:

Name Type Description Default
fname str

A .npz file written by convert_tgb_negatives() (or a TGB .pkl file, which is then converted next to it)

required
split_mode str

"val" or "test"

'val'
Source code in mlx_graphs/datasets/tgb.py
def load_eval_set(self, fname: str, split_mode: str = "val"):
    """Loads the negative samples of a split.

    Args:
        fname: A ``.npz`` file written by :func:`convert_tgb_negatives`
            (or a TGB ``.pkl`` file, which is then converted next to it)
        split_mode: ``"val"`` or ``"test"``
    """
    if split_mode not in _SPLITS:
        raise ValueError("Invalid split-mode! It should be `val` or `test`")
    if not os.path.exists(fname):
        raise FileNotFoundError(f"File not found at {fname}")
    if fname.endswith(".pkl"):
        npz = fname[: -len(".pkl")] + ".npz"
        if not os.path.exists(npz):
            convert_tgb_negatives(fname, npz)
        fname = npz
    with np.load(fname, allow_pickle=False) as f:
        keys, neg, num_neg = f["keys"], f["neg"], f["num_neg"]
    keys = _make_keys([keys[:, i] for i in range(keys.shape[1])])
    order = np.argsort(keys, kind="stable")
    self.eval_set[split_mode] = {
        "keys": keys[order],
        "neg": neg[order],
        "num_neg": num_neg[order],
    }

reset_eval_set

reset_eval_set(split_mode: str = 'test')

Unloads the negative samples of a split.

Source code in mlx_graphs/datasets/tgb.py
def reset_eval_set(self, split_mode: str = "test"):
    """Unloads the negative samples of a split."""
    if split_mode not in _SPLITS:
        raise ValueError("Invalid split-mode! It should be `val` or `test`")
    self.eval_set[split_mode] = None

query_batch

query_batch(
    pos_src: Any,
    pos_dst: Any,
    pos_timestamp: Any,
    edge_type: Any = None,
    split_mode: str = "test",
) -> list[list[int]]

Negative destinations of each positive edge, as py-tgb.

Parameters:

Name Type Description Default
pos_src Any

Sources of the positive edges, shape [batch_size]

required
pos_dst Any

Destinations of the positive edges

required
pos_timestamp Any

Timestamps of the positive edges

required
edge_type Any

Edge types (only for datasets with typed edges)

None
split_mode str

"val" or "test"

'test'

Returns:

Type Description
list[list[int]]

A list with the list of negative destinations of every positive

list[list[int]]

edge.

Source code in mlx_graphs/datasets/tgb.py
def query_batch(
    self,
    pos_src: Any,
    pos_dst: Any,
    pos_timestamp: Any,
    edge_type: Any = None,
    split_mode: str = "test",
) -> list[list[int]]:
    """Negative destinations of each positive edge, as ``py-tgb``.

    Args:
        pos_src: Sources of the positive edges, shape `[batch_size]`
        pos_dst: Destinations of the positive edges
        pos_timestamp: Timestamps of the positive edges
        edge_type: Edge types (only for datasets with typed edges)
        split_mode: ``"val"`` or ``"test"``

    Returns:
        A list with the list of negative destinations of every positive
        edge.
    """
    eval_set, rows = self._rows(
        pos_src, pos_dst, pos_timestamp, edge_type, split_mode
    )
    neg, num_neg = eval_set["neg"][rows], eval_set["num_neg"][rows]
    return [row[:n].tolist() for row, n in zip(neg, num_neg)]

query_batch_array

query_batch_array(
    pos_src: Any,
    pos_dst: Any,
    pos_timestamp: Any,
    edge_type: Any = None,
    split_mode: str = "test",
) -> tuple[array, array]

Negative destinations of each positive edge as a padded array.

Most positive edges of a split have the same number of negatives, a few have less: their rows are padded with -1. Give the scores of the padding entries the value -inf before passing them to the TGBEvaluator, so that they never rank above the positive.

Parameters:

Name Type Description Default
pos_src Any

Sources of the positive edges, shape [batch_size]

required
pos_dst Any

Destinations of the positive edges

required
pos_timestamp Any

Timestamps of the positive edges

required
edge_type Any

Edge types (only for datasets with typed edges)

None
split_mode str

"val" or "test"

'test'

Returns:

Type Description
array

The negative destinations, shape [batch_size, max_num_neg], and

array

the boolean mask of the valid (non-padding) entries.

Source code in mlx_graphs/datasets/tgb.py
def query_batch_array(
    self,
    pos_src: Any,
    pos_dst: Any,
    pos_timestamp: Any,
    edge_type: Any = None,
    split_mode: str = "test",
) -> tuple[mx.array, mx.array]:
    """Negative destinations of each positive edge as a padded array.

    Most positive edges of a split have the same number of negatives, a
    few have less: their rows are padded with ``-1``. Give the scores of
    the padding entries the value ``-inf`` before passing them to the
    :class:`~mlx_graphs.metrics.TGBEvaluator`, so that they never rank
    above the positive.

    Args:
        pos_src: Sources of the positive edges, shape `[batch_size]`
        pos_dst: Destinations of the positive edges
        pos_timestamp: Timestamps of the positive edges
        edge_type: Edge types (only for datasets with typed edges)
        split_mode: ``"val"`` or ``"test"``

    Returns:
        The negative destinations, shape `[batch_size, max_num_neg]`, and
        the boolean mask of the valid (non-padding) entries.
    """
    eval_set, rows = self._rows(
        pos_src, pos_dst, pos_timestamp, edge_type, split_mode
    )
    num_neg = eval_set["num_neg"][rows]
    width = int(num_neg.max()) if num_neg.size else 0
    neg = eval_set["neg"][rows, :width]
    mask = np.arange(width)[None, :] < num_neg[:, None]
    return mx.array(neg), mx.array(mask)

from mlx_graphs.datasets import TGBNegativeEdgeSampler · mlx_graphs/datasets/tgb.py