How to find the k-th and the top "k" elements of a tensor in PyTorch?

Published January 03, 2022

PyTorch includes a method to determine a tensor's k-th element. kthvalue (). It outputs the value of the original tensor's component, and the tensor's k-th member's in ascending order.

If you intend to obtain the top "K" element, then you need to use the torch.top () method. This technique will always return the tensor's biggest or top "K" element.

How do you locate the K-th and top "K" components of a tensor in PyTorch

Step 1: To get started, install the torch library. This is a must-have library.

Step 2: Construct and output a PyTorch tensor after installing the torch library.

Step 3: Determine the k-th value (input, k).  This method will return two tensors: one for the "index" and one for the "value."

 Step 4: Find the highest point (input, k). This method will return two tensors, one with the top "K" elements and one with the indices.

Step 5: Display the index and value of the tensor element for the K-th time.

 

Example

import torch

T = torch.Tensor([10.677,4.433,-4.3300,-0.433,5, 4.223])

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

value, index = torch.kthvalue(T, 2)

print("2rd element value:", value)

print("2rd element index:", index)

 

 

Output:

Original Tensor:

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

2rd element value: tensor(-4.3300)

2rd element index: tensor(0)

 

 

 

Download Source code

 

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

280 Views