如何在 PyTorch 中访问张量的元数据?
我们把张量的尺寸(形状)和张量中的元素数量访问为张量的元数据。若要访问张量的尺寸,我们使用 .size() 方法,而张量的形状通过 .shape 访问。
.size() 和 .shape 都产生相同的结果。我们使用 torch.numel() 函数找到张量中的元素总量。
步骤
导入必需的库。此处,必需的库是 torch。确保已安装 torch 应用程序。
定义一个 PyTorch 张量。
查找张量的元数据。使用 .size() 和 .shape 访问张量的尺寸和形状。使用 torch.numel() 访问张量中的元素数量。
打印张量和元数据以更好的理解。
示例 1
# Python Program to access meta-data of a Tensor
# import necessary libraries
import torch
# Create a tensor of size 4x3
T = torch.Tensor([[1,2,3],[2,1,3],[2,3,5],[5,6,4]])
print("T:\n", T)
# Find the meta-data of tensor
# Find the size of the above tensor "T"
size_T = T.size()
print("size of tensor T:\n", size_T)
# Other method to get size using .shape
print("Shape of tensor:\n", T.shape)
# Find the number of elements in the tensor "T"
num_T = torch.numel(T)
print("Number of elements in tensor T:\n", num_T)输出
运行上述 Python 3 代码时,将生成以下输出。
T: tensor([[1., 2., 3.], [2., 1., 3.], [2., 3., 5.], [5., 6., 4.]]) size of tensor T: torch.Size([4, 3]) Shape of tensor: torch.Size([4, 3]) Number of elements in tensor T: 12
示例 2
# Python Program to access meta-data of a Tensor
# import the libraries
import torch
# Create a tensor of random numbers
T = torch.randn(4,3,2)
print("T:\n", T)
# Find the meta-data of tensor
# Find the size of the above tensor "T"
size_T = T.size()
print("size of tensor T:\n", size_T)
# Other method to get size using .shape
print("Shape of tensor:\n", T.shape)
# Find the number of elements in the tensor "T"
num_T = torch.numel(T)
print("Number of elements in tensor T:\n", num_T)输出
运行上述 Python 3 代码时,将生成以下输出。
T: tensor([[[-1.1806, 0.5569], [ 2.2237, 0.9709], [ 0.4775, -0.2491]], [[-0.9703, 1.9916], [ 0.1998, -0.6501], [-0.7489, -1.3013]], [[ 1.3191, 2.0049], [-0.1195, 0.1860], [-0.6061, -1.2451]], [[-0.6044, 0.6153], [-2.2473, -0.1531], [ 0.5341, 1.3697]]]) size of tensor T: torch.Size([4, 3, 2]) Shape of tensor: torch.Size([4, 3, 2]) Number of elements in tensor T: 24
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP