Shortcuts

torch.sparse_coo_tensor

torch.sparse_coo_tensor(indices, values, size=None, *, dtype=None, device=None, requires_grad=False, check_invariants=None, is_coalesced=None) 张量

构建一个COO(rdinate)格式的稀疏张量,并在给定的indices处指定值。

注意

is_coalesced 未指定或为 None 时,此函数返回一个 未合并的张量

注意

如果未指定 device 参数,则给定的 values 和索引张量的设备必须匹配。然而,如果指定了该参数,输入张量将被转换到指定的设备,并由此确定构造的稀疏张量的设备。

Parameters
  • indices (array_like) – 张量的初始数据。可以是列表、元组、 NumPy ndarray、标量和其他类型。将在内部转换为 torch.LongTensor。 索引是矩阵中非零值的坐标,因此应该是二维的,其中第一维度是张量的维度数量, 第二维度是非零值的数量。

  • values (array_like) – 张量的初始值。可以是列表、元组、 NumPy ndarray、标量和其他类型。

  • size(列表、元组或torch.Size,可选)——稀疏张量的大小。如果未提供,大小将被推断为足以容纳所有非零元素的最小大小。

Keyword Arguments
  • dtype (torch.dtype, 可选) – 返回张量所需的数据类型。 默认值:如果为 None,则从 values 推断数据类型。

  • 设备 (torch.device, 可选) – 返回张量所需的设备。 默认值:如果为 None,则使用默认张量类型的当前设备 (参见 torch.set_default_device())。device 将是 CPU 用于 CPU 张量类型,以及当前 CUDA 设备用于 CUDA 张量类型。

  • requires_grad (布尔值, 可选) – 如果 autograd 应该记录对返回张量的操作。默认值:False

  • check_invariants (bool, 可选) – 如果检查稀疏张量不变量。 默认值:由 torch.sparse.check_sparse_tensor_invariants.is_enabled() 返回, 最初为 False。

  • is_coalesced (布尔值, 可选) – 当``True``时,调用者负责提供与合并张量相对应的张量索引。如果check_invariants标志为False,则在未满足前提条件的情况下不会引发错误,这将导致结果静默不正确。要强制合并,请在生成的张量上使用coalesce()。 默认值:None:除了简单情况(例如nnz < 2)外,生成的张量的is_coalesced设置为False`

示例:

>>> i = torch.tensor([[0, 1, 1],
...                   [2, 0, 2]])
>>> v = torch.tensor([3, 4, 5], dtype=torch.float32)
>>> torch.sparse_coo_tensor(i, v, [2, 4])
tensor(indices=tensor([[0, 1, 1],
                       [2, 0, 2]]),
       values=tensor([3., 4., 5.]),
       size=(2, 4), nnz=3, layout=torch.sparse_coo)

>>> torch.sparse_coo_tensor(i, v)  # 形状推断
tensor(indices=tensor([[0, 1, 1],
                       [2, 0, 2]]),
       values=tensor([3., 4., 5.]),
       size=(2, 3), nnz=3, layout=torch.sparse_coo)

>>> torch.sparse_coo_tensor(i, v, [2, 4],
...                         dtype=torch.float64,
...                         device=torch.device('cuda:0'))
tensor(indices=tensor([[0, 1, 1],
                       [2, 0, 2]]),
       values=tensor([3., 4., 5.]),
       device='cuda:0', size=(2, 4), nnz=3, dtype=torch.float64,
       layout=torch.sparse_coo)

# 创建一个空的稀疏张量,具有以下不变量:
#   1. sparse_dim + dense_dim = len(SparseTensor.shape)
#   2. SparseTensor._indices().shape = (sparse_dim, nnz)
#   3. SparseTensor._values().shape = (nnz, SparseTensor.shape[sparse_dim:])
#
# 例如,创建一个空的稀疏张量,nnz = 0,dense_dim = 0 和
# sparse_dim = 1(因此 indices 是一个形状为 (1, 0) 的二维张量)
>>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1])
tensor(indices=tensor([], size=(1, 0)),
       values=tensor([], size=(0,)),
       size=(1,), nnz=0, layout=torch.sparse_coo)

# 并创建一个空的稀疏张量,nnz = 0,dense_dim = 1 和
# sparse_dim = 1
>>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), torch.empty([0, 2]), [1, 2])
tensor(indices=tensor([], size=(1, 0)),
       values=tensor([], size=(0, 2)),
       size=(1, 2), nnz=0, layout=torch.sparse_coo)
优云智算