Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.transpose function

PyTorch torch.transpose function


PyTorch torch reference manual 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:

Return Value:


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

)

print

(

"Original shape:"

,

x.

shape

)

print

(

"Shape after transposition:"

,

y.

shape

)

print

(

"Original:"

)

print

(

x

)

print

(

"After transposition:"

)

print

(

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

)

print

(

"Original shape:"

,

x.

shape

)

print

(

"Shape after transposition:"

,

y.

shape

)

The output is:

原始形状: torch.Size([2, 3, 4])

转置后形状: torch.Size([2, 4, 3])


Notes


PyTorch torch reference manual PyTorch torch reference manual