Rate this Page

torch.topk#

torch.topk(input,k,dim=None,largest=True,sorted=True,*,out=None)#

Returns thek largest elements of the giveninput tensor alonga given dimension.

Ifdim is not given, the last dimension of theinput is chosen.

Iflargest isFalse then thek smallest elements are returned.

A namedtuple of(values, indices) is returned with thevalues andindices of the largestk elements of each row of theinput tensor in thegiven dimensiondim.

The boolean optionsorted ifTrue, will make sure that the returnedk elements are themselves sorted

Note

When usingtorch.topk, the indices of tied elements are not guaranteed to be stableand may vary across different invocations.

Parameters:
  • input (Tensor) – the input tensor.

  • k (int) – the k in “top-k”

  • dim (int,optional) – the dimension to sort along

  • largest (bool,optional) – controls whether to return largest orsmallest elements

  • sorted (bool,optional) – controls whether to return the elementsin sorted order

Keyword Arguments:

out (tuple,optional) – the output tuple of (Tensor, LongTensor) that can beoptionally given to be used as output buffers

Example:

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