PyTorch unsqueeze Explained: What It Does and When to Use It
PyTorch's unsqueeze(dim) function inserts a new axis of size 1 at a specified position in a tensor, changing its shape without altering the underlying data or allocating new memory. This operation is commonly needed because models expect batched inputs, so a single sample with shape (3, 32, 32) must be reshaped to (1, 3, 32, 32) before being passed to most layers. Developers can achieve the same result using None-based indexing, which is a shorter but equivalent alternative seen frequently in real codebases. The inverse operation, squeeze, removes size-1 dimensions either globally or at a specific position, but only acts on axes that are genuinely size 1. Together, these two functions resolve a large share of shape mismatch errors in PyTorch without any computational cost.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in