Skip to content

shuffle_node

shuffle_node(
    node_features: array,
    batch_indices: Optional[array] = None,
    training: bool = True,
) -> tuple[array, array]

Randomly shuffles the rows of node_features, within each graph if batch_indices is given.

Randomness comes from mx.random, so results are reproducible with mx.random.seed.

Parameters:

Name Type Description Default
node_features array

The node features, of shape [num_nodes, ...].

required
batch_indices Optional[array]

Optional graph of each node, of shape [num_nodes], with the nodes of each graph stored contiguously (as in GraphDataBatch). Default: None

None
training bool

If False, nothing is shuffled. Default: True

True

Returns:

Type Description
array

A tuple (node_features[perm], perm) with the shuffled features and

array

the permutation.

Example:

node_features = mx.arange(6).reshape(6, 1)
batch_indices = mx.array([0, 0, 0, 1, 1, 1])

shuffle_node(node_features, batch_indices)
# e.g. (mx.array([[1], [2], [0], [5], [3], [4]]),
#       mx.array([1, 2, 0, 5, 3, 4]))
Source code in mlx_graphs/utils/augmentation.py
def shuffle_node(
    node_features: mx.array,
    batch_indices: Optional[mx.array] = None,
    training: bool = True,
) -> tuple[mx.array, mx.array]:
    """
    Randomly shuffles the rows of ``node_features``, within each graph if
    ``batch_indices`` is given.

    Randomness comes from ``mx.random``, so results are reproducible with
    ``mx.random.seed``.

    Args:
        node_features: The node features, of shape ``[num_nodes, ...]``.
        batch_indices: Optional graph of each node, of shape ``[num_nodes]``,
            with the nodes of each graph stored contiguously (as in
            :class:`~mlx_graphs.data.GraphDataBatch`). Default: ``None``
        training: If ``False``, nothing is shuffled. Default: ``True``

    Returns:
        A tuple ``(node_features[perm], perm)`` with the shuffled features and
        the permutation.

    Example:

    .. code-block:: python

        node_features = mx.arange(6).reshape(6, 1)
        batch_indices = mx.array([0, 0, 0, 1, 1, 1])

        shuffle_node(node_features, batch_indices)
        # e.g. (mx.array([[1], [2], [0], [5], [3], [4]]),
        #       mx.array([1, 2, 0, 5, 3, 4]))
    """
    num_nodes = node_features.shape[0]
    if not training:
        return node_features, mx.arange(num_nodes)
    if batch_indices is None:
        perm = mx.random.permutation(num_nodes)
        return node_features[perm], perm

    batch = _to_numpy(batch_indices).reshape(-1)
    keys = _to_numpy(mx.random.uniform(shape=(num_nodes,)))
    # Sorting by (graph, random key) shuffles the nodes within each graph.
    perm = mx.array(np.lexsort((keys, batch)).astype(np.int32))
    return node_features[perm], perm

from mlx_graphs.utils import shuffle_node · mlx_graphs/utils/augmentation.py