PyTorch torch.is_tensor() method is “used to check if a variable is tensor or not.” It returns a boolean value: True if the object is a tensor and False otherwise.
Syntax
torch.is_tensor(obj)
Parameters
obj (Object): The object you want to check.
Example
import torch
# Creating a tensor
tensor = torch.tensor([1, 2, 3, 4])
# Checking if the object is a tensor
is_tensor_result_1 = torch.is_tensor(tensor)
# Checking if a list is a tensor
list_obj = [1, 2, 3, 4]
is_tensor_result_2 = torch.is_tensor(list_obj)
print(f"Is 'tensor' a tensor? {is_tensor_result_1}")
print(f"Is 'list_obj' a tensor? {is_tensor_result_2}")
Output
Is 'tensor' a tensor? True
Is 'list_obj' a tensor? False
The torch.is_tensor() method is helpful in scenarios where you want to ensure that an object is a tensor before performing tensor-specific operations.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.