Getting type from dtype

The dtype attribute of a PyTorch tensor can be used to get its type information.

The code below creates a tensor with the float type and prints the type information from dtype. You can try the code at the end of this lesson.

a = torch.tensor([1, 2, 3], dtype=torch.float)
print(a.dtype)

Getting size from shape and size()

PyTorch provides two ways to get the tensor size; these are shape, an attribute, and size(), which is a function.

a = torch.ones((3, 4))
print(a.shape)
print(a.size())

Getting the number of dim

As shown in the code below, the number of dimensions of a tensor in Pytorch can be obtained using the attribute ndim or using the function dim() or its alias ndimension().

a = torch.ones((3, 4, 6))
print(a.ndim)
print(a.dim())

Getting the number of elements

PyTorch provides two ways to get the number of elements of a tensor, nelement() and numel(). Both of them are functions.

a = torch.ones((3, 4, 6))
print(a.numel())

Checking if the tensor is on GPU

is_cuda is an attribute of a tensor. It is true if the tensor is stored on the GPU. Otherwise, it will be set to false.

Getting the device

device is an attribute of a tensor. It contains the information of the device being used by the tensor.

a = torch.ones((3, 4, 6))
print(a.device)
import torch
a = torch.randn((2, 3, 4), dtype=torch.float)
print("The dtype of tensor a is {}.\n".format(a.dtype))
print("The size of tensor a is {}.".format(a.size()))
print("The shape of tensor a is {}.\n".format(a.shape))
print("The dims of tensor a is {}.".format(a.dim()))
print("The dims of tensor a is {}.\n".format(a.ndim))
print("The number of element of tensor a is {}.\n".format(a.numel()))
print("The GPU is {}.\n".format(a.is_cuda))
print("The device is {}.".format(a.device))