dgl.sparse.from_csr
- dgl.sparse.from_csr(indptr: Tensor, indices: Tensor, val: Tensor | None = None, shape: Tuple[int, int] | None = None) SparseMatrix [source]
从压缩稀疏行(CSR)格式创建稀疏矩阵。
参见维基百科中的CSR。
对于稀疏矩阵的第i行
非零元素的列索引存储在
indices[indptr[i]: indptr[i+1]]
相应的值存储在
val[indptr[i]: indptr[i+1]]
- Parameters:
indptr (torch.Tensor) – 指向形状为
(N + 1)
的列索引的指针,其中N
是行数indices (torch.Tensor) – 形状为
(nnz)
的列索引val (torch.Tensor, optional) – 形状为
(nnz)
或(nnz, D)
的值。如果为 None,它将是一个形状为(nnz)
的张量,并用 1 填充。shape (tuple[int, int], optional) – 如果未指定,它将从
indptr
和indices
推断,即(len(indptr) - 1, indices.max() + 1)
。 否则,shape
不应小于此值。
- Returns:
稀疏矩阵
- Return type:
示例
案例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,))