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

PyTorch torch.moveaxis function

PyTorch torch.moveaxis function


PyTorch torch reference manual PyTorch torch reference manual

torch.moveaxis is a function in PyTorch used to move tensor axes. It moves a specified axis to a new position and returns a new view of the tensor.

This function has the same functionality as torch.movedim , differing only in parameter names (moveaxis uses "axis" while movedim uses "dim").

Function definition

torch.moveaxis(input, source, destination)

Parameters:

Return Value:


Usage examples

Example

import

torch

Create a tensor with shape (batch, seq_len, feature)

x

=

torch.

randn

(

32

,

10

,

128

)

Move the last dimension to the first position

y

=

torch.

moveaxis

(

x

,

1

,

0

)

print

(

"Original shape:"

,

x.

shape

)

print

(

"Shape after moving:"

,

y.

shape

)

The output is:

原始形状: torch.Size([32, 10, 128])

移动后形状: torch.Size([128, 10, 32])

Example

import

torch

Create a four-dimensional tensor (time, channel, height, width)

x

=

torch.

randn

(

10

,

3

,

32

,

32

)

Move the time dimension to the end

y

=

torch.

moveaxis

(

x

,

0

,

1

)

print

(

"Original shape:"

,

x.

shape

)

print

(

"Shape after moving:"

,

y.

shape

)

The output is:

原始形状: torch.Size([10, 3, 32, 32])

移动后形状: torch.Size([3, 32, 32, 10])

Example

import

torch

Move multiple axes together

x

=

torch.

randn

(

2

,

3

,

4

,

5

)

Move axes 0 and 1 to the positions of axes 2 and 3

y

=

torch.

moveaxis

(

x

,

source

=

(

0

,

1

)

,

destination

=

(

2

,

3

)

)

print

(

"Original shape:"

,

x.

shape

)

print

(

"Shape after moving:"

,

y.

shape

)

The output is:

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

移动后形状: torch.Size([4, 5, 2, 3])


Note:torch.moveaxis It returns a view rather than a copy, so the operation is efficient. This function is often used to reshape data to fit different deep learning frameworks or APIs.


PyTorch torch reference manual PyTorch torch reference manual