Skip to content

ClusterData

ClusterData(
    data: GraphData,
    num_parts: int,
    partition: Optional[Union[array, ndarray]] = None,
    method: Literal["auto", "metis", "balanced"] = "auto",
    num_iters: int = 10,
)

Partitions a graph into num_parts clusters, for Cluster-GCN training ("Cluster-GCN: An Efficient Algorithm for Training Deep and Large Graph Convolutional Networks"), following PyG's ClusterData. Use it with ClusterLoader.

PyG partitions with METIS. Here, METIS (through the optional pymetis package) is used only if it is installed or method="metis" is set; otherwise a dependency-free balanced partitioner is used (see balanced_partition()): partitions are balanced but differ from METIS', with a usually larger edge cut. Any custom partition can also be given with partition.

cluster_data[i] is the subgraph induced by the nodes of cluster i (edges between clusters are dropped), with n_id and e_id.

Parameters:

Name Type Description Default
data GraphData

The graph to partition.

required
num_parts int

Number of clusters. Ignored if partition is given (max(partition) + 1 is used).

required
partition Optional[Union[array, ndarray]]

Optional cluster id of every node, [num_nodes], to use instead of computing one.

None
method Literal['auto', 'metis', 'balanced']

"auto" (METIS if pymetis is installed, else "balanced"), "metis" or "balanced". Defaults to "auto"

'auto'
num_iters int

Refinement rounds of the "balanced" partitioner. Defaults to 10

10

Attributes:

Name Type Description
cluster

Cluster id of every node (numpy array).

node_perm

Node ids sorted by cluster (numpy array).

partptr

Start of every cluster in node_perm, [num_parts + 1].

Example:

from mlx_graphs.loaders import ClusterData, ClusterLoader

cluster_data = ClusterData(data, num_parts=100)
loader = ClusterLoader(cluster_data, batch_size=10, shuffle=True)
for batch in loader:
    out = model(batch.node_features, batch.edge_index)

Methods:

Name Description
nodes_of

Global ids of the nodes of the given cluster(s), cluster by cluster.

subgraph

Subgraph induced by the union of the given clusters.

Source code in mlx_graphs/loaders/cluster.py
def __init__(
    self,
    data: GraphData,
    num_parts: int,
    partition: Optional[Union[mx.array, np.ndarray]] = None,
    method: Literal["auto", "metis", "balanced"] = "auto",
    num_iters: int = 10,
):
    if method not in ("auto", "metis", "balanced"):
        raise ValueError(
            f"`method` must be 'auto', 'metis' or 'balanced' (got '{method}')"
        )
    self.data = data
    self.num_nodes = data.num_nodes
    self.num_edges = data.num_edges

    if partition is not None:
        cluster = to_numpy(partition).reshape(-1).astype(np.int64)
        if cluster.size != self.num_nodes:
            raise ValueError(
                f"`partition` has {cluster.size} entries, expected "
                f"{self.num_nodes} (one per node)."
            )
        if cluster.size and cluster.min() < 0:
            raise ValueError("`partition` must contain non-negative ids.")
        num_parts = int(cluster.max()) + 1 if cluster.size else 0
        self.method = "custom"
    else:
        has_metis = importlib.util.find_spec("pymetis") is not None
        if method == "metis" or (method == "auto" and has_metis):
            cluster = _metis_partition(data.edge_index, self.num_nodes, num_parts)
            self.method = "metis"
        else:
            cluster = balanced_partition(
                data.edge_index, self.num_nodes, num_parts, num_iters=num_iters
            )
            self.method = "balanced"

    self.num_parts = num_parts
    self.cluster = cluster
    self.node_perm = np.argsort(cluster, kind="stable")
    self.partptr = np.zeros(num_parts + 1, dtype=np.int64)
    np.cumsum(np.bincount(cluster, minlength=num_parts), out=self.partptr[1:])
    self._adj = Adjacency(data.edge_index, self.num_nodes)

nodes_of

nodes_of(parts: Union[int, ndarray, list]) -> ndarray

Global ids of the nodes of the given cluster(s), cluster by cluster.

Source code in mlx_graphs/loaders/cluster.py
def nodes_of(self, parts: Union[int, np.ndarray, list]) -> np.ndarray:
    """Global ids of the nodes of the given cluster(s), cluster by cluster."""
    parts = np.atleast_1d(np.asarray(parts, dtype=np.int64))
    starts = self.partptr[parts]
    return self.node_perm[segment_arange(starts, self.partptr[parts + 1] - starts)]

subgraph

subgraph(parts: Union[int, ndarray, list]) -> GraphData

Subgraph induced by the union of the given clusters.

Source code in mlx_graphs/loaders/cluster.py
def subgraph(self, parts: Union[int, np.ndarray, list]) -> GraphData:
    """Subgraph induced by the union of the given clusters."""
    n_id = self.nodes_of(parts)
    edge_index, e_id = self._adj.induced_subgraph(n_id)
    return slice_graph(
        self.data,
        n_id,
        e_id,
        edge_index,
        num_nodes=self.num_nodes,
        num_edges=self.num_edges,
        n_id=index_array(n_id, self.num_nodes),
        e_id=index_array(e_id, self.num_edges),
    )

from mlx_graphs.loaders import ClusterData · mlx_graphs/loaders/cluster.py