PyTorch .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
dimis not provided, the returned value is atorch.Sizeobject representing the size of all dimensions. - If
dimis specified, the returned value is anintrepresenting 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
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours