Method 2 : Using reshape() 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.
Syntax: tensor.reshape( [row,column] )
- row represents the number of rows in the reshaped tensor.
- column represents the number of columns in the reshaped tensor.
Return: return a resized tensor.
Example 3:
The following program is to know how to resize a 1D tensor to a 2D tensor.
Python
# import torch module import torch # Define an 1D tensor tens = torch.tensor([ 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 ]) # display tensor print ( "\n Original 1D Tensor: " , tens) # resize this tensor into 2x4 tens_1 = tens.reshape([ 2 , 4 ]) print ( "\n After Resize this Tensor to 2x4 : \n" , tens_1) # resize this tensor into 4x2 tens_2 = tens.reshape([ 4 , 2 ]) print ( "\n After Resize this Tensor to 4x2 : \n" , tens_2) |
Output:
Example 4:
The following program is to know how to resize a 2D tensor using reshape() method.
Python
# import torch module import torch # Define an 2D tensor tens = torch.Tensor([[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ], [ 10 , 11 , 12 ]]) # display tensor print ( " Original 2D Tensor: \n" , tens) # resize this tensor to 2x6 tens_1 = tens.reshape([ 2 , 6 ]) print ( "\n After Resize this Tensor to 2x6 : \n" , tens_1) # resize this tensor into 6x2 tens_2 = tens.reshape([ 6 , 2 ]) print ( "\n After Resize this Tensor to 6x2 : \n" , tens_2) |
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.