Skip to content

DMoNPooling

DMoNPooling(
    node_features_dim: Union[int, List[int]], k: int, dropout: float = 0.0
)

Bases: Module

The spectral modularity pooling operator from the "Graph Clustering with Graph Neural Networks" paper.

\[ \mathbf{X}^{\prime} &= {\mathrm{softmax}(\mathbf{S})}^{\top} \cdot \mathbf{X} \mathbf{A}^{\prime} &= {\mathrm{softmax}(\mathbf{S})}^{\top} \cdot \mathbf{A} \cdot \mathrm{softmax}(\mathbf{S}) \]

where the assignments \(\mathbf{S}\) are computed by an MLP from the node features. Also returns the spectral (modularity) loss

\[ \mathcal{L}_s = - \frac{1}{2m} \cdot{\mathrm{Tr}(\mathbf{S}^{\top} \mathbf{B} \mathbf{S})}, \]

where \(\mathbf{B}\) is the modularity matrix, the orthogonality loss (see dense_mincut_pool()) and the cluster loss

\[ \mathcal{L}_c = \frac{\sqrt{C}}{n} {\left\|\sum_i\mathbf{C_i}^{\top}\right\|}_F - 1. \]

The output features go through a SELU activation, and the output adjacency is normalized as in dense_mincut_pool(). As in PyG (2.8), the cluster loss of a batch is the mean of the cluster norms times the mean of the inverse graph sizes.

Parameters:

Name Type Description Default
node_features_dim Union[int, List[int]]

Size of the input node features, or a list of sizes [input, hidden_1, ...] of the MLP computing the assignments (which ends with k).

required
k int

Number of clusters.

required
dropout float

Dropout probability of the assignment logits. Default: 0.0

0.0

Example:

import mlx.core as mx
from mlx_graphs.nn import DMoNPooling

pool = DMoNPooling(16, k=4)
adj = (mx.random.uniform(shape=(2, 10, 10)) > 0.7).astype(mx.float32)
x = mx.random.normal((2, 10, 16))
s, x, adj, spectral_loss, ortho_loss, cluster_loss = pool(adj, x)
>>> x.shape
(2, 4, 16)

Methods:

Name Description
__call__

Pools the graphs.

Source code in mlx_graphs/nn/pooling/dense_pool.py
def __init__(
    self, node_features_dim: Union[int, List[int]], k: int, dropout: float = 0.0
):
    super().__init__()
    from mlx_graphs.nn.models.basic_gnn import MLP

    if isinstance(node_features_dim, int):
        node_features_dim = [node_features_dim]
    self.node_features_dim = list(node_features_dim)
    self.k = k
    self.mlp = MLP(self.node_features_dim + [k], act=None, norm=None)
    self.dropout = nn.Dropout(dropout) if dropout > 0.0 else None

__call__

__call__(
    adj: array, node_features: array, mask: Optional[array] = None
) -> Tuple[array, array, array, array, array, array]

Pools the graphs.

Parameters:

Name Type Description Default
adj array

Adjacency matrices of shape [batch_size, num_nodes, num_nodes] (or [num_nodes, num_nodes]).

required
node_features array

Node features of shape [batch_size, num_nodes, num_features] (or [num_nodes, num_features]).

required
mask Optional[array]

Optional boolean mask of shape [batch_size, num_nodes] of the real (non-padding) nodes. Default: None

None

Returns:

Type Description
array

A tuple `(s, node_features, adj, spectral_loss, ortho_loss,

array

cluster_loss)with the soft assignmentss` of shape

array

[batch_size, num_nodes, k] and the pooled graphs.

Source code in mlx_graphs/nn/pooling/dense_pool.py
def __call__(
    self,
    adj: mx.array,
    node_features: mx.array,
    mask: Optional[mx.array] = None,
) -> Tuple[mx.array, mx.array, mx.array, mx.array, mx.array, mx.array]:
    """Pools the graphs.

    Args:
        adj: Adjacency matrices of shape ``[batch_size, num_nodes,
            num_nodes]`` (or ``[num_nodes, num_nodes]``).
        node_features: Node features of shape ``[batch_size, num_nodes,
            num_features]`` (or ``[num_nodes, num_features]``).
        mask: Optional boolean mask of shape ``[batch_size, num_nodes]``
            of the real (non-padding) nodes. Default: ``None``

    Returns:
        A tuple ``(s, node_features, adj, spectral_loss, ortho_loss,
        cluster_loss)`` with the soft assignments ``s`` of shape
        ``[batch_size, num_nodes, k]`` and the pooled graphs.
    """
    adj, x = _batched(adj, node_features)
    s = self.mlp(x)
    if self.dropout is not None:
        s = self.dropout(s)
    s = mx.softmax(s, axis=-1)

    batch_size, num_nodes, _ = x.shape
    C = s.shape[-1]
    if mask is None:
        mask = mx.ones((batch_size, num_nodes), dtype=x.dtype)
    mask = mask.reshape(batch_size, num_nodes, 1).astype(x.dtype)
    x, s = x * mask, s * mask

    s_t = s.swapaxes(1, 2)
    out = _selu(s_t @ x)
    out_adj = (s_t @ adj) @ s

    degrees = adj.sum(axis=-1)[..., None] * mask  # [B, N, 1]
    m = degrees.sum(axis=(1, 2)) / 2  # [B]
    ca = s_t @ degrees  # [B, C, 1]
    cb = degrees.swapaxes(1, 2) @ s  # [B, 1, C]
    normalizer = (ca @ cb) / 2 / m[:, None, None]
    spectral_loss = (-_trace(out_adj - normalizer) / 2 / m).mean()

    ortho_loss = _ortho_loss(s)

    cluster_size = s.sum(axis=1)  # [B, C]
    cluster_norm = _frobenius(cluster_size, axes=1)  # [B]
    # [B] / [B, 1] broadcasts to [B, B], as in PyG
    cluster_loss = cluster_norm[None, :] / mask.sum(axis=1) * C**0.5 - 1
    cluster_loss = cluster_loss.mean()

    return (
        s,
        out,
        _normalize_pooled_adj(out_adj),
        spectral_loss,
        ortho_loss,
        cluster_loss,
    )

from mlx_graphs.nn import DMoNPooling · mlx_graphs/nn/pooling/dense_pool.py