如何在 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