Handling the Dimensions and Sizes of PyTorch Tensors
Definition
Let’s call a PyTorch tensor.
The following pair is called the size of .
Let’s refer to as the dimension of .
Call a -dimensional tensor.
are the sizes of the respective th dimensions, which are integers greater than . Since this is Python, note that it starts from the th dimension.
>>> A = torch.ones(2,3,4)
tensor([[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]],
[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]]])
For example, the dimension of such a tensor is , its size is , and its dimension is .
.dim()
, .ndim
Returns the dimension of the tensor.
>>> A.dim()
3
>>> A.ndim
3
.shape
, .size()
Returns the size of the tensor.
>>> A.shape
torch.Size([2, 3, 4])
>>> A.shape[1]
3
>>> A.size()
torch.Size([2, 3, 4])
>>> A.size(2)
4
.view()
, .reshape()
Changes the size of the tensor while keeping its dimension.
If you use as an argument, the size is adjusted automatically. For instance, as in the following example, changing a tensor of size with .view(4,-1)
changes its size to .
>>> A.reshape(8,3)
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
>>> A.view(3,-1)
tensor([[1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1.]])
>>> A.view(-1,4)
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])