Numpy Array and PyTorch Tensor’s Attributes: shape, size, and ndim

Jul. 20, 2024

NumPy array

numpy.shape(a)1: Return the shape of an array.

  • Parameters:
    • a: array_like. Input array.
  • Returns:
    • shape: tuple of ints. The elements of the shape tuple give the lengths of the corresponding array dimensions.


ndarray.size2: Number of elements in the array. Equal to np.prod(a.shape), i.e., the product of the array’s dimensions.


ndarray.ndim3: Number of array dimensions.

Examples

1
2
3
4
5
6
7
import numpy as np

a = np.array([[1,2,3,4], [5,6,7,8]])
print(a)
print(a.shape, np.shape(a))
print(a.size, np.size(a))
print(a.ndim, np.ndim(a))
1
2
3
4
5
[[1 2 3 4]
 [5 6 7 8]]
(2, 4) (2, 4)
8 8
2 2


PyTorch tensor

torch.Tensor.shape4: Returns the size of the self tensor. Alias for size.


torch.Tensor.size5 (Tensor.size(dim=None) → torch.Size or int): Returns the size of the self tensor. If dim is not specified, the returned value is a torch.Size, a subclass of tuple. If dim is specified, returns an int holding the size of that dimension.

Parameters

  • dim (int, optional) – The dimension for which to retrieve the size.


torch.Tensor.ndim6: Alias for dim().


torch.Tensor.dim7: Returns the number of dimensions of self tensor.

Examples

1
2
3
4
5
6
import torch

a = torch.tensor([[1,2,3,4], [5,6,7,8]])
print(a, a.shape)
print(a.size(), a.size(dim=0), a.size(dim=1))
print(a.ndim, a.dim())
1
2
3
4
tensor([[1, 2, 3, 4],
        [5, 6, 7, 8]]) torch.Size([2, 4])
torch.Size([2, 4]) 2 4
2 2


References