如何在 PyTorch 中获取张量的数据类型?
PyTorch 张量是同质的,即张量中的所有元素都具有相同的数据类型。我们可以通过使用张量的“.dtype” 属性来访问其数据类型。它将返回张量的数据类型。
步骤
导入必需的代码库。在所有以下 Python 示例中,所需的 Python 代码库都为torch。确保你已安装过它。
创建一个张量并进行打印。
计算T.dtype。此处 T 为我们需要获取其数据类型的张量。
打印该张量的数据类型。
示例 1
以下 Python 程序展示了如何获取张量的数据类型。
# 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)输出
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
示例 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)输出
Original Tensor T: tensor([1., 2., 3., 4.]) Data type of tensor T: torch.float32
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP