Skip to content

structured_negative_sampling

structured_negative_sampling(
    edge_index: array,
    num_nodes: Optional[int] = None,
    contains_neg_self_loops: bool = True,
) -> tuple[array, array, array]

Samples one negative destination for every edge of edge_index: for each edge (src, dst_pos), a node dst_neg such that (src, dst_neg) is not an edge.

Each dst_neg is drawn uniformly among the nodes that are not neighbors of src. The sampling is exact (no rejection loop), so it also terminates on dense graphs: an edge whose source is connected to every node has no valid negative and is left out of the result. The three returned arrays are therefore always aligned with each other, and they are aligned with edge_index whenever every source has at least one non-neighbor.

Randomness comes from a NumPy generator seeded from mx.random, so results are reproducible with mx.random.seed.

Parameters:

Name Type Description Default
edge_index array

a [2, num_edges] array representing the source and target nodes of each edge

required
num_nodes Optional[int]

Number of nodes in the graph. Inferred from edge_index if not given.

None
contains_neg_self_loops bool

If False, dst_neg is never equal to src. Default: True (a self-loop that is not in edge_index is a valid negative, as in PyG).

True

Returns:

Type Description
array

A tuple (src, dst_pos, dst_neg) of arrays of the same length, with

array

the dtype of edge_index.

Example:

edge_index = mx.array([[0, 0, 1, 2], [0, 1, 2, 3]])

src, dst_pos, dst_neg = structured_negative_sampling(edge_index)
# src: mx.array([0, 0, 1, 2])
# dst_pos: mx.array([0, 1, 2, 3])
# dst_neg: e.g. mx.array([3, 2, 0, 1])
Source code in mlx_graphs/utils/negative_sampling.py
@validate_edge_index
def structured_negative_sampling(
    edge_index: mx.array,
    num_nodes: Optional[int] = None,
    contains_neg_self_loops: bool = True,
) -> tuple[mx.array, mx.array, mx.array]:
    """
    Samples one negative destination for every edge of ``edge_index``: for
    each edge ``(src, dst_pos)``, a node ``dst_neg`` such that
    ``(src, dst_neg)`` is not an edge.

    Each ``dst_neg`` is drawn uniformly among the nodes that are not
    neighbors of ``src``. The sampling is exact (no rejection loop), so it
    also terminates on dense graphs: an edge whose source is connected to
    every node has no valid negative and is left out of the result. The three
    returned arrays are therefore always aligned with each other, and they
    are aligned with ``edge_index`` whenever every source has at least one
    non-neighbor.

    Randomness comes from a NumPy generator seeded from ``mx.random``, so
    results are reproducible with ``mx.random.seed``.

    Args:
        edge_index: a [2, num_edges] array representing the source and target
            nodes of each edge
        num_nodes: Number of nodes in the graph. Inferred from ``edge_index``
            if not given.
        contains_neg_self_loops: If ``False``, ``dst_neg`` is never equal to
            ``src``. Default: ``True`` (a self-loop that is not in
            ``edge_index`` is a valid negative, as in PyG).

    Returns:
        A tuple ``(src, dst_pos, dst_neg)`` of arrays of the same length, with
        the dtype of ``edge_index``.

    Example:

    .. code-block:: python

        edge_index = mx.array([[0, 0, 1, 2], [0, 1, 2, 3]])

        src, dst_pos, dst_neg = structured_negative_sampling(edge_index)
        # src: mx.array([0, 0, 1, 2])
        # dst_pos: mx.array([0, 1, 2, 3])
        # dst_neg: e.g. mx.array([3, 2, 0, 1])
    """
    src, dst, n = _host_edges(edge_index, num_nodes)
    dtype = edge_index.dtype
    if src.size == 0:
        empty = mx.zeros((0,), dtype=dtype)
        return empty, empty, empty

    # Forbidden destinations of each source, as sorted unique keys.
    forbidden_src, forbidden_dst = src, dst
    if not contains_neg_self_loops:
        nodes = np.arange(n, dtype=np.int64)
        forbidden_src = np.concatenate([src, nodes])
        forbidden_dst = np.concatenate([dst, nodes])
    keys = np.unique(forbidden_src * n + forbidden_dst)
    key_src, key_dst = keys // n, keys % n

    counts = np.bincount(key_src, minlength=n)
    row_ptr = np.concatenate([[0], np.cumsum(counts)])
    # Number of allowed destinations of the row below each forbidden one (see
    # `_kth_missing`), made globally sorted by adding the row.
    rank_in_row = np.arange(keys.size, dtype=np.int64) - row_ptr[key_src]
    allowed_before = key_src * (n + 1) + key_dst - rank_in_row

    num_allowed = n - counts[src]
    feasible = np.nonzero(num_allowed > 0)[0]
    if feasible.size == 0:
        empty = mx.zeros((0,), dtype=dtype)
        return empty, empty, empty

    feasible_src = src[feasible]
    ranks = _host_rng().integers(0, num_allowed[feasible])
    forbidden_before = (
        np.searchsorted(allowed_before, feasible_src * (n + 1) + ranks, side="right")
        - row_ptr[feasible_src]
    )
    dst_neg = mx.array(ranks + forbidden_before, dtype=dtype)

    if feasible.size == src.size:
        return edge_index[0], edge_index[1], dst_neg
    feasible_mx = mx.array(feasible)
    return edge_index[0][feasible_mx], edge_index[1][feasible_mx], dst_neg

from mlx_graphs.utils import structured_negative_sampling · mlx_graphs/utils/negative_sampling.py