Skip to content

from_scipy_sparse_matrix

from_scipy_sparse_matrix(matrix: Any) -> tuple[array, array]

Converts a scipy.sparse matrix (or array) to an edge_index and edge weights.

Parameters:

Name Type Description Default
matrix Any

A scipy.sparse matrix, in any format.

required

Returns:

Type Description
array

A tuple (edge_index, edge_weights) with an int32 [2, nnz]

array

edge_index and the stored values (float64 values are converted to

tuple[array, array]

float32). Explicitly stored zeros are kept.

Example:

import scipy.sparse as sp

matrix = sp.coo_matrix(([1.0, 2.0], ([0, 1], [1, 0])), shape=(2, 2))
from_scipy_sparse_matrix(matrix)
# (mx.array([[0, 1], [1, 0]]), mx.array([1.0, 2.0]))
Source code in mlx_graphs/utils/sparse.py
def from_scipy_sparse_matrix(matrix: Any) -> tuple[mx.array, mx.array]:
    """
    Converts a ``scipy.sparse`` matrix (or array) to an ``edge_index`` and
    edge weights.

    Args:
        matrix: A ``scipy.sparse`` matrix, in any format.

    Returns:
        A tuple ``(edge_index, edge_weights)`` with an int32 ``[2, nnz]``
        ``edge_index`` and the stored values (float64 values are converted to
        float32). Explicitly stored zeros are kept.

    Example:

    .. code-block:: python

        import scipy.sparse as sp

        matrix = sp.coo_matrix(([1.0, 2.0], ([0, 1], [1, 0])), shape=(2, 2))
        from_scipy_sparse_matrix(matrix)
        # (mx.array([[0, 1], [1, 0]]), mx.array([1.0, 2.0]))
    """
    coo = matrix.tocoo()
    edge_index = mx.array(np.stack([coo.row, coo.col]).astype(np.int32))
    return edge_index, _to_mlx(np.asarray(coo.data))

from mlx_graphs.utils import from_scipy_sparse_matrix · mlx_graphs/utils/sparse.py