Here is a visual representation of what squeeze/unsqueeze do for an effectively 2d matrix:

When you are unsqueezing a tensor, it is ambiguous which dimension you wish to 'unsqueeze' it across (as a row or column etc). The dim argument dictates this - i.e. position of the new dimension to be added.

Hence the resulting unsqueezed tensors have the same information, but the indices used to access them are different.

Answer from End genocide - save Gaza on Stack Overflow
Top answer
1 of 3
73

Here is a visual representation of what squeeze/unsqueeze do for an effectively 2d matrix:

When you are unsqueezing a tensor, it is ambiguous which dimension you wish to 'unsqueeze' it across (as a row or column etc). The dim argument dictates this - i.e. position of the new dimension to be added.

Hence the resulting unsqueezed tensors have the same information, but the indices used to access them are different.

2 of 3
28

Simply put, unsqueeze() "adds" a superficial 1 dimension to tensor (at the specified dimension), while squeeze removes all superficial 1 dimensions from tensor.

A 1 dimension is superficial in the sense that it does not add any more elements to the tensor than would be there without it. Whenever this is true of a tensor dimension, it will always have the size 1 - hence the name "1 dimension".

You should look at tensor's shape attribute to see it easily. In your last case it would be:

import torch

tensor = torch.tensor([1, 0, 2, 3, 4])
tensor.shape # torch.Size([5])
tensor.unsqueeze(dim=0).shape # [1, 5]
tensor.unsqueeze(dim=1).shape # [5, 1]

It is useful for providing single sample to the network (which requires first dimension to be batch), for images it would be:

# 3 channels, 32 width, 32 height
tensor = torch.randn(3, 32, 32)
# 1 batch, 3 channels, 32 width, 32 height
tensor.unsqueeze(dim=0).shape

unsqueeze can be seen if you create tensor with 1 dimensions, e.g. like this:

# 3 channels, 32 width, 32 height and some 1 unnecessary dimensions
tensor = torch.randn(3, 1, 32, 1, 32, 1)
# 1 batch, 3 channels, 32 width, 32 height again
tensor.squeeze().unsqueeze(0) # [1, 3, 32, 32]
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-squeeze-and-unsqueeze-a-tensor-in-pytorch
How to squeeze and unsqueeze a tensor in PyTorch? - GeeksforGeeks
May 23, 2022 - Dimension of input tensor: 5 Input tensor Size: torch.Size([3, 1, 2, 1, 4]) Size after squeeze with dim=0: torch.Size([3, 1, 2, 1, 4]) Size after squeeze with dim=1: torch.Size([3, 2, 1, 4]) Size after squeeze with dim=2: torch.Size([3, 1, 2, 1, 4]) Size after squeeze with dim=3: torch.Size([3, 1, 2, 4]) Size after squeeze with dim=4: torch.Size([3, 1, 2, 1, 4]) Notice that when we squeeze the tensor in dimension 0, there is no change in the shape of the output tensor.
🌐
Reddit
reddit.com › r/pytorch › hot take: never use squeeze
r/pytorch on Reddit: Hot take: never use squeeze
December 7, 2024 -

Idk if I if I am misunderstanding something, but torch.squeeze just seems like a less transparent alternative to getting a view via indexing into 0 elements. Just had to a fix a bug caused by squeeze getting called on a tensor with dynamic size along a dimension, that would occasionally be 1.

