Skip to content

batched_negative_sampling

batched_negative_sampling(
    edge_index: array,
    batch_indices: Union[array, tuple[array, array]],
    num_neg_samples: Optional[Union[int, float]] = None,
    force_undirected: bool = False,
) -> array

Samples random negative edges within each graph of a batch of graphs (see negative_sampling()): no negative edge connects two different graphs.

Parameters:

Name Type Description Default
edge_index array

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

required
batch_indices Union[array, tuple[array, array]]

The graph of each node, of shape [num_nodes], with the nodes of each graph stored contiguously (as in GraphDataBatch). For bipartite graphs, a tuple with the graph of each source node and of each destination node.

required
num_neg_samples Optional[Union[int, float]]

Number of negative edges to sample per graph. A float is interpreted as a ratio of the number of edges of each graph. Default: None (one negative edge per edge of each graph).

None
force_undirected bool

If True, the negative edges are undirected (see negative_sampling()). Ignored for bipartite graphs. Default: False

False

Returns:

Type Description
array

A [2, num_neg] array of negative edges, grouped by graph, with the

array

dtype of edge_index.

Example:

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

batched_negative_sampling(edge_index, batch_indices)
# e.g. mx.array([[1, 2, 0, 5, 3, 4], [0, 1, 2, 4, 5, 3]])
Source code in mlx_graphs/utils/negative_sampling.py
@validate_edge_index
def batched_negative_sampling(
    edge_index: mx.array,
    batch_indices: Union[mx.array, tuple[mx.array, mx.array]],
    num_neg_samples: Optional[Union[int, float]] = None,
    force_undirected: bool = False,
) -> mx.array:
    """
    Samples random negative edges within each graph of a batch of graphs (see
    :func:`negative_sampling`): no negative edge connects two different
    graphs.

    Args:
        edge_index: a [2, num_edges] array representing the source and target
            nodes of each edge of the batch
        batch_indices: The graph of each node, of shape ``[num_nodes]``, with
            the nodes of each graph stored contiguously (as in
            :class:`~mlx_graphs.data.GraphDataBatch`). For bipartite graphs, a
            tuple with the graph of each source node and of each destination
            node.
        num_neg_samples: Number of negative edges to sample per graph. A float
            is interpreted as a ratio of the number of edges of each graph.
            Default: ``None`` (one negative edge per edge of each graph).
        force_undirected: If ``True``, the negative edges are undirected (see
            :func:`negative_sampling`). Ignored for bipartite graphs.
            Default: ``False``

    Returns:
        A ``[2, num_neg]`` array of negative edges, grouped by graph, with the
        dtype of ``edge_index``.

    Example:

    .. code-block:: python

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

        batched_negative_sampling(edge_index, batch_indices)
        # e.g. mx.array([[1, 2, 0, 5, 3, 4], [0, 1, 2, 4, 5, 3]])
    """
    bipartite = isinstance(batch_indices, (tuple, list))
    if bipartite:
        src_batch = _to_numpy(batch_indices[0]).astype(np.int64).reshape(-1)
        dst_batch = _to_numpy(batch_indices[1]).astype(np.int64).reshape(-1)
    else:
        src_batch = dst_batch = _to_numpy(batch_indices).astype(np.int64).reshape(-1)

    num_graphs = int(max(src_batch.max(initial=-1), dst_batch.max(initial=-1))) + 1
    num_src = np.bincount(src_batch, minlength=num_graphs)
    num_dst = np.bincount(dst_batch, minlength=num_graphs)
    src_ptr = np.concatenate([[0], np.cumsum(num_src)[:-1]])
    dst_ptr = np.concatenate([[0], np.cumsum(num_dst)[:-1]])

    edges = _to_numpy(edge_index).astype(np.int64).reshape(2, -1)
    edge_batch = src_batch[edges[0]]
    # Edges grouped by graph; one host generator for all the graphs (a
    # single draw from mx.random, instead of one GPU sync per graph).
    order = np.argsort(edge_batch, kind="stable")
    edges, edge_batch = edges[:, order], edge_batch[order]
    edge_ptr = np.searchsorted(edge_batch, np.arange(num_graphs + 1))
    rng = _host_rng() if num_graphs > 0 else None
    negatives = []
    for graph in range(num_graphs):
        local = edges[:, edge_ptr[graph] : edge_ptr[graph + 1]]
        local = np.stack([local[0] - src_ptr[graph], local[1] - dst_ptr[graph]])
        num_neg = _num_negatives(num_neg_samples, local.shape[1])
        if num_neg <= 0:
            continue
        if bipartite:
            size = (int(num_src[graph]), int(num_dst[graph]))
            neg = _bipartite_negatives(local, size, num_neg, rng)
        else:
            n = int(num_src[graph])
            if n < 2:
                continue
            neg = _negatives(local[0], local[1], n, num_neg, force_undirected, rng)
        negatives.append(np.stack([neg[0] + src_ptr[graph], neg[1] + dst_ptr[graph]]))
    if not negatives:
        return _empty_like(edge_index)
    return mx.array(np.concatenate(negatives, axis=1), dtype=edge_index.dtype)

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