Unsqueeze a Tensor
When we unsqueeze a tensor, a new dimension of size 1 is inserted at the specified position. Always an unsqueeze operation increases the dimension of the output tensor. For example, if the input tensor is of shape: (m×n) and we want to insert a new dimension at position 1 then the output tensor after unsqueeze will be of shape: (m×1×n). The following is the syntax of the torch.unsqueeze() method-
Syntax: torch.unsqueeze(input, dim)
Parameters:
- input: the input tensor.
- dim: an integer value, the index at which the singleton dimension is inserted.
Return: It returns a new tensor with a dimension of size one inserted at the specified position dim.
Please note that we can choose the dim value from the range [-input.dim() – 1, input.dim() + 1). The negative dim will correspond to dim = dim + input.dim() + 1.
Example 3:
In the example below we unsqueeze a 1-D tensor to a 2D tensor.
Python3
# Python program to unsqueeze the input tensor # importing torch import torch # define the input tensor input = torch.arange( 8 , dtype = torch. float ) print ( "Input tensor:\n" , input ) print ( "Size of input Tensor before unsqueeze:\n" , input .size()) output = torch.unsqueeze( input , dim = 0 ) print ( "Tensor after unsqueeze with dim=0:\n" , output) print ( "Size after unsqueeze with dim=0:\n" , output.size()) output = torch.unsqueeze( input , dim = 1 ) print ( "Tensor after unsqueeze with dim=1:\n" , output) print ( "Size after unsqueeze with dim=1:\n" , output.size()) |
Output:
Input tensor: tensor([0., 1., 2., 3., 4., 5., 6., 7.]) Size of input Tensor before unsqueeze: torch.Size([8]) Tensor after unsqueeze with dim=0: tensor([[0., 1., 2., 3., 4., 5., 6., 7.]]) Size after unsqueeze with dim=0: torch.Size([1, 8]) Tensor after unsqueeze with dim=1: tensor([[0.], [1.], [2.], [3.], [4.], [5.], [6.], [7.]]) Size after unsqueeze with dim=1: torch.Size([8, 1])
How to squeeze and unsqueeze a tensor in PyTorch?
In this article, we will understand how to squeeze and unsqueeze a PyTorch Tensor.
To squeeze a tensor we can apply the torch.squeeze() method and to unsqueeze a tensor we use the torch.unsqueeze() method. Let’s understand these methods in detail.