How to check if an object is a PyTorch Tensor?

PyTorchServer Side ProgrammingProgramming

To check if an object is a tensor or not, we can use the torch.is_tensor() method. It returns True if the input is a tensor; False otherwise.

Syntax

torch.is_tensor(input)

Parameters

  • input – The object to be checked, if it is a tensor or not .

Output

It returns True if the input is a tensor; else False.

Steps

  • Import the required library. The required library is torch.

  • Define a tensor or other object.

  • Check if the created object is a tensor or not using torch.is_tensor(input).

  • Display the result.

Example 1

# import the required library
import torch

# create an object x
x = torch.rand(4)
print(x)

# check if the above created object is a tensor
print(torch.is_tensor(x))

Output

tensor([0.9270, 0.2194, 0.2078, 0.5716])
True

Example 2

# import the required library
import torch

# define an object x
x = 4

# check if the above created object is a tensor
if torch.is_tensor(x):
   print ("The input object is a Tensor.")
else:
   print ("The input object is not a Tensor.")

Output

The input object is not a Tensor.

In Example 2, torch.is_tensor(x) returns False, hence the input object is not a Tensor.

raja
Updated on 06-Dec-2021 12:44:53

Advertisements