Skip to content

AddLaplacianEigenvectorPE

AddLaplacianEigenvectorPE(
    k: int,
    attr_name: Optional[str] = "laplacian_eigenvector_pe",
    is_undirected: bool = False,
    **kwargs: Any,
)

Bases: BaseTransform

Adds the Laplacian eigenvector positional encoding from "Benchmarking Graph Neural Networks" to each node, as PyG's AddLaplacianEigenvectorPE.

The encoding holds the eigenvectors of the k smallest non-trivial eigenvalues of the symmetrically normalized Laplacian \(\mathbf{L} = \mathbf{I} - \mathbf{D}^{-1/2} \mathbf{A} \mathbf{D}^{-1/2}\) (the eigenvector of the smallest eigenvalue is skipped). The edge_weights attribute is used as \(\mathbf{A}\) if it exists. As eigenvectors are only defined up to their sign, the sign of each one is flipped at random (from mx.random, so reproducible with mx.random.seed), as in PyG.

The eigenvectors are computed on the host: with NumPy for graphs of less than SPARSE_THRESHOLD nodes, and with scipy.sparse.linalg (which is then required) otherwise.

Parameters:

Name Type Description Default
k int

Number of non-trivial eigenvectors, which is the size of the encoding. Must be smaller than the number of nodes.

required
attr_name Optional[str]

Name of the attribute in which the [num_nodes, k] float32 encoding is stored. If None, the encoding is appended to the node features instead. Default: "laplacian_eigenvector_pe"

'laplacian_eigenvector_pe'
is_undirected bool

If True, the graph is assumed to be undirected, which allows a faster symmetric eigensolver. Default: False

False
**kwargs Any

Additional arguments of scipy.sparse.linalg.eigs (or eigsh if is_undirected), used for large graphs.

{}

Example:

graph = GraphData(edge_index=mx.array([[0, 1, 1, 2], [1, 0, 2, 1]]))
graph = AddLaplacianEigenvectorPE(k=1, is_undirected=True)(graph)
graph.laplacian_eigenvector_pe
# mx.array([[0.7071], [0.0], [-0.7071]]) (up to the sign)

Methods:

Name Description
process

Adds the Laplacian eigenvector positional encoding to data.

Source code in mlx_graphs/transforms/spectral.py
def __init__(
    self,
    k: int,
    attr_name: Optional[str] = "laplacian_eigenvector_pe",
    is_undirected: bool = False,
    **kwargs: Any,
):
    self.k = k
    self.attr_name = attr_name
    self.is_undirected = is_undirected
    self.kwargs = kwargs

process

process(data: GraphData) -> GraphData

Adds the Laplacian eigenvector positional encoding to data.

Parameters:

Name Type Description Default
data GraphData

The graph to transform.

required

Returns:

Type Description
GraphData

The graph with the encoding.

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

    Args:
        data: The graph to transform.

    Returns:
        The graph with the encoding.
    """
    num_nodes = _num_nodes(data)
    if self.k >= num_nodes:
        raise ValueError(
            f"k={self.k} must be smaller than the number of nodes ({num_nodes})"
        )
    weights = mx.array(_edge_weights(data).astype(np.float32))
    edge_index, values = get_laplacian(
        data.edge_index, weights, normalization="sym", num_nodes=num_nodes
    )
    rows, cols = np.asarray(edge_index).astype(np.int64)
    values = np.asarray(values).astype(np.float64)

    if num_nodes < self.SPARSE_THRESHOLD:
        laplacian = np.zeros((num_nodes, num_nodes), dtype=np.float64)
        np.add.at(laplacian, (rows, cols), values)
        eig_fn = np.linalg.eigh if self.is_undirected else np.linalg.eig
        eig_vals, eig_vecs = eig_fn(laplacian)
    else:
        try:
            import scipy.sparse as sp
            from scipy.sparse.linalg import eigs, eigsh
        except ImportError as error:
            raise ImportError(
                "scipy is required by AddLaplacianEigenvectorPE for graphs of "
                f"{self.SPARSE_THRESHOLD} nodes or more, run `pip install scipy`"
            ) from error
        # float32, as in PyG: the Laplacian values are float32 (rounded),
        # so in float64 ARPACK has to separate clusters of eigenvalues
        # that differ only by that rounding, e.g. the zero eigenvalue of
        # every connected component, and fails to converge (on Cora).
        laplacian = sp.coo_matrix(
            (values.astype(np.float32), (rows, cols)),
            shape=(num_nodes, num_nodes),
        ).tocsr()
        eig_fn = eigsh if self.is_undirected else eigs
        eig_vals, eig_vecs = eig_fn(
            laplacian,
            k=self.k + 1,
            which="SA" if self.is_undirected else "SR",
            return_eigenvectors=True,
            **self.kwargs,
        )

    eig_vecs = np.real(eig_vecs[:, eig_vals.argsort()])
    encoding = eig_vecs[:, 1 : self.k + 1].astype(np.float32)
    sign = 2 * mx.random.randint(0, 2, (self.k,)) - 1
    encoding = mx.array(encoding) * sign.astype(mx.float32)

    if self.attr_name is None:
        return _add_node_features(data, encoding, cat=True)
    setattr(data, self.attr_name, encoding)
    return data

from mlx_graphs.transforms import AddLaplacianEigenvectorPE · mlx_graphs/transforms/spectral.py