Rate this Page

torch.sort#

torch.sort(input,dim=-1,descending=False,*,stable=False,out=None)#

Sorts the elements of theinput tensor along a given dimensionin ascending order by value.

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

Ifdescending isTrue then the elements are sorted in descendingorder by value.

Ifstable isTrue then the sorting routine becomes stable, preservingthe order of equivalent elements.

A namedtuple of (values, indices) is returned, where thevalues are thesorted values andindices are the indices of the elements in the originalinput tensor.

Parameters
  • input (Tensor) – the input tensor.

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

  • descending (bool,optional) – controls the sorting order (ascending or descending)

Keyword Arguments
  • stable (bool,optional) – makes the sorting routine stable, which guarantees that the orderof equivalent elements is preserved.

  • out (tuple,optional) – the output tuple of (Tensor,LongTensor) that canbe optionally given to be used as output buffers

Example:

>>>x=torch.randn(3,4)>>>sorted,indices=torch.sort(x)>>>sortedtensor([[-0.2162,  0.0608,  0.6719,  2.3332],        [-0.5793,  0.0061,  0.6058,  0.9497],        [-0.5071,  0.3343,  0.9553,  1.0960]])>>>indicestensor([[ 1,  0,  2,  3],        [ 3,  1,  0,  2],        [ 0,  3,  1,  2]])>>>sorted,indices=torch.sort(x,0)>>>sortedtensor([[-0.5071, -0.2162,  0.6719, -0.5793],        [ 0.0608,  0.0061,  0.9497,  0.3343],        [ 0.6058,  0.9553,  1.0960,  2.3332]])>>>indicestensor([[ 2,  0,  0,  1],        [ 0,  1,  1,  2],        [ 1,  2,  2,  0]])>>>x=torch.tensor([0,1]*9)>>>x.sort()torch.return_types.sort(    values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]),    indices=tensor([ 2, 16,  4,  6, 14,  8,  0, 10, 12,  9, 17, 15, 13, 11,  7,  5,  3,  1]))>>>x.sort(stable=True)torch.return_types.sort(    values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]),    indices=tensor([ 0,  2,  4,  6,  8, 10, 12, 14, 16,  1,  3,  5,  7,  9, 11, 13, 15, 17]))