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
和 indices 张量(s) 的设备必须匹配。但是,如果指定了该参数,则输入张量将被转换到指定的设备,并由此决定构造的稀疏张量的设备。- 参数
indices (array_like) – 张量的初始数据。可以是列表、元组、NumPy
ndarray
、标量及其他类型。内部将转换为torch.LongTensor
。索引是矩阵中非零值的坐标,因此应为二维,其中第一维表示张量的维度数,第二维表示非零值的数量。values (array_like) – 张量的初始值。可以是列表、元组、NumPy
ndarray
、标量及其他类型。size (list, tuple, 或
torch.Size
, 可选) – 稀疏张量的大小。如果未提供,则将推断为足以容纳所有非零元素的最小尺寸。
- 关键字参数
dtype (
torch.dtype
, 可选) – 返回张量所需的数据类型。默认值: 如果为 None,则从values
推断数据类型。device (
torch.device
, 可选) – 返回张量所需的设备。默认值: 如果为 None,则使用默认张量类型的当前设备(参见torch.set_default_device()
)。对于 CPU 张量类型,device
将是 CPU;对于 CUDA 张量类型,将是当前的 CUDA 设备。pin_memory (bool, 可选) – 如果设置,返回的张量将分配在锁页内存中。仅适用于 CPU 张量。默认值:
False
。requires_grad (bool, 可选) – 如果自动微分应对返回张量上的操作进行记录。默认值:
False
。check_invariants (bool, 可选) – 是否检查稀疏张量不变性。默认值: 由
torch.sparse.check_sparse_tensor_invariants.is_enabled()
返回,初始值为 False。is_coalesced (bool, 可选) – 当为 ``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)