Skip to content

RandomLinkSplit

RandomLinkSplit(
    num_val: Union[int, float] = 0.1,
    num_test: Union[int, float] = 0.2,
    is_undirected: bool = False,
    add_negative_train_samples: bool = True,
    neg_sampling_ratio: float = 1.0,
)

Bases: BaseTransform

Randomly splits the edges of a graph into training, validation and test sets for link prediction.

Three graphs are returned. Each one has

  • edge_index: the edges to use for message passing;
  • edge_label_index: the [2, num_labels] edges to predict, positive edges first, then negative edges;
  • edge_label: the [num_labels] float32 labels of these edges, 1 for positive (existing) edges and 0 for negative (sampled) ones.

There is no leakage between the splits, as in PyG:

  • the training graph uses the training edges both for message passing and as positive edges to predict;
  • the validation graph predicts the validation edges, using only the training edges for message passing;
  • the test graph predicts the test edges, using the training and validation edges for message passing.

The negative edges are sampled once among the node pairs that are not connected in the full graph (see negative_sampling()) and shared out between the splits, so they do not overlap either. Per-edge attributes (e.g. edge_features) follow the message passing edges, and the number of nodes of each graph is set explicitly to that of the input graph.

Randomness comes from mx.random (mx.random.permutation for the split, a NumPy generator seeded from mx.random for the negative edges), so results are reproducible with mx.random.seed.

Parameters:

Name Type Description Default
num_val Union[int, float]

Number of validation edges, or ratio of the edges if given as a float. Default: 0.1

0.1
num_test Union[int, float]

Number of test edges, or ratio of the edges if given as a float. Default: 0.2

0.2
is_undirected bool

If True, the graph is assumed to be undirected, i.e. to hold both directions of every edge. Both directions then go to the same split: the edges with src <= dst are split, num_val and num_test count these, edge_label_index holds only that direction, and the message passing edge_index holds both directions. Default: False

False
add_negative_train_samples bool

Whether to add negative edges to the training graph. Set it to False to sample new negative edges at every training epoch instead. Default: True

True
neg_sampling_ratio float

Number of negative edges per positive edge. Default: 1.0

1.0

Example:

graph = GraphData(
    edge_index=mx.array(
        [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]]
    ),
    node_features=mx.ones((10, 4)),
)
train, val, test = RandomLinkSplit(num_val=0.1, num_test=0.2)(graph)

train.edge_index.shape, train.edge_label_index.shape
# (2, 7), (2, 14)
val.edge_index.shape, val.edge_label_index.shape
# (2, 7), (2, 2)
test.edge_index.shape, test.edge_label_index.shape
# (2, 8), (2, 4)

Methods:

Name Description
process

Splits the edges of data.

Source code in mlx_graphs/transforms/splits.py
def __init__(
    self,
    num_val: Union[int, float] = 0.1,
    num_test: Union[int, float] = 0.2,
    is_undirected: bool = False,
    add_negative_train_samples: bool = True,
    neg_sampling_ratio: float = 1.0,
):
    self.num_val = num_val
    self.num_test = num_test
    self.is_undirected = is_undirected
    self.add_negative_train_samples = add_negative_train_samples
    self.neg_sampling_ratio = neg_sampling_ratio

process

process(data: GraphData) -> tuple[GraphData, GraphData, GraphData]

Splits the edges of data.

Parameters:

Name Type Description Default
data GraphData

The graph to split.

required

Returns:

Type Description
tuple[GraphData, GraphData, GraphData]

A tuple (train, val, test) of graphs.

Source code in mlx_graphs/transforms/splits.py
def process(self, data: GraphData) -> tuple[GraphData, GraphData, GraphData]:
    """Splits the edges of ``data``.

    Args:
        data: The graph to split.

    Returns:
        A tuple ``(train, val, test)`` of graphs.
    """
    num_nodes = _num_nodes(data)
    _, edge_keys = _attribute_names(data, num_nodes)
    edge_index = data.edge_index
    edges = np.asarray(edge_index)

    if self.is_undirected:
        candidates = np.nonzero(edges[0] <= edges[1])[0]
    else:
        candidates = np.arange(edges.shape[1])
    perm = candidates[_random_permutation(candidates.size)]

    num_val = _resolve_size(self.num_val, perm.size, rounded=False)
    num_test = _resolve_size(self.num_test, perm.size, rounded=False)
    num_train = perm.size - num_val - num_test
    if num_train <= 0:
        raise ValueError("Insufficient number of edges for training")

    train_edges = perm[:num_train]
    val_edges = perm[num_train : num_train + num_val]
    test_edges = perm[num_train + num_val :]
    train_val_edges = perm[: num_train + num_val]

    num_neg_train = 0
    if self.add_negative_train_samples:
        num_neg_train = int(num_train * self.neg_sampling_ratio)
    num_neg_val = int(num_val * self.neg_sampling_ratio)
    num_neg_test = int(num_test * self.neg_sampling_ratio)
    num_neg = num_neg_train + num_neg_val + num_neg_test

    negatives = np.zeros((2, 0), dtype=edges.dtype)
    if num_neg > 0:
        negatives = np.asarray(
            negative_sampling(edge_index, num_nodes, num_neg_samples=num_neg)
        )
        num_neg_found = negatives.shape[1]
        if num_neg_found < num_neg:
            warnings.warn(
                "There are not enough negative edges to satisfy the provided "
                "sampling ratio. The ratio will be adjusted to "
                f"{num_neg_found / num_neg:.2f}.",
                stacklevel=2,
            )
            num_neg_train = int((num_neg_train / num_neg) * num_neg_found)
            num_neg_val = int((num_neg_val / num_neg) * num_neg_found)
            num_neg_test = num_neg_found - num_neg_train - num_neg_val

    splits = (
        (train_edges, train_edges, negatives[:, num_neg_val + num_neg_test :]),
        (train_edges, val_edges, negatives[:, :num_neg_val]),
        (
            train_val_edges,
            test_edges,
            negatives[:, num_neg_val : num_neg_val + num_neg_test],
        ),
    )
    train, val, test = (
        self._build(data, edges, edge_keys, num_nodes, *split) for split in splits
    )
    return train, val, test

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