How to sort the elements of a tensor in PyTorch?

Published January 02, 2022

For a variety of reasons, you may want to sort out tensor items in a specific order. To sort out these elements, you only need to use the torch. Sort (TM) method.  You simply need to use the torch.sort (TM) method to sort these elements. It returns the sorted elements as well as an array of the index values in the original tensor as the results of this operation.

You can either compute the column-wise, row-wise, or 2D tensors.

 

How to sort the elements of a tensor in PyTorch

PyTorch makes it simple to sort tensor elements. Follow these simple steps to get started:

 Step 1: Add the torch library to your application

Step 2: Proceed and create a PyTorch tensor and print it.

Step 3: The torch may be used to sort the tensor's elements. kind of (input, dim). This value should be assigned to a new variable called "v". We may arrange these items along dim, which is the same dimension as input. Dim is set to 1 while sorting rows, whereas dim is set to 0 when sorting columns. v [0] gives access to the values that have been sorted, whereas v [1] gives access to the indexes of the sorted items.

Step 4:  Finally, output the sensor values with the indices of the sorted values.

 

Example

The sorting of tensor elements is shown in the following Python code

 

import torch

T = torch.Tensor([2.334,4.433,-4.33,-0.433,5, 4.443])

print("Unsorted Tensor:\n", T)

v = torch.sort(T)

print("Sorted values:\n", v[0])

print("Indices values:\n", v[1])

 

 

Output:

Unsorted Tensor:

   tensor([ 2.3340, 4.4330, -4.3300, -0.4330, 5.0000, 4.4430])

Sorted values:

   tensor([-4.3300, -0.4330, 2.3340, 4.4330, 4.4430, 5.0000])

Indices values:

   tensor([2, 3, 0, 1, 5, 4])

 

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

433 Views