The primary and most efficient way to get the data type of a tensor is to use the .dtype attribute. We can use the print() function to print the type in the console.
import torch # Creating a Tensor tensor = torch.tensor([11.0, 21.0, 31.0]) print(tensor.dtype) # Output: torch.float32
You can see that it created a tensor of type torch.float32 values. It is the type of elements in the tensor.
We can set the data type while creating a tensor. By default, it creates a tensor with torch.float32 type, but using the dtype attribute, we can also set it.
import torch # Float64 tensor tensor_float64 = torch.tensor([11, 21], dtype=torch.float64) print(tensor_float64.dtype) # Output: torch.float64 # Int32 tensor tensor_int32 = torch.tensor([11, 21], dtype=torch.int32) print(tensor_int32.dtype) # Output: torch.int32 # Boolean tensor tensor_bool = torch.tensor([True, False], dtype=torch.bool) print(tensor_bool.dtype) # Output: torch.bool
Getting the object type

To get the type of the object (not the individual elements’ type), use the built-in Python type() method.
import torch tensor = torch.tensor([90, 100]) print(type(tensor)) # Output: <class 'torch.Tensor'>
The above output shows that the object is of type Tensor. It can be anything from a Parameter or a custom subclass.
Getting the full type string

If you want detailed type info, you can use the .type() method on a tensor.
import torch tensor = torch.tensor([1.0]) print(tensor.type()) # Output: torch.FloatTensor
.is_* Methods
You can check if the tensor matches a specific dtype (e.g., .is_floating_point(), .is_complex()) using is.* family methods.
import torch tensor = torch.tensor([11.0, 21.0]) print(tensor.is_floating_point()) # Output: True print(tensor.is_complex()) # Output: False
The input tensor has a floating value. So, is_floating_point() method returns True. However, the values are not of type complex. So, the is_complex() method returns False.