SoFunction
Updated on 2025-04-13

Commonly used dimension conversion methods in Pytorch

In PyTorch, dimension conversion is a common operation. Here are some commonly used dimension conversion methods:

1. View method

viewThe method can reshape the shape of the tensor, but it is necessary to ensure that the total number of elements before and after the reshaping is the same.

import torch

# Create a tensorx = (12)
print("Original Tensor:", x)

# Use the view method to convert dimensionsy = (3, 4)
print("Converted tensor:", y)

2. Reshape method

reshapeMethods andviewThe method functions similarly and is also used to reshape the tensor shape, butreshapeMore flexible, it can be used even if the original tensor is discontinuous.

import torch

# Create a tensorx = (12)
print("Original Tensor:", x)

# Use the reshape method to perform dimension conversiony = (3, 4)
print("Converted tensor:", y)

3. Transpose method

transposeMethods can exchange two specified dimensions of tensors.

import torch

# Create a two-dimensional tensorx = (12).view(3, 4)
print("Original Tensor:", x)

# Use transpose method to exchange dimensionsy = (0, 1)
print("Converted tensor:", y)

4. Permute method

permuteThe method can rearrange all dimensions of a tensor.

import torch

# Create a three-dimensional tensorx = (24).view(2, 3, 4)
print("Original Tensor Shape:", )

# Use the permute method to rearrange the dimensionsy = (1, 2, 0)
print("Converted tensor shape:", )

5. Unsqueeze and squeeze methods

  • unsqueezeMethod is used to insert a dimension at a specified position.
  • squeezeMethods are used to remove all dimensions with dimensions of 1.
import torch

# Create a one-dimensional tensorx = (3)
print("Original Tensor Shape:", )

# Use the unsqueeze method to insert dimensionsy = (0)
print("Tensor shape after inserting dimension:", )

# Use the squeeze method to remove dimensionsz = (0)
print("Tensor shape after removing dimensions:", )

These methods can help you flexibly perform dimension conversion in PyTorch. When using it in practice, you should choose the appropriate method according to the specific needs.

Summarize

This is the end of this article about the commonly used dimension conversion methods of Pytorch. For more related Pytorch dimension conversion content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!