Skip to content

IndexToMask

IndexToMask(
    attrs: Optional[Union[str, list[str]]] = None,
    sizes: Optional[Union[int, Sequence[int]]] = None,
    replace: bool = False,
)

Bases: BaseTransform

Converts index attributes (named *_index, e.g. train_index) to boolean mask attributes (named *_mask, e.g. train_mask).

Attributes containing edge_index are never converted.

Parameters:

Name Type Description Default
attrs Optional[Union[str, list[str]]]

Name(s) of the index attributes to convert. Default: None (all the attributes ending with _index).

None
sizes Optional[Union[int, Sequence[int]]]

Size of the masks, as one int for all the attributes or a list with one int per attribute. Default: None (the number of edges for attributes containing edge, the number of nodes otherwise).

None
replace bool

If True, the index attributes are removed. Default: False

False

Example:

graph = GraphData(
    edge_index=mx.array([[0, 1, 2], [1, 2, 3]]),
    node_features=mx.ones((4, 1)),
    train_index=mx.array([0, 2]),
)
graph = IndexToMask()(graph)
graph.train_mask
# mx.array([True, False, True, False])

Methods:

Name Description
process

Adds the masks to data.

Source code in mlx_graphs/transforms/masks.py
def __init__(
    self,
    attrs: Optional[Union[str, list[str]]] = None,
    sizes: Optional[Union[int, Sequence[int]]] = None,
    replace: bool = False,
):
    self.attrs = [attrs] if isinstance(attrs, str) else attrs
    self.sizes = sizes
    self.replace = replace

process

process(data: GraphData) -> GraphData

Adds the masks to data.

Parameters:

Name Type Description Default
data GraphData

The graph to transform.

required

Returns:

Type Description
GraphData

The graph with the mask attributes.

Source code in mlx_graphs/transforms/masks.py
def process(self, data: GraphData) -> GraphData:
    """Adds the masks to ``data``.

    Args:
        data: The graph to transform.

    Returns:
        The graph with the mask attributes.
    """
    attrs = _attrs_with_suffix(self.attrs, data, "_index")
    if isinstance(self.sizes, int):
        sizes = [self.sizes] * len(attrs)
    elif isinstance(self.sizes, (list, tuple)):
        if len(attrs) != len(self.sizes):
            raise ValueError(
                f"The number of attributes (got {len(attrs)}) must match "
                f"the number of sizes provided (got {len(self.sizes)})"
            )
        sizes = list(self.sizes)
    else:
        sizes = [None] * len(attrs)

    for attr, size in zip(attrs, sizes):
        if "edge_index" in attr or getattr(data, attr, None) is None:
            continue
        if size is None:
            size = data.num_edges if "edge" in attr else data.num_nodes
        setattr(data, f"{attr[:-6]}_mask", index_to_mask(getattr(data, attr), size))
        if self.replace:
            delattr(data, attr)
    return data

from mlx_graphs.transforms import IndexToMask · mlx_graphs/transforms/masks.py