N minimum tensors in terms of absolute value

Is there a pythonic way of zeroing 10 smallest tensors(in terms of absolute value)?

Yes, you’ll basically want to get access to the indices that will sort the tensor, choose the 10 lowest, and then use those to index into your tensor and zero them out.

x = torch.randn(100)

# Get the indices that would sort x (in terms of abs value)
indices = torch.argsort(x.abs())

# choose the first 10 
indices_smallest = indices[:10]

# Zero those positions out
x[indices] = 0.0

1 Like

Weirdly enought. It causes : "Unable to get repr for <class 'torch.Tensor'>"
Is there a way to do this action on a specific dimension individually?
e.g. if x=[6,3,10,10] we do it individually on each [3,10,10]

torch.topk (torch.topk — PyTorch 1.10.0 documentation) should get you the k smallest elements along with their indices if you use the argument largest=False. Should be much faster than sorting the whole Tensor. You can then use those indices to do what you want.

2 Likes

Thaks. That’s the function, but I don’t know how to use these indeces for new assignment.
I tried scatter_ and np.ind=np.unravel_index, but they are not working.