Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Change view of Tensor in Pytorch

  • Last Updated : 30 Jun, 2021

In this article, we are going to change the view of the given tensor in PyTorch. For this, we will use view() function to be 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)

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Example 1: Python program to create a tensor with 10 elements and view with 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:

Example 2: Change the view of a tensor into 4 rows and 3 columns and vice versa

Python3




# importing torch module
import torch
  
# create one dimensional tensor 12 elements
a = torch.FloatTensor([34, 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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!