dgl.sparse.from_csr

dgl.sparse.from_csr(indptr: Tensor, indices: Tensor, val: Tensor | None = None, shape: Tuple[int, int] | None = None) SparseMatrix[source]

Creates a sparse matrix from compress sparse row (CSR) format.

See CSR in Wikipedia.

For row i of the sparse matrix

  • the column indices of the non-zero elements are stored in indices[indptr[i]: indptr[i+1]]

  • the corresponding values are stored in val[indptr[i]: indptr[i+1]]

Parameters:
  • indptr (torch.Tensor) – Pointer to the column indices of shape (N + 1), where N is the number of rows

  • indices (torch.Tensor) – The column indices of shape (nnz)

  • val (torch.Tensor, optional) – The values of shape (nnz) or (nnz, D). If None, it will be a tensor of shape (nnz) filled by 1.

  • shape (tuple[int, int], optional) – If not specified, it will be inferred from indptr and indices, i.e., (len(indptr) - 1, indices.max() + 1). Otherwise, shape should be no smaller than this.

Returns:

Sparse matrix

Return type:

SparseMatrix

Examples

Case1: Sparse matrix without values

[[0, 1, 0],
 [0, 0, 1],
 [1, 1, 1]]
>>> indptr = torch.tensor([0, 1, 2, 5])
>>> indices = torch.tensor([1, 2, 0, 1, 2])
>>> A = dglsp.from_csr(indptr, indices)
SparseMatrix(indices=tensor([[0, 1, 2, 2, 2],
                             [1, 2, 0, 1, 2]]),
             values=tensor([1., 1., 1., 1., 1.]),
             shape=(3, 3), nnz=5)
>>> # Specify shape
>>> A = dglsp.from_csr(indptr, indices, shape=(3, 5))
SparseMatrix(indices=tensor([[0, 1, 2, 2, 2],
                             [1, 2, 0, 1, 2]]),
             values=tensor([1., 1., 1., 1., 1.]),
             shape=(3, 5), nnz=5)

Case2: Sparse matrix with scalar/vector values. Following example is with vector data.

>>> indptr = torch.tensor([0, 1, 2, 5])
>>> indices = torch.tensor([1, 2, 0, 1, 2])
>>> val = torch.tensor([[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]])
>>> A = dglsp.from_csr(indptr, indices, val)
SparseMatrix(indices=tensor([[0, 1, 2, 2, 2],
                             [1, 2, 0, 1, 2]]),
             values=tensor([[1, 1],
                            [2, 2],
                            [3, 3],
                            [4, 4],
                            [5, 5]]),
             shape=(3, 3), nnz=5, val_size=(2,))