Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to resize a tensor in PyTorch?
Next article icon

Reshaping a Tensor in Pytorch

Last Updated : 01 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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])

Method 1 : Using reshape() Method

This method is used to reshape the given tensor into a given shape( Change the dimensions)

Syntax: tensor.reshape([row,column])

where,

  • tensor is the input tensor
  • row represents the number of rows in the reshaped tensor
  • column represents the number of columns  in the reshaped tensor

Example 1: Python program to reshape a 1 D tensor to a two-dimensional tensor.

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  actual tensor print(a)  # reshape tensor into 4 rows and 2 columns print(a.reshape([4, 2]))  # display shape of reshaped tensor print(a.shape) 

Output:

torch.Size([8]) tensor([1, 2, 3, 4, 5, 6, 7, 8]) tensor([[1, 2],         [3, 4],         [5, 6],         [7, 8]]) torch.Size([8])

Example 2: Python code to reshape tensors into 4 rows and 2 columns

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  actual tensor print(a)  # reshape tensor into 4 rows and 2 columns print(a.reshape([4, 2]))  # display shape print(a.shape) 

Output:

torch.Size([8]) tensor([1, 2, 3, 4, 5, 6, 7, 8]) tensor([[1, 2],        [3, 4],        [5, 6],        [7, 8]]) torch.Size([8])

Example 3: Python code to reshape tensor into 8 rows and 1 column.

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  actual tensor print(a)  # reshape tensor into 8 rows and 1 column print(a.reshape([8, 1]))  # display shape print(a.shape) 

Output:

torch.Size([8]) tensor([1, 2, 3, 4, 5, 6, 7, 8]) tensor([[1],        [2],        [3],        [4],        [5],        [6],        [7],        [8]]) torch.Size([8])

Method 2 : Using flatten() method

flatten() is used to flatten an N-Dimensional tensor to a 1D Tensor. 

Syntax: torch.flatten(tensor)

Where, tensor is the input tensor

Example 1: Python code to create a tensor  with 2 D elements and flatten this vector

Python3
# import torch module import torch  # create an 2 D tensor with 8 elements each a = torch.tensor([[1,2,3,4,5,6,7,8],                   [1,2,3,4,5,6,7,8]])  # display actual tensor print(a)  # flatten a tensor with flatten() function print(torch.flatten(a)) 

Output:

tensor([[1, 2, 3, 4, 5, 6, 7, 8],        [1, 2, 3, 4, 5, 6, 7, 8]]) tensor([1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8])

Example 2: Python code to create a tensor  with 3 D elements and flatten this vector

Python3
# import torch module import torch  # create an 3 D tensor with 8 elements each a = torch.tensor([[[1,2,3,4,5,6,7,8],                  [1,2,3,4,5,6,7,8]],                 [[1,2,3,4,5,6,7,8],                  [1,2,3,4,5,6,7,8]]])  # display actual tensor print(a)  # flatten a tensor with flatten() function print(torch.flatten(a)) 

Output:

tensor([[[1, 2, 3, 4, 5, 6, 7, 8],

        [1, 2, 3, 4, 5, 6, 7, 8]],

       [[1, 2, 3, 4, 5, 6, 7, 8],

        [1, 2, 3, 4, 5, 6, 7, 8]]])

tensor([1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8,

       1, 2, 3, 4, 5, 6, 7, 8])

Method 3: Using view() method

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

Method 4: Using resize() method

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:

Method 5: Using unsqueeze() method

This is used to reshape a tensor by adding new dimensions at given positions.

Syntax: tensor.unsqueeze(position)

where, position is the dimension index which will start from 0.

Example 1: Python code to create 2 D tensors and add a dimension in 0 the dimension.

Python3
# importing torch module import torch  # create two dimensional tensor  a = torch.Tensor([[2,3], [1,2]])    # display shape print(a.shape)  # add dimension at 0 position  added = a.unsqueeze(0)  print(added.shape) 

Output:

torch.Size([2, 2]) torch.Size([1, 2, 2])

Example 2: Python code to create 1 D tensor and add dimensions

Python3
# importing torch module import torch  # create one dimensional tensor  a = torch.Tensor([1, 2, 3, 4, 5])    # display shape print(a.shape)  # add dimension at 0 position  added = a.unsqueeze(0)  print(added.shape)  # add dimension at 1 position  added = a.unsqueeze(1)  print(added.shape) 

Output:

torch.Size([5]) torch.Size([1, 5]) torch.Size([5, 1])

Next Article
How to resize a tensor in PyTorch?

D

deepakresearch222
Improve
Article Tags :
  • Python
  • Python-PyTorch
Practice Tags :
  • python

Similar Reads

  • 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. Method 1: Using view() method We can resize the tensors in PyTorch by using the view() m
    5 min read
  • Tensors in Pytorch
    A Pytorch Tensor is basically the same as a NumPy array. This means it does not know anything about deep learning or computational graphs or gradients and is just a generic n-dimensional array to be used for arbitrary numeric computation. However, the biggest difference between a NumPy array and a P
    6 min read
  • How to Slice a 3D Tensor in Pytorch?
    In this article, we will discuss how to Slice a 3D Tensor in Pytorch. Let's create a 3D Tensor for demonstration. We can create a vector by using torch.tensor() function Syntax: torch.tensor([value1,value2,.value n]) Code: [GFGTABS] Python3 # import torch module import torch # create an 3 D tensor w
    2 min read
  • Creating a Tensor in Pytorch
    All the deep learning is computations on tensors, which are generalizations of a matrix that can be indexed in more than 2 dimensions. Tensors can be created from Python lists with the torch.tensor() function. The tensor() Method: To create tensors with Pytorch we can simply use the tensor() method:
    6 min read
  • Tensor Operations in PyTorch
    In this article, we will discuss tensor operations in PyTorch. PyTorch is a scientific package used to perform operations on the given data like tensor in python. A Tensor is a collection of data like a numpy array. We can create a tensor using the tensor function: Syntax: torch.tensor([[[element1,e
    5 min read
  • Way to Copy a Tensor in PyTorch
    In deep learning, PyTorch has become a popular framework for building and training neural networks. At the heart of PyTorch is the tensor—a multi-dimensional array that serves as the fundamental building block for all operations in the framework. There are many scenarios where you might need to copy
    5 min read
  • Change view of Tensor in PyTorch
    In this article, we will learn how to change the shape of tensors using the PyTorch view function. We will also look at the multiple ways in which we can change the shape of the tensors. Also, we can use the view function to convert lower-dimensional matrices to higher dimensions. What is the necess
    3 min read
  • PyTorch Tensor vs NumPy Array
    PyTorch and NumPy can help you create and manipulate multidimensional arrays. This article covers a detailed explanation of how the tensors differ from the NumPy arrays. What is a PyTorch Tensor?PyTorch tensors are the data structures that allow us to handle multi-dimensional arrays and perform math
    8 min read
  • One-Dimensional Tensor in Pytorch
    In this article, we are going to discuss a one-dimensional tensor in Python. We will look into the following concepts: Creation of One-Dimensional TensorsAccessing Elements of TensorSize of TensorData Types of Elements of TensorsView of TensorFloating Point TensorIntroduction The Pytorch is used to
    5 min read
  • Python - tensorflow.ensure_shape()
    TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.  ensure_shape() is used to update and check the shape of Tensor. Syntax: tensorflow.ensure_shape( x, shape, name) Parameters: x: It is input Tensor.shape: It is TensorSh
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences