Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.is_tensor function

PyTorch torch.is_tensor function


PyTorch torch reference manual 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:

Return Value:


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

)

print

(

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

)

print

(

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

)

print

(

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:

  1. Debug code: When you need to confirm whether a variable is a PyTorch tensor, you can use this function for a quick check.
  2. Type checking: When writing functions that need to handle multiple data types, use torch.is_tensor to ensure that the passed-in arguments are PyTorch tensors.
  3. Conditional Judgment: When performing different operations based on data type in a program,torch.is_tensor it can help you make conditional judgments.

Notes


PyTorch torch reference manual PyTorch torch reference manual