Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does Pytorch has an opposite of topk that returns the smallest k elements?

The topk operation in Pytorch "Returns the k largest elements of the given input tensor along a given dimension." (from here). But does it have an opposite that returns the smallest k elements?

top k

x = torch.arange(1., 6.)
print(x)
>>> tensor([ 1.,  2.,  3.,  4.,  5.])
torch.topk(x, 3)
>>> torch.return_types.topk(values=tensor([5., 4., 3.]), indices=tensor([4, 3, 2]))

min k –> does this exist?

x = torch.arange(1., 6.)
print(x)
>>> tensor([ 1.,  2.,  3.,  4.,  5.])
torch.mink(x, 3) # doesn't run
>>> torch.return_types.mink(values=tensor([1., 2., 3.]), indices=tensor([0, 1, 2]))

I know that a way around it is to multiply the tensor by -1:

torch.topk(-x, 3)

But wondering if this mink operation already exist.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Check the documention page https://pytorch.org/docs/stable/generated/torch.topk.html

There is a keyword argument to get the smallest values (and indices)

largest (bool, optional) – controls whether to return largest or smallest elements

so mink is just functools.partial(torch.topk, largest=False)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading