torch.sparse_coo_tensor#
- torch.sparse_coo_tensor(indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None, is_coalesced=None) Tensor #
构造一个 COO(坐标)格式的稀疏张量,在给定
indices
处具有指定的值。注意
当
is_coalesced
未指定或为None
时,此函数返回一个 未合并的张量。注意
如果未指定
device
参数,则给定values
和索引张量的设备必须匹配。然而,如果指定了该参数,则输入张量将被转换为给定设备,并以此确定构造的稀疏张量的设备。- 参数
indices (array_like) – 张量的初始数据。可以是列表、元组、NumPy
ndarray
、标量及其他类型。内部将转换为torch.LongTensor
。索引是矩阵中非零值的坐标,因此应该是二维的,其中第一维是张量维度数,第二维是非零值数。values (array_like) – 张量的初始值。可以是列表、元组、NumPy
ndarray
、标量及其他类型。size (list, tuple, or
torch.Size
, optional) – 稀疏张量的大小。如果未提供,则大小将推断为足以容纳所有非零元素的最小大小。
- 关键字参数
dtype (
torch.dtype
, optional) – 返回张量所需的数据类型。默认值:如果为 None,则从values
推断数据类型。device (
torch.device
, optional) – 返回张量所需的设备。默认值:如果为 None,则使用默认张量类型的当前设备(参见torch.set_default_device()
)。device
对于 CPU 张量类型将是 CPU,对于 CUDA 张量类型将是当前的 CUDA 设备。pin_memory (bool, optional) – 如果设置,返回的张量将分配到锁定内存中。仅适用于 CPU 张量。默认值:
False
。requires_grad (bool, optional) – Autograd 是否应该记录返回张量上的操作。默认值:
False
。check_invariants (bool, optional) – 是否检查稀疏张量不变量。默认值:由
torch.sparse.check_sparse_tensor_invariants.is_enabled()
返回,初始为 False。is_coalesced (bool, optional) – 当为``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) # Shape inference 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) # Create an empty sparse tensor with the following invariants: # 1. sparse_dim + dense_dim = len(SparseTensor.shape) # 2. SparseTensor._indices().shape = (sparse_dim, nnz) # 3. SparseTensor._values().shape = (nnz, SparseTensor.shape[sparse_dim:]) # # For instance, to create an empty sparse tensor with nnz = 0, dense_dim = 0 and # sparse_dim = 1 (hence indices is a 2D tensor of shape = (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) # and to create an empty sparse tensor with nnz = 0, dense_dim = 1 and # 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)