torch.Tensor.to_sparse#
- Tensor.to_sparse(sparseDims)→Tensor#
Returns a sparse copy of the tensor. PyTorch supports sparse tensors incoordinate format.
- Parameters
sparseDims (int,optional) – the number of sparse dimensions to include in the new sparse tensor
Example:
>>>d=torch.tensor([[0,0,0],[9,0,10],[0,0,0]])>>>dtensor([[ 0, 0, 0], [ 9, 0, 10], [ 0, 0, 0]])>>>d.to_sparse()tensor(indices=tensor([[1, 1], [0, 2]]), values=tensor([ 9, 10]), size=(3, 3), nnz=2, layout=torch.sparse_coo)>>>d.to_sparse(1)tensor(indices=tensor([[1]]), values=tensor([[ 9, 0, 10]]), size=(3, 3), nnz=1, layout=torch.sparse_coo)
- to_sparse(*,layout=None,blocksize=None,dense_dim=None)→Tensor
Returns a sparse tensor with the specified layout and blocksize. Ifthe
selfis strided, the number of dense dimensions could bespecified, and a hybrid sparse tensor will be created, withdense_dim dense dimensions andself.dim() - 2 - dense_dim batchdimension.Note
If the
selflayout and blocksize parameters matchwith the specified layout and blocksize, returnself. Otherwise, return a sparse tensor copy ofself.- Parameters
layout (
torch.layout, optional) – The desired sparselayout. One oftorch.sparse_coo,torch.sparse_csr,torch.sparse_csc,torch.sparse_bsr, ortorch.sparse_bsc. Default: ifNone,torch.sparse_coo.blocksize (list, tuple,
torch.Size, optional) – Block sizeof the resulting BSR or BSC tensor. For other layouts,specifying the block size that is notNonewill result in aRuntimeError exception. A block size must be a tuple of lengthtwo such that its items evenly divide the two sparse dimensions.dense_dim (int,optional) – Number of dense dimensions of theresulting CSR, CSC, BSR or BSC tensor. This argument should beused only if
selfis a strided tensor, and must be avalue between 0 and dimension ofselftensor minus two.
Example:
>>>x=torch.tensor([[1,0],[0,0],[2,3]])>>>x.to_sparse(layout=torch.sparse_coo)tensor(indices=tensor([[0, 2, 2], [0, 0, 1]]), values=tensor([1, 2, 3]), size=(3, 2), nnz=3, layout=torch.sparse_coo)>>>x.to_sparse(layout=torch.sparse_bsr,blocksize=(1,2))tensor(crow_indices=tensor([0, 1, 1, 2]), col_indices=tensor([0, 0]), values=tensor([[[1, 0]], [[2, 3]]]), size=(3, 2), nnz=2, layout=torch.sparse_bsr)>>>x.to_sparse(layout=torch.sparse_bsr,blocksize=(2,1))RuntimeError: Tensor size(-2) 3 needs to be divisible by blocksize[0] 2>>>x.to_sparse(layout=torch.sparse_csr,blocksize=(3,1))RuntimeError: to_sparse for Strided to SparseCsr conversion does not use specified blocksize>>>x=torch.tensor([[[1],[0]],[[0],[0]],[[2],[3]]])>>>x.to_sparse(layout=torch.sparse_csr,dense_dim=1)tensor(crow_indices=tensor([0, 1, 1, 3]), col_indices=tensor([0, 0, 1]), values=tensor([[1], [2], [3]]), size=(3, 2, 1), nnz=3, layout=torch.sparse_csr)