How to use view() method In Python
view() is used to change the tensor in two-dimensional format IE rows and columns. We have to specify the number of rows and the number of columns to be viewed.
Syntax: tensor.view(no_of_rows,no_of_columns)
where,
- tensor is an input one dimensional tensor
- no_of_rows is the total number of the rows that the tensor is viewed
- no_of_columns is the total number of the columns that the tensor is viewed.
Example 1: Python program to create a tensor with 12 elements and view with 3 rows and 4 columns and vice versa.
Python3
# importing torch module import torch # create one dimensional tensor 12 elements a = torch.FloatTensor([ 24 , 56 , 10 , 20 , 30 , 40 , 50 , 1 , 2 , 3 , 4 , 5 ]) # view tensor in 4 rows and 3 columns print (a.view( 4 , 3 )) # view tensor in 3 rows and 4 columns print (a.view( 3 , 4 )) |
Output:
tensor([[24., 56., 10.], [20., 30., 40.], [50., 1., 2.], [ 3., 4., 5.]]) tensor([[24., 56., 10., 20.], [30., 40., 50., 1.], [ 2., 3., 4., 5.]])
Example 2: Python code to change the view of a tensor into 10 rows and one column and vice versa.
Python3
# importing torch module import torch # create one dimensional tensor 10 elements a = torch.FloatTensor([ 24 , 56 , 10 , 20 , 30 , 40 , 50 , 1 , 2 , 3 ]) # view tensor in 10 rows and 1 column print (a.view( 10 , 1 )) # view tensor in 1 row and 10 columns print (a.view( 1 , 10 )) |
Output:
tensor([[24.], [56.], [10.], [20.], [30.], [40.], [50.], [ 1.], [ 2.], [ 3.]]) tensor([[24., 56., 10., 20., 30., 40., 50., 1., 2., 3.]])
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])