PyTorch torch.unsqueeze Function


Pytorch torch 参考手册PyTorch torch Reference Manual

torch.unsqueezeis a function in PyTorch used to insert a dimension of size 1 at the specified position.

Function Definition

torch.unsqueeze(input, dim)

Usage Example

Example

import torch

x = torch.randn(2, 3)
print("Original shape:", x.shape)

# Insert dimension at dim=0
y = torch.unsqueeze(x, dim=0)
print("After dim=0 expansion:", y.shape)

# Insert dimension at dim=1
z = torch.unsqueeze(x, dim=1)
print("After dim=1 expansion:", z.shape)

The output is:

原始形状: torch.Size([2, 3])
dim=0 扩展后: torch.Size([1, 2, 3])
dim=1 扩展后: torch.Size([2, 1, 3])

Pytorch torch 参考手册PyTorch torch Reference Manual

Other Extensions