PyTorch torch.movedim function
PyTorch torch reference manual
torch.movedim is a function in PyTorch used to move tensor dimensions. It moves a specified dimension to a new position and returns a new view of the tensor.
This function is very useful when reshaping a tensor for a specific operation, such as when processing image data or preparing neural network inputs.
Function definition
torch.movedim(input, source, destination)
Parameters:
input(Tensor): the input tensor.source(int or tuple of int): The index of the original dimension to move. It can be an integer or a tuple of dimension indices.destination(int or tuple of int): The index of the target position. It can be an integer or a tuple of dimension indices, and its length must be the same as source.
Return Value:
torch.Tensor: Returns a view of the tensor with dimensions moved.
Usage examples
Example
import
torch
Create a tensor with shape (batch, channel, height, width)
x
=
torch.
randn
(
32
,
3
,
224
,
224
)
Move the channel dimension to the last dimension
Move from position 1 to position 3
y
=
torch.
movedim
(
x
,
1
,
3
)
(
"Original shape:"
,
x.
shape
)
(
"Shape after moving:"
,
y.
shape
)
The output is:
原始形状: torch.Size([32, 3, 224, 224])
移动后形状: torch.Size([32, 224, 224, 3])
Example
import
torch
Create a tensor with shape (D0, D1, D2, D3)
x
=
torch.
randn
(
2
,
3
,
4
,
5
)
Move multiple dimensions together
Move dimensions 0 and 1 to the positions of dimensions 2 and 3
y
=
torch.
movedim
(
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])
Example
import
torch
Convert an image tensor from (N, C, H, W) to (N, H, W, C)
This is useful when sending data to APIs that require channels in the last position
images
=
torch.
randn
(
16
,
3
,
64
,
64
)
images_permuted
=
torch.
movedim
(
images
,
1
,
3
)
(
"Original shape (N, C, H, W):"
,
images.
shape
)
(
"Converted shape (N, H, W, C):"
,
images_permuted.
shape
)
Note:torch.movedim It returns a view rather than a copy, so the operation is efficient. A similar function is torch.moveaxis, which is the same as torch.movedim Same functionality, but with different parameter names.