How to use unsqueeze() method In Python

This is used to reshape a tensor by adding new dimensions at given positions.

Syntax: tensor.unsqueeze(position)

where, position is the dimension index which will start from 0.

Example 1: Python code to create 2 D tensors and add a dimension in 0 the dimension.

Python3




# importing torch module
import torch
 
# create two dimensional tensor
a = torch.Tensor([[2,3], [1,2]]) 
 
# display shape
print(a.shape)
 
# add dimension at 0 position
added = a.unsqueeze(0)
 
print(added.shape)


Output:

torch.Size([2, 2])
torch.Size([1, 2, 2])

Example 2: Python code to create 1 D tensor and add dimensions

Python3




# importing torch module
import torch
 
# create one dimensional tensor
a = torch.Tensor([1, 2, 3, 4, 5]) 
 
# display shape
print(a.shape)
 
# add dimension at 0 position
added = a.unsqueeze(0)
 
print(added.shape)
 
# add dimension at 1 position
added = a.unsqueeze(1)
 
print(added.shape)


Output:

torch.Size([5])
torch.Size([1, 5])
torch.Size([5, 1])


Reshaping a Tensor in Pytorch

In this article, we will discuss how to reshape a Tensor in Pytorch. Reshaping allows us to change the shape with the same data and number of elements as self but with the specified shape, which means it returns the same data as the specified array, but with different specified dimension sizes.

Creating Tensor for demonstration:

Python code to create a 1D Tensor and display it.

Python3




# import torch module
import torch
 
# create an 1 D etnsor with 8 elements
a = torch.tensor([1,2,3,4,5,6,7,8])
 
# display tensor shape
print(a.shape)
 
# display tensor
a


Output:

torch.Size([8])
tensor([1, 2, 3, 4, 5, 6, 7, 8])

Similar Reads

Method 1 : Using reshape() Method

...

Method 2 : Using flatten() method

This method is used to reshape the given tensor into a given shape( Change the dimensions)...

Method 3: Using view() method

...

Method 4: Using resize() method

...

Method 5: Using unsqueeze() method

...