Skip to content
Minsing Log
Go back

English Edition

Tensor Manipulation Tips - What is unsqueeze?

Data & ML

Tensor Manipulation Tips

https://sputnik-kr.tistory.com/229

What is unsqueeze?

unsqueeze is a function in PyTorch that adds a new dimension (an axis of length 1) to a tensor.
For example,

This creates a batch dimension that did not exist before, so

Why use it?

Example

import torch
x = torch.tensor([1, 2, 3, 4])       # shape: (4,)
x1 = x.unsqueeze(0)                  # shape: (1, 4)
x2 = x.unsqueeze(1)                  # shape: (4, 1)

Summary:
unsqueeze is a function that changes a tensor’s shape by adding a new dimension.
It is essential in deep learning for matching batch dimensions and the like.[2][3][4][5][7]

Citations: [1] https://pplx-res.cloudinary.com/image/private/user_uploads/35150927/dcfdae12-8bbe-4f0b-89ae-d9a629d4a871/image.jpg [2] https://pplx-res.cloudinary.com/image/private/user_uploads/35150927/dcfdae12-8bbe-4f0b-89ae-d9a629d4a871/image.jpg [3] https://pytorch.org/docs/stable/generated/torch.unsqueeze.html [4] https://stackoverflow.com/questions/57237352/what-does-unsqueeze-do-in-pytorch [5] https://www.codecademy.com/resources/docs/pytorch/tensors/unsqueeze [6] https://www.codecademy.com/resources/docs/pytorch/tensor-operations/unsqueeze [7] https://www.datasciencebyexample.com/2023/05/19/squeeze-and-unsqueeze-in-pytorch/ [8] https://dnmtechs.com/understanding-the-unsqueeze-function-in-pytorch/ [9] https://www.projectpro.io/recipes/unsqueeze-torch-tensor [10] https://blog.naver.com/je_un/222297587260 [11] https://codemax.app/snippet/what-does-unsqueeze-do-in-pytorch-in-python/ [12] https://stackoverflow.com/questions/57237352/what-does-unsqueeze-do-in-pytorch/57237378 [13] https://www.tutorialspoint.com/how-to-squeeze-and-unsqueeze-a-tensor-in-pytorch [14] https://iifx.dev/en/articles/332257550 [15] https://sanghyu.tistory.com/86 [16] https://www.slingacademy.com/article/pytorch-squeezing-and-unsqueezing-tensors/ [17] https://stackoverflow.com/questions/57237352/what-does-unsqueeze-do-in-pytorch/65831759 [18] https://www.youtube.com/watch?v=VTryujXrMOs [19] https://blog.csdn.net/chengyq116/article/details/106962842 [20] https://researchdatapod.com/understanding-unsqueeze-in-pytorch-a-beginner-friendly-guide/ [21] https://myscale.com/blog/mastering-tensor-manipulation-pytorch-guide-torch-unsqueeze/ [22] https://pytorch.org/docs/stable/generated/torch.Tensor.unsqueeze.html


Answer from Perplexity: pplx.ai/share

Follow the journey

Get new posts by email.

Short, honest notes on building, startups, learning, failures, and retrospectives, for readers who follow the journey rather than pass through from search.

The newsletter is coming soon. Until then, follow via RSS or email me to get notified.


Share this post:

Comments

Sign in with GitHub to leave a comment.


Previous Post
The Concepts of Embeddings and Tokenization
Next Post
What is nn.Embedding