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 Upsample a PyTorch Tensor?
Next article icon

How to resize a tensor in PyTorch?

Last Updated : 23 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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() 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:

Method 2 : Using reshape() 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.

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

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

Return: return a resized tensor.

Example 3:

The following program is to know how to resize a 1D tensor to a 2D tensor.  

Python
# import torch module import torch  # Define an 1D tensor tens = torch.tensor([10, 20, 30, 40, 50, 60, 70, 80])  # display tensor print("\n Original 1D Tensor: ", tens)  # resize this tensor into 2x4 tens_1 = tens.reshape([2, 4]) print("\n After Resize this Tensor to 2x4 : \n", tens_1)  # resize this tensor into 4x2 tens_2 = tens.reshape([4, 2]) print("\n After Resize this Tensor to 4x2 : \n", tens_2) 

Output:

Example 4:

The following program is to know how to resize a 2D tensor using reshape() method.

Python
# import torch module import torch  # Define an 2D tensor tens = torch.Tensor([[1, 2, 3], [4, 5, 6],                      [7, 8, 9], [10, 11, 12]])  # display tensor print(" Original 2D Tensor: \n", tens)  # resize this tensor to 2x6 tens_1 = tens.reshape([2, 6]) print("\n After Resize this Tensor to 2x6 : \n", tens_1)  # resize this tensor into 6x2 tens_2 = tens.reshape([6, 2]) print("\n After Resize this Tensor to 6x2 : \n", tens_2) 

Output:  

Method 3: Using resize() method

This method is also used to resize tensors in PyTorch and the below syntax helps us to resize the tensor.

Syntax: tensor.resize_(no_of_tensors, no_of_rows, no_of_columns)

Parameters:

  • 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 5:

The following program is to understand how to resize the tensor using resize() method.

Python
# import torch module import torch  # Define an 1D tensor tens = torch.Tensor([11, 12, 13, 14, 15, 16, 17, 18])  # display tensor print("\n Original 2D Tensor: \n", tens)  # resize the tensor to 4 tensors. # each tensor with 4 rows and 5 columns tens_1 = tens.resize_(4, 4, 5) print("\n After resize tensor: \n", tens_1) 

Output:

Method 4: Using unsqueeze() method

This is used to resize a tensor by adding new dimensions at given positions. below syntax is used to resize tensor using unsqueeze() method.

Syntax: tensor.unsqueeze(position)

Parameter: position is the dimension index which will start from 0.

Return: It returns a new tensor dimension of size 1 inserted at specific position.

Example 6:

The following program is to resize tensor using unsqueeze() method.

Python
# import torch library import torch  # define a tensor tens = torch.Tensor([10, 20, 30, 40, 50])  # display tensor and it's size print("\n Original Tensor: ", tens)  # Squeeze the tensor in dimension 1 tens_1 = torch.unsqueeze(tens, dim=1) print("\n After resize tensor to 5x1: \n", tens_1) 

Output:


Next Article
How to Upsample a PyTorch Tensor?
author
mukulsomukesh
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • Geeks-Premier-League-2022
  • Python-PyTorch
Practice Tags :
  • python

Similar Reads

  • 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
  • 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. Crea
    7 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
  • How to Upsample a PyTorch Tensor?
    As the amount of data generated by modern sensors and simulations continues to grow, it's becoming increasingly common for datasets to include multiple channels representing different properties or dimensions. However, in some cases, these channels may be at a lower resolution or spatial/temporal sc
    8 min read
  • How To Sort The Elements of a Tensor in PyTorch?
    In this article, we are going to see how to sort the elements of a PyTorch Tensor in Python. To sort the elements of a PyTorch tensor, we use torch.sort() method.  We can sort the elements along with columns or rows when the tensor is 2-dimensional. Syntax: torch.sort(input, dim=- 1, descending=Fals
    3 min read
  • How to Reshape a Tensor in Tensorflow?
    Tensor reshaping is the process of reshaping the order and total number of elements in tensors while only the shape is being changed. It is a fundamental operation in TensorFlow that allows you to change the shape of a tensor without changing its underlying data. Using tf.reshape() In TensorFlow, th
    4 min read
  • How to Get the Value of a Tensor in PyTorch
    When working with PyTorch, a powerful and flexible deep learning framework, you often need to access and manipulate the values stored within tensors. Tensors are the core data structures in PyTorch, representing multi-dimensional arrays that can store various types of data, including scalars, vector
    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
  • Two-Dimensional Tensors in Pytorch
    PyTorch is a python library developed by Facebook to run and train machine learning and deep learning models. In PyTorch everything is based on tensor operations. Two-dimensional tensors are nothing but matrices or vectors of two-dimension with specific datatype, of n rows and n columns. Representat
    3 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
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