Tensorflow Metadata

 

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.

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)


Alright, let's go line by line and break this down so it sticks.


1. Create a random tensor

a = torch.randn((2, 3, 4), dtype=torch.float)
  • torch.randn() → Creates a tensor with random numbers from a normal distribution (mean = 0, std = 1).

  • (2, 3, 4) → Shape of the tensor:

    • 2 batches, each containing

    • 3 rows, and each row has

    • 4 columns.

  • dtype=torch.float → The type of data stored is 32-bit floating point numbers.


2. Check the data type

print(a.dtype)
  • .dtype → Tells you the data type (torch.float32 here).


3. Size and Shape

print(a.size())
print(a.shape)
  • .size() and .shape → Both give the same info: (2, 3, 4).

  • Size/shape tells you the dimensions and number of elements in each.


4. Number of dimensions

print(a.dim())
print(a.ndim)
  • .dim() or .ndim → Number of axes = 3 (batch, row, column).


5. Number of elements

print(a.numel())
  • .numel() → Total count of elements in the tensor.

    • 2 × 3 × 4 = 24 elements.


6. GPU check

print(a.is_cuda)
  • .is_cudaTrue if tensor is stored on the GPU, otherwise False.

    • Here it's False unless you explicitly send it to GPU with .to('cuda').


7. Device

print(a.device)
  • .device → Tells you where the tensor lives:

    • cpu

    • or cuda:0 (GPU index 0).


In short: This code is doing a "health check" on a PyTorch tensor—its type, shape, dimensions, element count, and where it’s stored.



Comments

Popular Posts