.transpose()
Anonymous contributor
Published Jan 24, 2025
Contribute to Docs
In PyTorch, the .transpose()
operation creates a view of the input tensor with the specified dimensions swapped, commonly used for matrix operations and reshaping data for neural network inputs. Unlike .permute()
, .transpose()
only swaps two dimensions at a time.
Syntax
tensor.transpose(dim0, dim1)
dim0
: The first dimension to be transposed.dim1
: The second dimension to be transposed.
Example
The following code creates a 2x3 tensor and then uses .transpose()
to swap row and column dimensions, resulting in a 3x2 tensor where original rows become columns and vice versa:
import torch# Create a 2x3 tensorx = torch.tensor([[1, 2, 3],[4, 5, 6]])# Transpose its dimensionsy = x.transpose(0, 1)# Print the resultant tensorprint(y)
The above code will result in the following output:
tensor([[1, 4],[2, 5],[3, 6]])
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
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 - 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