PyTorch torch.is_tensor Function
Pytorch torch Reference Manual
torch.is_tensoris a utility function in PyTorch used to check whether a given object is a tensor.
In deep learning and scientific computing, tensors are the most fundamental data structure, so being able to quickly determine whether an object is a tensor is very useful.
Function Definition
torch.is_tensor(obj)
Parameter:
obj(any type): The object to check.
Return Value:
bool: ifobjis a PyTorch tensor, returnsTrue; otherwise, returnFalse。
Usage Examples
The following are some uses oftorch.is_tensorAn example of the function to help you better understand how it works.
Example 1: Check Tensor
Example
import torch
# Create a PyTorch tensor
tensor = torch.tensor([1, 2, 3])
# Check if it is a tensor
result = torch.is_tensor(tensor)
print(result) # Output: True
The output result is:
True
In this example, we created a PyTorch tensor and usedtorch.is_tensorThe function checks whether it is a tensor. Sincetensorit is indeed a tensor, the function returnsTrue。
Example 2: Check Non-Tensor Object
Example
import torch
# Create a Python list
python_list = [1, 2, 3]
# Check if it is a tensor
result = torch.is_tensor(python_list)
print(result) # Output: False
The output result is:
False
In this example, we created a Python list and usedtorch.is_tensorThe function checks whether it is a tensor. Sincepython_listis not a PyTorch tensor, the function returnsFalse。
Example 3: Check Other Types of Objects
Example
import torch
import numpy as np
# Create a NumPy array
numpy_array = np.array([1, 2, 3])
# Check if it is a tensor
result = torch.is_tensor(numpy_array)
print(result) # Output: False
The output result is:
False
In this example, we created a NumPy array and usedtorch.is_tensorThe function checks whether it is a PyTorch tensor. Sincenumpy_arrayis a NumPy array rather than a PyTorch tensor, the function returnsFalse。
Use Cases
torch.is_tensorThe function is typically very useful in the following scenarios:
- Debug Code: When you need to confirm whether a variable is a PyTorch tensor, you can use this function for a quick check.
- Type Checking: When writing functions that need to handle multiple data types, using
torch.is_tensorcan ensure that the passed-in parameter is a PyTorch tensor.
- Conditional Judgment: When performing different operations based on data types in a program,
torch.is_tensorcan help you make conditional judgments.
Notes
torch.is_tensorcan only check whether an object is a PyTorch tensor and cannot be used to check other types of tensors (such as NumPy arrays).
- If you need to check whether an object is a NumPy array, you can use
isinstance(obj, np.ndarray)。
Pytorch torch Reference Manual