.size()
Published Oct 12, 2024
Contribute to Docs
The size()
method in PyTorch returns a torch.Size
object containing the size (shape) information of a tensor. It serves as a fundamental function for dynamically obtaining the tensor’s shape during operations. Specific dimensions can be accessed by indexing into the torch.Size
object, which functions like a tuple.
Syntax
tensor.size(dim=None)
tensor
: The PyTorch tensor on which the.size()
method is called.dim
(Optional): Specifies the dimension for which to retrieve the size. The default value isNone
.- If
dim
is not provided, the returned value is atorch.Size
object representing the size of all dimensions. - If
dim
is specified, the returned value is anint
representing the size of the given dimension.
- If
Example
The following example shows how to use the .size()
method:
import torcht = torch.empty(3, 4, 5)print(t.size())print(t.size(dim=1))
The code above generates the following output:
torch.Size([3, 4, 5])4
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
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours