Python – PyTorch numel() method

PyTorch torch.numel() method returns the total number of elements in the input tensor.

Syntax: torch.numel(input)

Arguments

  • input: This is input tensor.

Return: It returns the length of the input tensor.

Let’s see this concept with the help of few examples:
Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

# Importing the PyTorch library 
import torch 
    
# A constant tensor of size n
a = torch.randn(4, 6)
print(a)
  
# Applying the numel function and 
# storing the result in 'out'
out = torch.numel(a)
print(out)

chevron_right


Output:

-0.8263  0.9807 -1.4688  0.2117 -0.8356 -0.0228
-0.8815  1.3652 -0.1892 -1.1241  0.2755  1.3006
 0.0559  0.2389  0.7944  2.6587 -2.0908  1.2973
-0.2056  0.4110  0.2163  0.3091  0.5559 -0.2468
[torch.FloatTensor of size 4x6]
24

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Importing the PyTorch library 
import torch 
    
# A constant tensor of size n
a = torch.FloatTensor([1, 4, 6, 8])
print(a)
  
# Applying the numel function and 
# storing the result in 'out'
out = torch.numel(a)
print(out)

chevron_right


Output:

 1
 4
 6
 8
[torch.FloatTensor of size 4]
4
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.