.numel()
Anonymous contributor
Published Feb 10, 2025
Contribute to Docs
In PyTorch, the .numel()
method calculates the product of all dimensions of the tensor to determine its total size. It’s particularly useful to know the total count of elements regardless of the tensor’s shape or dimensionality.
Syntax
torch.numel(Tensor)
Tensor
: The input tensor whose total number of elements is to be computed.
It returns an integer representing the total number of elements in the given tensor.
Example
The following example creates a 2x3 tensor and demonstrates how .numel()
counts all elements across all dimensions:
import torch# Create a 2x3 tensorx = torch.randn(2, 3)print("Tensor x:")print(x)y = torch.numel(x)print("\nTotal number of elements:", y)
The above code produces the following output:
Tensor x:tensor([[-1.0727, 0.3469, -1.2021],[ 0.0424, 0.1689, 2.6234]])Total number of elements: 6
Note: The output varies on each run because
torch.randn(2, 3)
generates random values from a normal distribution.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly95 hours - Free course
Intro to PyTorch and Neural Networks
Learn how to use PyTorch to build, train, and test artificial neural networks in this course.Intermediate3 hours