PyTorch Transpose and Permute
Transpose swaps two dimensions of a tensor. Rows become columns, and columns become rows.
Swap rows and columns
t() turns the first row into the first column. Every value keeps its value and moves to a new place.
scores = torch.tensor([[85, 92], [90, 88], [72, 81]])
print(scores.t())Name the dimensions to swap
Swapping two dimensions turns rows into columns. transpose(0, 1) names those two dimensions.
print(scores.transpose(0, 1).shape)
print(scores.transpose(0, 1))Move three dimensions at once
permute lists every dimension in its new order. Here dimension 1 moves first, then dimension 0, then dimension 2.
blocks = torch.arange(24).reshape(2, 3, 4)
print(blocks.permute(1, 0, 2).shape)Example
import torch
scores = torch.tensor([[85, 92],
[90, 88],
[72, 81]])
print("Scores shape:", scores.shape)
print("Scores, students as rows:")
print(scores)
by_quiz = scores.t()
print("Transposed shape:", by_quiz.shape)
print("Scores, students as columns:")
print(by_quiz)
print("Quiz 1 row:", by_quiz[0])
print("Quiz 2 row:", by_quiz[1])Key points
- Use t() to swap the rows and columns of a table
- Use transpose(0, 1) to swap two named dimensions
- Use permute to move every dimension into a new order at once
- permute takes the new order as dimension numbers, like (1, 0, 2)
In this example, scores is a table with three rows and two columns. Each row holds one student's two quiz scores. Each column holds one quiz. scores.t() swaps the dimensions, so the shape becomes (2, 3). The transposed table prints with students as columns. Its first row holds every student's quiz 1 score. Its second row holds every quiz 2 score.
Note
t() works only on tables, while transpose and permute also work on larger tensors
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
A table has shape (4, 2). What shape does t() give it?