Ruchit
Ruchit

Reputation: 356

How to create a 1D sparse tensors from given list of indices and values?

I have a list of indices and values. I want to create a sparse tensor of size 30000 from this indices and values as follows.

indices = torch.LongTensor([1,3,4,6])
values = torch.FloatTensor([1,1,1,1])

So, I want to build a 30k dimensional sparse tensor in which the indices [1,3,4,6] are ones and the rest are zeros. How can I do that?

I want to store the sequences of such sparce tensors efficiently.

Upvotes: 2

Views: 1561

Answers (1)

jodag
jodag

Reputation: 22204

In general the indices tensor needs to have shape (sparse_dim, nnz) where nnz is the number of non-zero entries and sparse_dim is the number of dimensions for your sparse tensor.

In your case nnz = 4 and sparse_dim = 1 since your desired tensor is 1D. All we need to do to make your indices work is to insert a unitary dimension at the front of indices to make it shape (1, 4).

t = torch.sparse_coo_tensor(indices.unsqueeze(0), values, (30000,))

or equivalently

t = torch.sparse.FloatTensor(indices.unsqueeze(0), values, (30000,))

Keep in mind only a limited number of operations are supported on sparse tensors. To convert a tensor back to it's dense (inefficient) representation you can use the to_dense method

t_dense = t.to_dense()

Upvotes: 4

Related Questions