
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to get the data type of a tensor in PyTorch?
A PyTorch tensor is homogenous, i.e., all the elements of a tensor are of the same data type. We can access the data type of a tensor using the ".dtype" attribute of the tensor. It returns the data type of the tensor.
Steps
Import the required library. In all the following Python examples, the required Python library is torch. Make sure you have already installed it.
Create a tensor and print it.
Compute T.dtype. Here T is the tensor of which we want to get the data type.
Print the data type of the tensor.
Example 1
The following Python program shows how to get the data type of a tensor.
# Import the library import torch # Create a tensor of random numbers of size 3x4 T = torch.randn(3,4) print("Original Tensor T:\n", T) # Get the data type of above tensor data_type = T.dtype # Print the data type of the tensor print("Data type of tensor T:\n", data_type)
Output
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
# Python program to get data type of a tensor # Import the library import torch # Create a tensor of random numbers of size 3x4 T = torch.Tensor([1,2,3,4]) print("Original Tensor T:\n", T) # Get the data type of above tensor data_type = T.dtype # Print the data type of the tensor print("Data type of tensor T:\n", data_type)
Output
Original Tensor T: tensor([1., 2., 3., 4.]) Data type of tensor T: torch.float32
- Related Articles
- PyTorch – How to get the exponents of tensor elements?
- How to resize a tensor in PyTorch?
- How to normalize a tensor in PyTorch?
- How to sort the elements of a tensor in PyTorch?
- How to compute the histogram of a tensor in PyTorch?
- How to access the metadata of a tensor in PyTorch?
- How to find the transpose of a tensor in PyTorch?
- How to narrow down a tensor in PyTorch?
- PyTorch – How to compute the error function of a tensor?
- How to compute the sine of elements of a tensor in PyTorch?
- How to compute the Logarithm of elements of a tensor in PyTorch?
- Creating a Tensor in Pytorch
- How to squeeze and unsqueeze a tensor in PyTorch?
- How to access and modify the values of a Tensor in PyTorch?
- How to convert an image to a PyTorch Tensor?

Advertisements