dgl.sparse.from_coo

dgl.sparse.from_coo(row: Tensor, col: Tensor, val: Tensor | None = None, shape: Tuple[int, int] | None = None) SparseMatrix[source]

从坐标列表 (COO) 创建稀疏矩阵,该列表存储 (行, 列, 值) 元组列表。

参见 维基百科中的 COO

参数:
  • row (torch.Tensor) – 形状为 (nnz) 的行索引

  • col (torch.Tensor) – 形状为 (nnz) 的列索引

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

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

返回值:

稀疏矩阵

返回类型:

SparseMatrix

示例

情况1:仅包含行和列索引的稀疏矩阵。

>>> dst = torch.tensor([1, 1, 2])
>>> src = torch.tensor([2, 4, 3])
>>> A = dglsp.from_coo(dst, src)
SparseMatrix(indices=tensor([[1, 1, 2],
                             [2, 4, 3]]),
             values=tensor([1., 1., 1.]),
             shape=(3, 5), nnz=3)
>>> # Specify shape
>>> A = dglsp.from_coo(dst, src, 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:包含向量值的稀疏矩阵。

>>> dst = torch.tensor([1, 1, 2])
>>> src = torch.tensor([2, 4, 3])
>>> val = torch.tensor([[1., 1.], [2., 2.], [3., 3.]])
>>> A = dglsp.from_coo(dst, src, 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,))