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 ¶
在指定的
indices
处构建具有指定值的 COO(坐标)格式的稀疏张量注意
此函数在未指定
is_coalesced
或None
时返回一个未合并的张量。注意
如果未指定
device
参数,则给定values
和索引张量的设备必须匹配。然而,如果指定了该参数,则输入张量将被转换为指定的设备,进而确定构造的稀疏张量的设备。- 参数:
索引(array_like)- 张量的初始数据。可以是列表、元组、NumPy
ndarray
、标量和其他类型。将内部转换为torch.LongTensor
。索引是矩阵中非零值的坐标,因此应该是二维的,其中第一维是张量维度数,第二维是非零值的数量。值(array_like)- 张量的初始值。可以是列表、元组、NumPy
ndarray
、标量和其他类型。大小(list、tuple 或
torch.Size
,可选)- 稀疏张量的大小。如果不提供,大小将推断为足以容纳所有非零元素的最小大小。
- 关键字参数:
dtype (
torch.dtype
,可选) – 返回张量的期望数据类型。默认:如果为 None,则从values
推断数据类型。device (
torch.device
,可选) – 返回张量的期望设备。默认:如果为 None,则使用当前设备进行默认张量类型(见torch.set_default_device()
)。device
将是 CPU 张量类型的 CPU,对于 CUDA 张量类型是当前 CUDA 设备。pin_memory (bool,可选) – 如果设置,返回的张量将在固定内存中分配。仅适用于 CPU 张量。默认:
False
。requires_grad (bool,可选) – 如果 autograd 应记录对返回张量的操作。默认:
False
。check_invariants (bool,可选) – 如果检查稀疏张量不变量。默认:如
torch.sparse.check_sparse_tensor_invariants.is_enabled()
返回,最初为 False。is_coalesced (bool,可选) – 当为 True 时,调用者负责提供对应于合并张量的张量索引。如果
check_invariants
标志为 False,如果未满足先决条件,则不会引发错误,这可能导致静默错误的结果。要强制合并,请使用coalesce()
在结果 Tensor 上。默认:None:除了简单情况(例如 nnz < 2)外,结果 Tensor 的 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)