Skip to content

ChebConv

ChebConv(
    node_features_dim: int,
    out_features_dim: int,
    K: int,
    normalization: Optional[Literal["sym", "rw"]] = "sym",
    bias: bool = True,
    **kwargs,
)

Bases: MessagePassing

Chebyshev spectral graph convolution layer from "Convolutional Neural Networks on Graphs with Fast Localized Spectral Filtering" paper.

\[ \mathbf{H} = \sum_{k=1}^{K} \mathbf{Z}^{(k)} \mathbf{W}_k + \mathbf{b}, \]

where the \(\mathbf{Z}^{(k)}\) are computed recursively by

\[ \mathbf{Z}^{(1)} &= \mathbf{X} \mathbf{Z}^{(2)} &= \mathbf{\hat{L}} \mathbf{X} \mathbf{Z}^{(k)} &= 2 \mathbf{\hat{L}} \mathbf{Z}^{(k-1)} - \mathbf{Z}^{(k-2)} \]

and \(\mathbf{\hat{L}} = \frac{2 \mathbf{L}}{\lambda_{\max}} - \mathbf{I}\) is the scaled graph Laplacian.

Parameters:

Name Type Description Default
node_features_dim int

Size of input node features

required
out_features_dim int

Size of output node embeddings

required
K int

Number of Chebyshev terms, i.e. the filter reaches K - 1 hops

required
normalization Optional[Literal['sym', 'rw']]

Normalization of the graph Laplacian \(\mathbf{L}\), with \(\mathbf{D}\) the (weighted) degree matrix (default: "sym"):

  • None: \(\mathbf{L} = \mathbf{D} - \mathbf{A}\)
  • "sym": \(\mathbf{L} = \mathbf{I} - \mathbf{D}^{-1/2} \mathbf{A} \mathbf{D}^{-1/2}\)
  • "rw": \(\mathbf{L} = \mathbf{I} - \mathbf{D}^{-1} \mathbf{A}\)
'sym'
bias bool

Whether to add a bias to the output

True
**kwargs

Arguments of MessagePassing

{}

Example:

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

edge_index = mx.array([[0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2]])
node_features = mx.ones((5, 16))

conv = ChebConv(16, 32, K=3)
h = conv(edge_index, node_features)
>>> h.shape
(5, 32)

# Largest eigenvalue of the Laplacian, if it is known
h = conv(edge_index, node_features, lambda_max=1.8)

Methods:

Name Description
__call__

Computes the forward pass of ChebConv.

Source code in mlx_graphs/nn/conv/cheb_conv.py
def __init__(
    self,
    node_features_dim: int,
    out_features_dim: int,
    K: int,
    normalization: Optional[Literal["sym", "rw"]] = "sym",
    bias: bool = True,
    **kwargs,
):
    kwargs.setdefault("aggr", "add")
    super(ChebConv, self).__init__(**kwargs)

    if K < 1:
        raise ValueError(f"K must be at least 1, got {K}")
    if normalization not in (None, "sym", "rw"):
        raise ValueError(
            f"normalization must be None, 'sym' or 'rw', got {normalization!r}"
        )

    self.node_features_dim = node_features_dim
    self.out_features_dim = out_features_dim
    self.K = K
    self.normalization = normalization

    self.lins = [
        Linear(node_features_dim, out_features_dim, bias=False) for _ in range(K)
    ]
    if bias:
        self.bias = mx.zeros((out_features_dim,))

__call__

__call__(
    edge_index: array,
    node_features: array,
    edge_weights: Optional[array] = None,
    batch: Optional[array] = None,
    lambda_max: Optional[Union[float, array]] = None,
) -> array

Computes the forward pass of ChebConv.

Parameters:

Name Type Description Default
edge_index array

Input edge index of shape [2, num_edges]

required
node_features array

Input node features

required
edge_weights Optional[array]

Optional scalar weight per edge, of shape [num_edges] or [num_edges, 1]. Default: None

None
batch Optional[array]

Graph index of every node, of shape [num_nodes]. Only needed when lambda_max has one value per graph. Default: None

None
lambda_max Optional[Union[float, array]]

Largest eigenvalue of the graph Laplacian, either one value or an array with one value per graph of the batch. If None, twice the largest entry of the Laplacian is used: 2 for the "sym" and "rw" normalizations, twice the largest degree without normalization. Default: None

None

Returns:

Type Description
array

The computed node embeddings

Source code in mlx_graphs/nn/conv/cheb_conv.py
def __call__(
    self,
    edge_index: mx.array,
    node_features: mx.array,
    edge_weights: Optional[mx.array] = None,
    batch: Optional[mx.array] = None,
    lambda_max: Optional[Union[float, mx.array]] = None,
) -> mx.array:
    r"""Computes the forward pass of ChebConv.

    Args:
        edge_index: Input edge index of shape `[2, num_edges]`
        node_features: Input node features
        edge_weights: Optional scalar weight per edge, of shape `[num_edges]`
            or `[num_edges, 1]`. Default: ``None``
        batch: Graph index of every node, of shape `[num_nodes]`. Only
            needed when ``lambda_max`` has one value per graph.
            Default: ``None``
        lambda_max: Largest eigenvalue of the graph Laplacian, either one
            value or an array with one value per graph of the batch. If
            ``None``, twice the largest entry of the Laplacian is used:
            2 for the ``"sym"`` and ``"rw"`` normalizations, twice the
            largest degree without normalization. Default: ``None``

    Returns:
        mx.array: The computed node embeddings
    """
    num_nodes = node_features.shape[0]
    if edge_weights is None and (
        lambda_max is None or isinstance(lambda_max, (int, float))
    ):
        # The scaled Laplacian of an unweighted graph only depends on the
        # graph: computed once per edge_index array.
        graph = edge_index
        edge_index, norm = _norm_cache.get(
            graph,
            ("cheb", num_nodes, self.normalization, lambda_max),
            lambda: self._scaled_laplacian(
                graph, num_nodes, None, batch, lambda_max
            ),
        )
    else:
        edge_index, norm = self._scaled_laplacian(
            edge_index, num_nodes, edge_weights, batch, lambda_max
        )

    previous = node_features
    out = self.lins[0](previous)

    if len(self.lins) > 1:
        current = self.propagate(
            edge_index=edge_index,
            node_features=node_features,
            message_kwargs={"edge_weights": norm},
        )
        out = out + self.lins[1](current)

        for lin in self.lins[2:]:
            following = self.propagate(
                edge_index=edge_index,
                node_features=current,
                message_kwargs={"edge_weights": norm},
            )
            following = 2.0 * following - previous
            out = out + lin(following)
            previous, current = current, following

    if "bias" in self:
        out = out + self.bias

    return out

from mlx_graphs.nn import ChebConv · mlx_graphs/nn/conv/cheb_conv.py