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(rdinate) 格式的稀疏张量,并在给定的
indices
位置指定值。注意
当
is_coalesced
未指定或为None
时,此函数返回一个 未合并的张量。注意
如果未指定
device
参数,则给定的values
和 indices 张量的设备必须匹配。但是,如果指定了该参数,则输入张量将被转换为给定的设备,并反过来确定构造的稀疏张量的设备。- 参数
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()
)。device
对于 CPU 张量类型将是 CPU,对于 CUDA 张量类型将是当前的 CUDA 设备。pin_memory (bool, 可选) – 如果设置,返回的张量将在 pinned 内存中分配。仅适用于 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()
。默认值: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)