How to use view() method In Python

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.

 Syntax: torch.view(shape):

Parameters: updated shape of tensor.

Return: view() method returns a new tensor with the same data as the self tensor but of a different shape.

Example 1:

The following program is to resize 1D tensor in PyTorch using view()

Python




# Import the torch library
import torch
 
# define a tensor
tens = torch.Tensor([10, 20, 30, 40, 50, 60])
print("Original Tensor: ", tens)
 
# below is the different ways to resize
# tensor to 2x3 using view()
 
# Resize tensor to 2x3
tens_1 = tens.view(2, 3)
print(" Tensor After Resize: \n", tens_1)
 
# other way resize tensor to 2x3
tens_2 = tens.view(2, -1)
print(" Tensor after resize: \n", tens_2)
 
# Other way to resize tensor to 2x3
tens_3 = tens.view(-1, 3)
print(" Tensor after resize: \n", tens_3)


Output:

Example 2:

The following program is to resize the 2D tensor in PyTorch using view().

Python




# Import the torch library
import torch
 
# define a tensor
tens = torch.Tensor([[1, 2, 3], [4, 5, 6],
                     [7, 8, 9], [10, 11, 12]])
print("Original Tensor: \n", tens)
 
# below is the different ways to use view()
 
# Resize tensor to 3x4
tens_1 = tens.view(2, -1)
print("\n Tensor After Resize: \n", tens_1)
 
# other way resize tensor to 3x4
tens_2 = tens.view(-1, 4)
print("\n Tensor after resize: \n", tens_2)
 
# Other way to resize tensor to 3x4
tens_3 = tens.view(3, -1)
print("\n Tensor after resize: \n", tens_3)


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....