PyTorch torch.is_tensor function
PyTorch torch reference manual
torch.is_tensor A utility function in PyTorch for checking 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)
Parameters:
obj(any type): The object to check.
Return Value:
bool: Ifobjis a PyTorch tensor, returnsTrue; otherwise, returnsFalse.
Usage examples
The following are some uses of torch.is_tensor Examples of the function to help you better understand how it works.
Example 1: Check a tensor
Example
import
torch
Create a PyTorch tensor
tensor
=
torch.
tensor
(
[
1
,
2
,
3
]
)
Check whether it is a tensor
result
=
torch.
is_tensor
(
tensor
)
(
result
)
Output: True
The output is:
True
In this example, we create a PyTorch tensor and use the torch.is_tensor function to check whether it is a tensor. Since tensor is indeed a tensor, the function returns True.
Example 2: Check a non-tensor object
Example
import
torch
Create a Python list
python_list
=
[
1
,
2
,
3
]
Check whether it is a tensor
result
=
torch.
is_tensor
(
python_list
)
(
result
)
Output: False
The output is:
False
In this example, we create a Python list and use the torch.is_tensor function to check whether it is a tensor. Since python_list is not a PyTorch tensor, the function returns False.
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 whether it is a tensor
result
=
torch.
is_tensor
(
numpy_array
)
(
result
)
Output: False
The output is:
False
In this example, we create a NumPy array and use the torch.is_tensor The function checks whether it is a PyTorch tensor. Since numpy_array is a NumPy array rather than a PyTorch tensor, the function returns False.
Use Cases
torch.is_tensor This function is usually 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, use
torch.is_tensorto ensure that the passed-in arguments are PyTorch tensors. - Conditional Judgment: When performing different operations based on data type in a program,
torch.is_tensorit can help you make conditional judgments.
Notes
torch.is_tensorIt can only check whether an object is a PyTorch tensor; it 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).