PyTorch torch.transpose function
PyTorch torch reference manual
torch.transpose is a function in PyTorch used to swap two dimensions of a tensor. It returns a transposed view of the input tensor.
This is a common operation in deep learning, used to change the data shape to suit different computational needs.
Function definition
torch.transpose(input, dim0, dim1)
Parameters:
input(Tensor): the input tensor.dim0(int): The first dimension to swap.dim1(int): The second dimension to swap.
Return Value:
torch.Tensor: Returns the transposed view of the tensor.
Usage examples
Example 1: Transpose a 2D matrix
Example
import
torch
Create a 3x4 matrix
x
=
torch.
randn
(
3
,
4
)
Transpose
y
=
torch.
transpose
(
x
,
0
,
1
)
(
"Original shape:"
,
x.
shape
)
(
"Shape after transposition:"
,
y.
shape
)
(
"Original:"
)
(
x
)
(
"After transposition:"
)
(
y
)
The output is:
原始形状: torch.Size([3, 4])
转置后形状: torch.Size([4, 3])
原始:
tensor([[ 0.3364, -0.7844, 0.9760, 0.4381],
[ 0.7865, -1.2775, 0.5767, -0.5268],
[-0.6399, -0.6743, -0.2972, -0.4781]])
Transposed:
tensor([[ 0.3364, 0.7865, -0.6399],
[-0.7844, -1.2775, -0.6743],
[ 0.9760, 0.5767, -0.2972],
[ 0.4381, -0.5268, -0.4781]])
Example 2: Transpose a multi-dimensional tensor
Example
import
torch
Create a 3D tensor
x
=
torch.
randn
(
2
,
3
,
4
)
Swap dim=1 and dim=2
y
=
torch.
transpose
(
x
,
1
,
2
)
(
"Original shape:"
,
x.
shape
)
(
"Shape after transposition:"
,
y.
shape
)
The output is:
原始形状: torch.Size([2, 3, 4])
转置后形状: torch.Size([2, 4, 3])
Notes
torch.transposeWhat is returned is a view, not a copy.- For 2D tensors, you can also use
tensor.t()method.