#
Getting Information from Tensors
Understanding tensor properties is crucial when working with PyTorch. In this section, we'll explore how to retrieve and understand key information about tensors, including:
Shape: The dimensions of the tensor.Data Type: The type of data the tensor holds.Device: Where the tensor is stored (CPU or GPU).Number of Dimensions: The number of axes in the tensor.Size of Each Dimension: The length of each axis.
#
Shape of a Tensor
The shape of a tensor indicates its dimensions. For example, a tensor with shape [2, 3] has 2 rows and 3 columns.
import torch
# Create a 2x3 tensor
tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
print("Shape of Tensor:", tensor.shape)
Output:
Shape of Tensor: torch.Size([2, 3])
Explanation:
shape: The dimensions of the tensor. In this case, it shows[2, 3], meaning the tensor has 2 rows and 3 columns.
#
Data Type of a Tensor
The data type of a tensor defines what kind of data it contains, such as integers or floating-point numbers.
import torch
# Create a tensor with default data type
tensor = torch.tensor([1.0, 2.0, 3.0])
print("Data Type of Tensor:", tensor.dtype)
Output:
Data Type of Tensor: torch.float32
Explanation:
dtype: The type of elements in the tensor.torch.float32indicates 32-bit floating-point numbers.
#
Device of a Tensor
The device attribute tells you where the tensor is stored—either on the CPU or a GPU.
import torch
# Create a tensor on CPU
tensor_cpu = torch.tensor([1.0, 2.0, 3.0])
print("Device of Tensor on CPU:", tensor_cpu.device)
# Create a tensor on GPU (if CUDA is available)
if torch.cuda.is_available():
tensor_gpu = torch.tensor([1.0, 2.0, 3.0], device='cuda')
print("Device of Tensor on GPU:", tensor_gpu.device)
else:
print("CUDA is not available. Tensor GPU creation skipped.")
Output:
Device of Tensor on CPU: cpu
Device of Tensor on GPU: cuda:0
Explanation:
device: Indicates whether the tensor is on the CPU or GPU.cpumeans the tensor is on the CPU, whilecuda:0indicates the first GPU.
#
Number of Dimensions
The number of dimensions (axes) in a tensor tells you its rank.
import torch
# Create a 3-D tensor
tensor_3d = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("Number of Dimensions:", tensor_3d.ndim)
Output:
Number of Dimensions: 3
Explanation:
ndim: Returns the number of dimensions. A3-D tensor has three dimensions, which might represent depth, rows, and columns.
#
Size of Each Dimension
To get the size of each dimension, use the .size() method.
import torch
# Create a tensor
tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
print("Size of Each Dimension:", tensor.size())
Output:
Size of Each Dimension: torch.Size([2, 3])
Explanation:
size(): Returns the size of each dimension. For a tensor of shape[2, 3], it has 2 rows and 3 columns.