dgl.sparse.from_csr

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

从压缩稀疏行 (CSR) 格式创建稀疏矩阵。

请参阅 维基百科上的 CSR

对于稀疏矩阵的第 i 行

  • 非零元素的列索引存储在 indices[indptr[i]: indptr[i+1]]

  • 相应的值存储在 val[indptr[i]: indptr[i+1]]

参数:
  • indptr (torch.Tensor) – 指向列索引的指针,形状为 (N + 1),其中 N 是行数

  • indices (torch.Tensor) – 列索引,形状为 (nnz)

  • val (torch.Tensor, 可选) – 值,形状为 (nnz)(nnz, D)。如果为 None,它将是一个形状为 (nnz) 且填充为 1 的张量。

  • shape (tuple[int, int], 可选) – 如果未指定,将从 indptrindices 推断,即 (len(indptr) - 1, indices.max() + 1)。否则,shape 应不小于此推断形状。

返回:

稀疏矩阵

返回类型:

SparseMatrix

示例

案例1:没有值的稀疏矩阵

[[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)

案例2:带有标量/向量值的稀疏矩阵。下面的示例是带有向量数据的。

>>> 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,))