PyTorch torch.moveaxis function
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:
input(Tensor): the input tensor.source(int or tuple of int): The index of the original axis to move. It can be an integer or a tuple of axis indices.destination(int or tuple of int): The index of the target position. It can be an integer or a tuple of axis indices, and its length must be the same as source.
Return Value:
torch.Tensor: Returns a view of the tensor with axes moved.
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
)
(
"Original shape:"
,
x.
shape
)
(
"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
)
(
"Original shape:"
,
x.
shape
)
(
"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
)
)
(
"Original shape:"
,
x.
shape
)
(
"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.