dgl.sparse.spmatrix

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

从坐标格式索引创建稀疏矩阵。

Parameters:
  • indices (tensor.Tensor) – 索引是矩阵中非零元素的坐标, 其形状应为 (2, N),其中第一行是行索引,第二行是非零元素的列索引。

  • val (tensor.Tensor, optional) – 形状为 (nnz)(nnz, D) 的值。如果为 None,它将是一个形状为 (nnz) 的张量,并用 1 填充。

  • shape (tuple[int, int], optional) – 如果未指定,将从 rowcol 推断, 即 (row.max() + 1, col.max() + 1)。否则,shape 应不小于此值。

Returns:

稀疏矩阵

Return type:

SparseMatrix

示例

案例1:带有行和列索引但没有值的稀疏矩阵。

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

案例2:带有标量值的稀疏矩阵。

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

案例3:具有向量值的稀疏矩阵。

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