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.
>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)