PyTorch torch.is_tensor() Method

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.

Leave a Comment