Open In App

How Does the “View” Method Work in Python PyTorch?

Last Updated : 03 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how does the torch.view method work in PyTorch using Python.

The tensor.view() method is used to change the tensor in a two-dimensional format, i.e. rows and columns. We have to specify the number of rows and the number of columns to get output. Below is the Syntax of the following method.

Syntax: tensor.view(shape)

Parameter:

  • Shape: no_of_rows,no_of_columns

Returns: a new tensor with the same data as the self tensor but of a different shape.

Example 1

In this example, we are creating a tensor of 10 elements with the help of FloatTensor of one dimensional, and changing the tensor in a two-dimensional format of 5 rows and 2 columns and vice versa.

Python3




# importing torch module
import torch
  
# create one dimensional tensor
# 10 elements
a = torch.FloatTensor([10, 20, 30, 40, 50,
                       1, 2, 3, 4, 5])
  
# view tensor in 5 rows and 2
# columns
print(a.view(5, 2))
  
# view tensor in 2 rows and 5
# columns
print(a.view(2, 5))


Output:

tensor([[10., 20.],
        [30., 40.],
        [50.,  1.],
        [ 2.,  3.],
        [ 4.,  5.]])
        
tensor([[10., 20., 30., 40., 50.],
        [ 1.,  2.,  3.,  4.,  5.]])

Example 2

In this example, we are creating a tensor of 10 elements with the help of torch.arange of one-dimensional, and changing the tensor in a two-dimensional format of 4 rows and 3 columns and vice versa.

Python3




# importing torch module
import torch
  
# create one dimensional tensor
# 12 elements
a = torch.arange(1, 13)
  
# 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([[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9],
        [10, 11, 12]])
        
tensor([[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12]])

Example 3

In this example, we are creating a tensor of 10 elements with the help of torch.range of one dimensional, and changing the tensor in a two-dimensional format of 4 rows and 3 columns and vice versa.

Python3




# importing torch module
import torch
  
# create one dimensional tensor 
# 12 elements
a = torch.range(10, 21)
  
# 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([[10., 11., 12.],
        [13., 14., 15.],
        [16., 17., 18.],
        [19., 20., 21.]])
        
tensor([[10., 11., 12., 13.],
        [14., 15., 16., 17.],
        [18., 19., 20., 21.]])


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads