How to use resize() method In Python

This method is also used to resize tensors in PyTorch and the below syntax helps us to resize the tensor.

Syntax: tensor.resize_(no_of_tensors, no_of_rows, no_of_columns)

Parameters:

  • no_of_tensors: represents the total number of tensors to be generated
  • no_of_rows: represents the total number of rows in the new resized tensor
  • no_of_columns: represents the total number of columns in the new resized tensor

Example 5:

The following program is to understand how to resize the tensor using resize() method.

Python




# import torch module
import torch
 
# Define an 1D tensor
tens = torch.Tensor([11, 12, 13, 14, 15, 16, 17, 18])
 
# display tensor
print("\n Original 2D Tensor: \n", tens)
 
# resize the tensor to 4 tensors.
# each tensor with 4 rows and 5 columns
tens_1 = tens.resize_(4, 4, 5)
print("\n After resize tensor: \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....