How PyTorch Tensors Get the Index of a Specific Value

Here are three ways to get the index of a specific value in PyTorch Tensors.

  1. Using PyTorch’s where()
  2. Using Numpy’s where()
  3. Using Python’s index()

Method 1: Using PyTorch’s where()

PyTorch’s where() function returns a tuple of indices where a given condition is true.

To find the index of a specific value, you can use PyTorch’s where() function.

import torch

tensor = torch.tensor([11, 19, 21, 46, 52])

value = 21

indices = torch.where(tensor == value)[0]

print(indices.item())

Output

2

Method 2: Using Numpy’s where()

PyTorch tensors can easily be converted to numpy arrays using the .numpy() method. Once it’s a numpy array, you can use numpy’s where() function to get the index.

import torch
import numpy as np

tensor = torch.tensor([11, 19, 21, 46, 52])
value = 21

index = np.where(tensor.numpy() == value)[0]
print(index)

Output

[2]

Method 3: Using Python’s index() function

You can convert the PyTorch tensor to a Python list and then use the index() method of the list to get the index. This method may not be as efficient for larger tensors but is straightforward for smaller ones.

import torch

tensor = torch.tensor([11, 19, 21, 46, 52])
value = 21

index = tensor.tolist().index(value)
print(index)

Output

2

Conclusion

The best and easiest way to get the index of a specific value in PyTorch is to use PyTorch’s where() method. If you are working solely within the PyTorch ecosystem (especially with larger tensors), use PyTorch’s where().

PyTorch’s where() method is typically faster than the other methods for large tensors since it’s GPU-accelerated if you’re using a CUDA tensor.

That’s it!

Leave a Comment