How to use unsqueeze() method In Python

This is used to resize a tensor by adding new dimensions at given positions. below syntax is used to resize tensor using unsqueeze() method.

Syntax: tensor.unsqueeze(position)

Parameter: position is the dimension index which will start from 0.

Return: It returns a new tensor dimension of size 1 inserted at specific position.

Example 6:

The following program is to resize tensor using unsqueeze() method.

Python




# import torch library
import torch
 
# define a tensor
tens = torch.Tensor([10, 20, 30, 40, 50])
 
# display tensor and it's size
print("\n Original Tensor: ", tens)
 
# Squeeze the tensor in dimension 1
tens_1 = torch.unsqueeze(tens, dim=1)
print("\n After resize tensor to 5x1: \n", tens_1)


Output:



How to resize a tensor in PyTorch?

In this article, we will discuss how to resize a Tensor in Pytorch. Resize allows us to change the size of the tensor. we have multiple methods to resize a tensor in PyTorch. let’s discuss the available methods.

Similar Reads

Method 1: Using view() method

We can resize the tensors in PyTorch by using the view() method. view() method allows us to change the dimension of the tensor but always make sure the total number of elements in a tensor must match before and after resizing tensors. The below syntax is used to resize a tensor....

Method 2 : Using reshape() Method

...

Method 3: Using resize() method

...

Method 4: Using unsqueeze() method

This method is also used to resize the tensors. This method returns a new tensor with a modified size. the below syntax is used to resize the tensor using reshape() method....