dgl.sparse.spmatrix

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

从 Coordinate 格式的索引创建稀疏矩阵。

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

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

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

返回值:

稀疏矩阵

返回类型:

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