How to use resize() method In Python
This is used to resize the dimensions of the given tensor.
Syntax: tensor.resize_(no_of_tensors,no_of_rows,no_of_columns)
where:
- tensor is the input tensor
- 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 1: Python code to create an empty one D tensor and create 4 new tensors with 4 rows and 5 columns
Python3
# importing torch module import torch # create one dimensional tensor a = torch.Tensor() # resize the tensor to 4 tensors. # each tensor with 4 rows and 5 columns print (a.resize_( 4 , 4 , 5 )) |
Output:
Example 2: Create a 1 D tensor with elements and resize to 3 tensors with 2 rows and 2 columns
Python3
# importing torch module import torch # create one dimensional a = torch.Tensor() # resize the tensor to 2 tensors. # each tensor with 4 rows and 2 columns print (a.resize_( 2 , 4 , 2 )) |
Output:
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])
Contact Us