.stack()
Anonymous contributor
Published Nov 20, 2024
Contribute to Docs
In PyTorch, the .stack()
method stacks given tensors along a specified dimension to create a combined tensor. The tensors being stacked must have the same shape.
Syntax
torch.stack(tensors, dim=0, out=None)
tensors
: The list or sequence of tensors to be stacked.dim
: The dimension along which to stack the tensors. The default value is0
.out
: The optional output tensor to store the result. IfNone
, a new tensor is returned. The default isNone
.
Example
The following example demonstrates the usage of the .stack()
method:
import torch# Define tensorst0 = torch.zeros(4)t1 = torch.ones(4)# Stack tensors along the default dimension (dim=0)t2 = torch.stack((t0, t1))# Stack tensors along dimension 1t3 = torch.stack((t0, t1), dim=1)print(t2)print('\n')print(t3)
The returned tensors are as follows:
tensor([[0., 0., 0., 0.],[1., 1., 1., 1.]])tensor([[0., 1.],[0., 1.],[0., 1.],[0., 1.]])
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 Friendly90 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