Skip to content

RandomNodeSplit

RandomNodeSplit(
    split: Literal["train_rest", "test_rest", "random"] = "train_rest",
    num_val: Union[int, float] = 500,
    num_test: Union[int, float] = 1000,
    num_train_per_class: int = 20,
    key: str = "node_labels",
)

Bases: BaseTransform

Randomly splits the nodes of a graph into training, validation and test sets, stored as the boolean masks train_mask, val_mask and test_mask of shape [num_nodes].

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

Parameters:

Name Type Description Default
split Literal['train_rest', 'test_rest', 'random']

The type of split:

  • "train_rest": num_val random nodes for validation, num_test for test, and all the others for training.
  • "test_rest": num_train_per_class random nodes of each class for training, num_val for validation, and all the others for test.
  • "random": num_train_per_class random nodes of each class for training, num_val for validation and num_test for test. The remaining nodes are in no split.

Default: "train_rest"

'train_rest'
num_val Union[int, float]

Number of validation nodes, or ratio of the nodes if given as a float. Default: 500

500
num_test Union[int, float]

Number of test nodes, or ratio of the nodes if given as a float. Default: 1000

1000
num_train_per_class int

Number of training nodes per class for the "test_rest" and "random" splits. Default: 20

20
key str

Name of the attribute holding the class index of each node, used by the "test_rest" and "random" splits. Nodes with a negative label are never used for training. Default: "node_labels"

'node_labels'

Example:

graph = GraphData(
    edge_index=mx.array([[0, 1, 2, 3], [1, 2, 3, 4]]),
    node_features=mx.ones((5, 2)),
)
graph = RandomNodeSplit(num_val=1, num_test=0.2)(graph)
graph.train_mask
# e.g. mx.array([True, False, True, False, True])

Methods:

Name Description
process

Adds the train_mask, val_mask and test_mask attributes.

Source code in mlx_graphs/transforms/splits.py
def __init__(
    self,
    split: Literal["train_rest", "test_rest", "random"] = "train_rest",
    num_val: Union[int, float] = 500,
    num_test: Union[int, float] = 1000,
    num_train_per_class: int = 20,
    key: str = "node_labels",
):
    if split not in ("train_rest", "test_rest", "random"):
        raise ValueError(
            f"Invalid split '{split}', expected 'train_rest', 'test_rest' "
            "or 'random'"
        )
    self.split = split
    self.num_val = num_val
    self.num_test = num_test
    self.num_train_per_class = num_train_per_class
    self.key = key

process

process(data: GraphData) -> GraphData

Adds the train_mask, val_mask and test_mask attributes.

Parameters:

Name Type Description Default
data GraphData

The graph to split.

required

Returns:

Type Description
GraphData

The graph with the three masks.

Source code in mlx_graphs/transforms/splits.py
def process(self, data: GraphData) -> GraphData:
    """Adds the ``train_mask``, ``val_mask`` and ``test_mask`` attributes.

    Args:
        data: The graph to split.

    Returns:
        The graph with the three masks.
    """
    num_nodes = _num_nodes(data)
    num_val = _resolve_size(self.num_val, num_nodes, rounded=True)
    num_test = _resolve_size(self.num_test, num_nodes, rounded=True)

    train_mask = np.zeros(num_nodes, dtype=bool)
    val_mask = np.zeros(num_nodes, dtype=bool)
    test_mask = np.zeros(num_nodes, dtype=bool)

    if self.split == "train_rest":
        perm = _random_permutation(num_nodes)
        val_mask[perm[:num_val]] = True
        test_mask[perm[num_val : num_val + num_test]] = True
        train_mask[perm[num_val + num_test :]] = True
    else:
        labels = getattr(data, self.key, None)
        if labels is None:
            raise ValueError(
                f"The '{self.split}' split requires the '{self.key}' attribute"
            )
        labels = np.asarray(labels).reshape(-1)
        if labels.size != num_nodes:
            raise ValueError(
                f"'{self.key}' must hold one class index per node (got "
                f"{labels.size} entries for {num_nodes} nodes)"
            )
        # Shuffle the nodes, group them by class (keeping the shuffled order
        # within each class) and take the first ones of each class.
        perm = _random_permutation(num_nodes)
        perm = perm[labels[perm] >= 0]
        perm = perm[np.argsort(labels[perm], kind="stable")]
        sorted_labels = labels[perm]
        is_first = np.ones(perm.size, dtype=bool)
        is_first[1:] = sorted_labels[1:] != sorted_labels[:-1]
        class_start = np.maximum.accumulate(
            np.where(is_first, np.arange(perm.size), 0)
        )
        rank_in_class = np.arange(perm.size) - class_start
        train_mask[perm[rank_in_class < self.num_train_per_class]] = True

        remaining = np.nonzero(~train_mask)[0]
        remaining = remaining[_random_permutation(remaining.size)]
        val_mask[remaining[:num_val]] = True
        if self.split == "test_rest":
            test_mask[remaining[num_val:]] = True
        else:
            test_mask[remaining[num_val : num_val + num_test]] = True

    data.train_mask = mx.array(train_mask)
    data.val_mask = mx.array(val_mask)
    data.test_mask = mx.array(test_mask)
    return data

from mlx_graphs.transforms import RandomNodeSplit · mlx_graphs/transforms/splits.py