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

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.

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

Similar Reads

Method 1 : Using reshape() Method

...

Method 2 : Using flatten() method

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

Method 3: Using view() method

...

Method 4: Using resize() method

...

Method 5: Using unsqueeze() method

...

Contact Us