Normalize tensor shapes
Remove an extra batch, channel, or sequence axis introduced during preprocessing.
PyTorch · Function
torch.squeeze removes dimensions of size 1 from a tensor. Supplying dim limits removal to the selected dimensions.
torch.squeeze returns a tensor formed by removing dimensions of size 1 from the input. With dim specified, only those dimensions are considered; the result shares storage with the input.
torch.squeeze(input, dim=None)| Name | Type | Description |
|---|---|---|
input | Tensor | The input tensor. |
dim | int or tuple of ints | Optional dimension or dimensions in which to squeeze the input. |
A tensor with the specified singleton dimensions removed.
import torch
x = torch.zeros(2, 1, 2, 1, 2)
y = torch.squeeze(x, dim=1)
print(x.shape) # torch.Size([2, 1, 2, 1, 2])
print(y.shape) # torch.Size([2, 2, 1, 2])This removes only dimension 1 because its size is 1; the other singleton dimension remains.
Remove an extra batch, channel, or sequence axis introduced during preprocessing.
Delete known singleton axes while preserving unrelated singleton dimensions.
Collapse several known singleton axes in one call using a tuple of dimensions.
It removes dimensions whose size is 1. Without dim, all such dimensions are removed; with dim, only the specified dimensions are processed.
Follow-up: What happens if a specified dimension is not size 1? The dimension is not removed, so the tensor remains unchanged along that dimension.
The input is a Tensor, and dim is optional. dim can be an integer or a tuple of integers; tuple support was added in version 2.0.
Follow-up: Why use a tuple? It lets one operation explicitly target several singleton dimensions instead of squeezing every singleton dimension.
The output shares storage with the input, so it is an alias rather than an independently allocated copy. Changes through either tensor can therefore affect the shared data.
Follow-up: What should be used when fresh output storage is required? torch.squeeze_copy performs the operation while creating fresh output tensors.
torch.Tensor.squeezetorch.Tensor.squeeze_torch.squeeze_copytorch.unsqueeze