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?

Try something like this:

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

Does that solve your query?

Yes. Thanks for this solution. I also have another problem in which I need to index a whole batch of tensors like this.

a = torch.zeros((5, 30000))
indices = [[1,2], [1,4,5], [2,6], [6,8], [3,12, 110]]
a[indices] = 1

As you can see, I have a sequence of such sparse tensors. And a sequence of indices. We can definitely use a for loop to assign value 1 to each of the five 30000 dimensional vectors one by one, but its huge overhead (approx. 4 seconds in my program). Is there more efficient way to do this? Without using a for loop? Thanks

I think that you are trying to run the loop over the entire 30000 batch instead of running it five times. Try this:

for i in range(5):

Do tell me if this has a high overhead too as there would most probably be more efficient methods