How to access the metadata of a tensor in PyTorch?
Last Updated :
01 Nov, 2022
In this article, we are going to see how to access the metadata of a tensor in PyTorch using Python.
PyTorch in Python is a machine learning library. Also, it is free and open-source. It was firstly introduced by the Facebook AI research team. A tensor in PyTorch is similar to a NumPy array. But it doesn’t have any knowledge of deep learning, graphs, etc. It is considered a normal n-dimensional array that can be used for mathematical computation. It differs from a Numpy in terms of its execution platform. Unlike Numpy array, a tensor is capable of running on CPU or GPU.
Example 1:
In this example, each of the statements used in the source code has been discussed below,
The first step is to import the torch library. We need to create a tensor. For example, we have created a tensor of dimension 5 X 3. Now to access metadata that is, the size and shape of the tensor we have used the .size() and .shape method. We have used the torch.numel() method. It gives us the total number of elements in the created tensor. Finally, we are printing these data to the console.
Python3
import torch
tensor = torch.Tensor([[ 5 , 1 , 7 ],[ 7 , 2 , 9 ],[ 4 , 7 , 9 ],
[ 8 , 12 , 14 ],[ 2 , 4 , 7 ]])
print ( "tensor:\n" , tensor)
tensor_size = tensor.size()
print ( "The size of tensor:\n" , tensor_size)
print ( "The shape of tensor:\n" , tensor.shape)
size = torch.numel(tensor)
print ( "Total number of elements in tensor:\n" , size)
|
Output:
tensor:
tensor([[ 5., 1., 7.],
[ 7., 2., 9.],
[ 4., 7., 9.],
[ 8., 12., 14.],
[ 2., 4., 7.]])
The size of tensor:
torch.Size([5, 3])
The shape of tensor:
torch.Size([5, 3])
Total number of elements in tensor:
15
Example 2:
In this example, each of the statements used in the source code has been discussed below,
The first step is to import the torch library. We need to create a tensor. For example, we have created a tensor of numbers from 1 to 9 (inclusive). Now to access metadata that is, the size and shape of the tensor we have used the .size() and .shape method. We have used the torch.numel() method. It gives us the total number of elements in the created tensor. Finally, we are printing these data to the console.
Python3
import torch
data = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
tensor = torch.tensor(data)
print (tensor)
tensor_size = tensor.size()
print ( "The size of tensor:\n" , tensor_size)
print ( "The shape of tensor:\n" , tensor.shape)
size = torch.numel(tensor)
print ( "Total number of elements in tensor:\n" , size)
|
Output:
tensor([1, 2, 3, 4, 5, 6, 7, 8, 9])
The size of tensor:
torch.Size([9])
The shape of tensor:
torch.Size([9])
Total number of elements in tensor:
9
Share your thoughts in the comments
Please Login to comment...