YouTip LogoYouTip

Pytorch Torch Moveaxis

# Create a tensor with shape (batch, seq_len, feature) tensor\\ x = torch.randn(32,10,128)\\ \\ # SetMove 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 result is:

\\

Original shape: torch.Size([32, 10, 128])Shape after moving: torch.Size([128, 10, 32])

\\ \\

Example

\\
import torch\\
\\
# Create a 4D tensor (time, channel, height, width)\\
 x = torch.randn(10,3,32,32)\\
\\
# Set time Move dimension to the end\\
 y = torch.moveaxis(x,0, -1)\\
\\
print("Original shape:", x.shape)\\
\\
print("Shape after moving:", y.shape)
\\

The output result is:

\\

Original shape: torch.Size([10, 3, 32, 32])Shape after moving: torch.Size([3, 32, 32, 10])

\\ \\

Example

\\
import torch\\
\\
# Move multiple axes together\\
 x = torch.randn(2,3,4,5)\\
\\
# Setaxis0and1Move together to the position of axis2and3\\
 y = torch.moveaxis(x, source=(0,1), destination=(2,3))\\
\\
print("Original shape:", x.shape)\\
\\
print("Shape after moving:", y.shape)
\\

The output result is:

\\

Original shape: torch.Size([2, 3, 4, 5])Shape after moving: torch.Size([4, 5, 2, 3])

\\ \\
\\

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

\\
\\

Image 4: Pytorch torch Reference Manual Pytorch torch Reference Manual

\\

← Pytorch Torch MsortPytorch Torch Mm β†’