如何在 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)输出结果
当您运行上述Python3代码时,它将产生以下输出。
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)输出结果
当您运行上述Python3代码时,它将产生以下输出。
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