PyTorch torch.squeeze function
PyTorch torch reference manual
torch.squeeze is a function in PyTorch used to remove dimensions of size 1 from a tensor.
Function definition
torch.squeeze(input, dim)
Usage examples
Example
import
torch
Create a tensor with dimensions of size 1
x
=
torch.
randn
(
1
,
2
,
1
,
3
,
1
)
(
"Original shape:"
,
x.
shape
)
Remove all dimensions of size 1
y
=
torch.
squeeze
(
x
)
(
"Shape after squeezing:"
,
y.
shape
)
Specify a dimension
z
=
torch.
squeeze
(
x
,
dim
=
0
)
(
"After squeezing dim=0:"
,
z.
shape
)
The output is:
原始形状: torch.Size([1, 2, 1, 3, 1])
挤压后形状: torch.Size([2, 3])
dim=0 挤压后: torch.Size([2, 1, 3, 1])