Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get the data type of a tensor in PyTorch?
A PyTorch tensor is homogeneous, meaning all elements share the same data type. You can access the data type of any tensor using the .dtype attribute, which returns the tensor's data type.
Syntax
tensor.dtype
Where tensor is the PyTorch tensor whose data type you want to retrieve.
Example 1: Random Tensor Data Type
The following example shows how to get the data type of a randomly generated tensor ?
import torch
# Create a tensor of random numbers of size 3x4
T = torch.randn(3, 4)
print("Original Tensor T:")
print(T)
# Get the data type of the tensor
data_type = T.dtype
print("\nData type of tensor T:", data_type)
Original Tensor T:
tensor([[ 2.1768, -0.1328, 0.8155, -0.7967],
[ 0.1194, 1.0465, 0.0779, 0.9103],
[-0.1809, 1.8085, 0.8393, -0.2463]])
Data type of tensor T: torch.float32
Example 2: Integer List to Tensor
When creating a tensor from a Python list, PyTorch automatically determines the appropriate data type ?
import torch
# Create a tensor from a list
T = torch.Tensor([1, 2, 3, 4])
print("Original Tensor T:")
print(T)
# Get the data type of the tensor
data_type = T.dtype
print("\nData type of tensor T:", data_type)
Original Tensor T: tensor([1., 2., 3., 4.]) Data type of tensor T: torch.float32
Example 3: Different Data Types
You can create tensors with specific data types and verify them ?
import torch
# Create tensors with different data types
int_tensor = torch.tensor([1, 2, 3], dtype=torch.int32)
float_tensor = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float64)
bool_tensor = torch.tensor([True, False, True], dtype=torch.bool)
print("Integer tensor:", int_tensor.dtype)
print("Float tensor:", float_tensor.dtype)
print("Boolean tensor:", bool_tensor.dtype)
Integer tensor: torch.int32 Float tensor: torch.float64 Boolean tensor: torch.bool
Common PyTorch Data Types
| Data Type | PyTorch Type | Description |
|---|---|---|
| 32-bit float | torch.float32 |
Default floating point type |
| 64-bit float | torch.float64 |
Double precision float |
| 32-bit integer | torch.int32 |
Signed integer |
| Boolean | torch.bool |
True/False values |
Conclusion
Use the .dtype attribute to check any PyTorch tensor's data type. PyTorch defaults to torch.float32 for most tensor operations, but you can specify different types when creating tensors.
