Metadata của tensor bao gồm kích thước (size/shape) và số lượng phần tử. Để lấy size dùng .size(), shape dùng .shape (hai cách cho cùng kết quả). Số phần tử dùng torch.numel().
Các bước
Nhập torch.
Định nghĩa tensor.
Lấy metadata: .size(), .shape, torch.numel().
In tensor và metadata.
Ví dụ 1: Tensor 2D kích thước 4x3
import torch
# Tạo tensor 4x3
T = torch.Tensor([[1, 2, 3], [2, 1, 3], [2, 3, 5], [5, 6, 4]])
print("T:\n", T)
# Lấy metadata
size_T = T.size()
print("Kích thước tensor T:\n", size_T)
# Dùng .shape
print("Shape của tensor:\n", T.shape)
# Số phần tử
num_T = torch.numel(T)
print("Số phần tử trong tensor T:\n", num_T)
Kết quả
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
Ví dụ 2: Tensor 3D ngẫu nhiên 4x3x2
import torch
# Tensor ngẫu nhiên 4x3x2
T = torch.randn(4, 3, 2)
print("T:\n", T)
size_T = T.size()
print("Kích thước tensor T:\n", size_T)
print("Shape của tensor:\n", T.shape)
num_T = torch.numel(T)
print("Số phần tử trong tensor T:\n", num_T)
Kết quả
T: tensor([[[-1.1806, 0.5569], [2.2237, 0.9709], [0.4775, -0.2491]], ...]) size of tensor T: torch.Size([4, 3, 2]) Shape of tensor: torch.Size([4, 3, 2]) Number of elements in tensor T: 24