squeeze vs unsqueeze in PyTorch
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
PyTorch models care about tensor shape just as much as tensor values. squeeze and unsqueeze are small operations, but they solve a huge number of shape mismatches by either removing dimensions of size 1 or inserting new singleton dimensions exactly where a model expects them.
What squeeze Does
torch.squeeze removes dimensions whose length is 1. That is useful when data has extra wrapper dimensions that do not carry real information.
Output:
Without an explicit dimension argument, squeeze removes every singleton dimension. That is convenient, but it can also remove a batch dimension you wanted to keep.
You can be more precise:
Now only dimension 2 is removed, so the batch dimension remains.
What unsqueeze Does
torch.unsqueeze does the opposite. It inserts a dimension of size 1 at the given position.
Output:
This is common when you have a single sample and need to add a batch axis before passing it to a model.
Typical Deep Learning Use Cases
The most common pattern is preparing tensors for layers that expect a fixed rank.
For example, a grayscale image loaded as height by width may need a channel dimension and a batch dimension:
The result is shape [1, 1, 28, 28], which matches the usual batch, channel, height, width convention used by convolutional layers.
The reverse happens after model output or indexing. You may end up with a tensor such as [1, 10] and want to remove the batch axis before post-processing:
Dimension Choice Matters
Both functions are simple, but the dimension index controls semantics. Inserting a singleton dimension at 0 means "new batch axis" in many pipelines. Inserting at 1 may mean "new channel axis." Removing the wrong singleton dimension can subtly break downstream layers even when the tensor still has a valid shape.
That is why many experienced PyTorch users prefer explicit calls such as unsqueeze(0) or squeeze(1) instead of relying on the no-argument version everywhere.
In-Place Variants
PyTorch also provides squeeze_ and unsqueeze_, which modify the tensor in place.
In-place shape operations are fine in some preprocessing code, but they make debugging harder if multiple variables reference the same tensor. Unless you need the in-place behavior, the non-mutating form is usually easier to reason about.
Common Pitfalls
- Calling
squeeze()without a dimension can accidentally remove the batch axis when batch size is1. - '
squeeze(dim)removes a dimension only if its size is1. If the chosen dimension is larger, nothing happens.' - Using the wrong
unsqueezeposition can swap the meaning of batch and channel dimensions. - Expecting
squeezeorunsqueezeto reorder data is a mistake. They change shape metadata, not element order. - Chaining many shape operations without printing
tensor.shapemakes shape bugs much harder to diagnose.
Summary
- '
squeezeremoves dimensions of size1, whileunsqueezeadds a size1dimension at a chosen index.' - Use
unsqueezeto add batch or channel axes before model input. - Use
squeezeto remove wrapper dimensions after indexing or inference output. - Prefer explicit dimension arguments when the meaning of a shape matters.
Related reading
- SSIM / MS-SSIM for TensorFlow
- stack vs cat in PyTorch
- Stateful LSTM - Hidden State transfer between and within batches Keras
- Stateful LSTM and stream predictions
- Suboptimal convergence in PyTorch compared to TensorFlow when using Adam optimizer
- Taking subsets of a pytorch dataset
- Stateful LSTM When to reset states?
- Stopping and starting a deep learning google cloud VM instance causes tensorflow to stop recognizing GPU
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.