Reshaping a Tensor in Pytorch
Last Updated :
01 Sep, 2021
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
a = torch.tensor([1,2,3,4,5,6,7,8])
print(a.shape)
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
a = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8])
print(a.shape)
print(a)
print(a.reshape([4, 2]))
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
a = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8])
print(a.shape)
print(a)
print(a.reshape([4, 2]))
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
a = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8])
print(a.shape)
print(a)
print(a.reshape([8, 1]))
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
a = torch.tensor([[1,2,3,4,5,6,7,8],
[1,2,3,4,5,6,7,8]])
print(a)
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
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]]])
print(a)
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
import torch
a=torch.FloatTensor([24, 56, 10, 20, 30,
40, 50, 1, 2, 3, 4, 5])
print(a.view(4, 3))
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
import torch
a = torch.FloatTensor([24, 56, 10, 20, 30,
40, 50, 1, 2, 3])
print(a.view(10, 1))
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
import torch
a = torch.Tensor()
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
import torch
a = torch.Tensor()
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
import torch
a = torch.Tensor([[2,3], [1,2]])
print(a.shape)
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
import torch
a = torch.Tensor([1, 2, 3, 4, 5])
print(a.shape)
added = a.unsqueeze(0)
print(added.shape)
added = a.unsqueeze(1)
print(added.shape)
|
Output:
torch.Size([5])
torch.Size([1, 5])
torch.Size([5, 1])
Similar Reads
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
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: C/C++ Code # import torch module import torch # create an 3 D tensor with 8 e
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
How to join tensors in PyTorch?
In this article, we are going to see how to join two or more tensors in PyTorch. We can join tensors in PyTorch using torch.cat() and torch.stack() functions. Both the function help us to join the tensors but torch.cat() is basically used to concatenate the given sequence of tensors in the given dim
4 min read
Repeating Tensors in a Specific New Dimension in PyTorch
In PyTorch, one of the essential operations in tensor manipulation is repeating tensors along specific dimensions. This can be useful in various scenarios such as data replication, tiling, or creating larger datasets.This article discusses the concept of tensor repetition, how tensor repetition does
6 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 TensorShap
2 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
What is PyTorch ?
Deep Learning is a branch of Machine Learning where algorithms are written that mimic the functioning of a human brain. The most commonly used libraries in deep learning are Tensorflow and PyTorch. Pytorch is an open-source deep learning framework available with a Python and C++ interface. The PyTor
10 min read
How to compare two tensors in PyTorch?
In this article, we are going to see how we can compare two tensors in Pytorch. We can compare two tensors by using the torch.eq() method. This method compares the corresponding elements of tensors. It has to return rue at each location where both tensors have equal value else it will return false.
2 min read
Understanding Broadcasting in PyTorch
Broadcasting is a fundamental concept in PyTorch that allows element-wise operations between tensors with diverse shapes. PyTorch automatically conforms (or "broadcasts") the smaller tensor's shape to match the larger tensor's when the two tensors have different dimensions. This allows the operation
8 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
Python - PyTorch is_tensor() method
PyTorch torch.is_tensor() method returns True if the passed object is a PyTorch tensor. Syntax: torch.is_tensor(object) Arguments object: This is input tensor to be tested. Return: It returns either True or False. Let's see this concept with the help of few examples: Example 1: # Importing the PyTor
1 min read