#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.
Output:
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.
Output:
Explanation:
dtype
: The type of elements in the tensor.torch.float32
indicates 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.
Output:
Explanation:
device
: Indicates whether the tensor is on the CPU or GPU.cpu
means the tensor is on the CPU, whilecuda:0
indicates the first GPU.
#Number of Dimensions
The number of dimensions (axes) in a tensor tells you its rank.
Output:
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.
Output:
Explanation:
size()
: Returns the size of each dimension. For a tensor of shape[2, 3]
, it has 2 rows and 3 columns.