PyTorch torch.unsqueeze function
PyTorch torch reference manual
torch.unsqueeze is a function in PyTorch used to insert a dimension of size 1 at a specified position.
Function definition
torch.unsqueeze(input, dim)
Usage examples
Example
import
torch
x
=
torch.
randn
(
2
,
3
)
(
"Original shape:"
,
x.
shape
)
Insert a dimension at dim=0
y
=
torch.
unsqueeze
(
x
,
dim
=
0
)
(
"After expanding dim=0:"
,
y.
shape
)
Insert a dimension at dim=1
z
=
torch.
unsqueeze
(
x
,
dim
=
1
)
(
"After expanding dim=1:"
,
z.
shape
)
The output is:
原始形状: torch.Size([2, 3])
dim=0 扩展后: torch.Size([1, 2, 3])
dim=1 扩展后: torch.Size([2, 1, 3])