🌐
DEV Community
dev.to › hyperkai › squeeze-in-pytorch-nkl
squeeze in PyTorch - DEV Community
December 30, 2024 - import torch my_tensor = torch.tensor([[[[0], [1]], [[2], [3]], [[4], [5]]]]) torch.squeeze(input=my_tensor) my_tensor.squeeze() torch.squeeze(input=my_tensor, dim=(0, 3)) my_tensor.squeeze(dim=(0, 3)) my_tensor.squeeze(0, 3) torch.squeeze(input=my_tensor, dim=(0, 1, 3)) my_tensor.squeeze(dim=(0, 1, 3)) my_tensor.squeeze(0, 1, 3) etc.
Find elsewhere
🌐
Medium
medium.com › dejunhuang › learning-day-6-pytorch-unsqueeze-squeeze-transpose-and-broadcasting-88e75dc8facb
Learning Day 6: Pytorch unsqueeze, squeeze, transpose and broadcasting | by De Jun Huang | dejunhuang | Medium
April 24, 2021 - import torch b = torch.rand(32) # bias print(b.shape) f = torch.rand(4, 32, 14, 14) # 4 images 32 channels, b = b.unsqueeze(0).unsqueeze(2).unsqueeze(3) # need to match f's dimension print(b) print(b.shape) It is easier to understand as compared to unsqueeze. It will just eliminate the dimension at the specific index if dim=1. If not, it won’t change anything: print(b.squeeze().shape) # eliminate all dim=1 print(b.squeeze(0).shape) # eliminate at specific dimension print(b.squeeze(-1).shape) print(b.squeeze(1).shape) print(b.squeeze(-4).shape)
🌐
YouTube
youtube.com › watch
Squeezing and Unsqueezing Tensors in PyTorch - YouTube
Let's squeeze and unsqueeze tensors in PyTorch
Published: October 26, 2023
🌐
ProjectPro
projectpro.io › recipes › what-does-squeeze-function-do-torch
What does squeeze function do in torch -
August 3, 2022 - This is achieved by using torch.squeeze(input, dim, out) which will return a tensor, with all the dimensions of input of size 1 removed. For e.g, if the input tensor is of shape A×1×B×C×1×D then the out tensor will be of shape A×B×C×D.
🌐
Torch for R
torch.mlverse.org › docs › reference › torch_squeeze.html
Squeeze — torch_squeeze • torch
torch_squeeze.Rd · Squeeze · torch_squeeze(self, dim) self · (Tensor) the input tensor. dim · (int, optional) if given, the input will be squeezed only in this dimension · The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.
🌐
Fandom
grace-rbx.fandom.com › wiki › Badges
Badges | Grace Wiki | Fandom
July 29, 2026 - Badges are achievements a player can earn on Roblox by doing certain tasks in-game. There are currently 173 [Actually its 199 but the wiki isnt updated and the latest update is Grace but Evil] in the latest Grace update (including the unobtainable ones), and 169 badges that can be currently obtained.
🌐
Torch Drinks
torchdrinks.com › collection › thc-drinks › 60mg-high-potency
60mg THC Drinks - Torch Drinks - THC Seltzers & Iced Teas
A 60mg dose is not a starting point. If you’re new to THC, start with a 5mg or 10mg THC seltzer and work up. For experienced drinkers, 60mg delivers a strong effect cleanly, with almost no sugar and no alcohol hangover. Most THC seltzers top out at 25mg; Torch goes to 60mg.
🌐
Codecademy
codecademy.com › docs › pytorch › tensor operations › .squeeze()
PyTorch | Tensor Operations | .squeeze() | Codecademy
November 25, 2024 - The PyTorch .squeeze() function removes dimensions of size 1 from a given tensor.
🌐
Towards Data Science
towardsdatascience.com › home › latest › hybrid neuro-symbolic fraud detection: guiding neural networks with domain rules
Hybrid Neuro-Symbolic Fraud Detection: Guiding Neural Networks with Domain Rules | Towards Data Science
March 11, 2026 - def rule_loss(x, probs): # x[:, -1] = Amount (last column in creditcard.csv after dropping Class) # x[:, 1:29] = V1–V28 (PCA components, columns 1–28) amount = x[:, -1] pca_norm = torch.norm(x[:, 1:29], dim=1) suspicious = ( torch.sigmoid(5 * (amount - amount.mean())) + torch.sigmoid(5 * (pca_norm - pca_norm.mean())) ) / 2.0 penalty = suspicious * torch.relu(0.6 - probs.squeeze()) return penalty.mean()
🌐
Artiper
artistdeveloper.github.io › pytorch › Pytorch-squeeze(),-unsqueeze()
[Pytorch] squeeze(), unsqueeze() - Artiper
August 4, 2023 - import torch tensor = torch.tensor([[[5,3,0], [2,0,1]]]) print(tensor.shape) print(tensor.squeeze().shape) output: torch.Size([1, 2, 3]) torch.Size([2, 3]) squeeze()함수는 axis가 1인 축을 제거한다. 주어진 매개변수 차원에 대해 1인 축을 추가한다.
🌐
PyTorch Forums
discuss.pytorch.org › uncategorized
Is squeezing a 1-dimensional tensor broken? - Uncategorized - PyTorch Forums
July 18, 2018 - The documentation of torch.squeeze (PyTorch 0.4) states that “As an exception to the above, a 1-dimensional tensor of size 1 will not have its dimensions changed.” However, when I torch.squeeze() a 1-dimensional tensor, it becomes zero-dimensional: i.e. it does get squeezed!
🌐
MyScale
myscale.com › blog › effortless-tensor-manipulation-mastering-pytorch-squeeze-techniques
Mastering PyTorch Squeeze Techniques for Effortless Tensor Manipulation
April 24, 2024 - Optimizing Tensor Shapes for faster computation is another area where PyTorch squeeze shines. By removing redundant dimensions through squeezing operations, computational efficiency is boosted during matrix multiplications (opens new window) and element-wise operations.
🌐
Facebook
facebook.com › groups › homebakeryforbeginners › posts › 948027624748665
Requested to make a creme brulee cake for my ...
Explore the things you love · Log into Facebook · English (US) · فارسی · العربية · Türkçe · Deutsch · Français (France) · Polski · More languages…