TL;DR: torch.flatten()

Use torch.flatten() which was introduced in v0.4.1 and documented in v1.0rc1:

>>> t = torch.tensor([[[1, 2],
                       [3, 4]],
                      [[5, 6],
                       [7, 8]]])
>>> torch.flatten(t)
tensor([1, 2, 3, 4, 5, 6, 7, 8])
>>> torch.flatten(t, start_dim=1)
tensor([[1, 2, 3, 4],
        [5, 6, 7, 8]])

For v0.4.1 and earlier, use t.reshape(-1).


With t.reshape(-1):

If the requested view is contiguous in memory this will equivalent to t.view(-1) and memory will not be copied.

Otherwise it will be equivalent to t.contiguous().view(-1).


Other non-options:

  • t.view(-1) won't copy memory, but may not work depending on original size and stride

  • t.resize(-1) gives RuntimeError (see below)

  • t.resize(t.numel()) warning about being a low-level method (see discussion below)

(Note: pytorch's reshape() may change data but numpy's reshape() won't.)


t.resize(t.numel()) needs some discussion. The torch.Tensor.resize_ documentation says:

The storage is reinterpreted as C-contiguous, ignoring the current strides (unless the target size equals the current size, in which case the tensor is left unchanged)

Given the current strides will be ignored with the new (1, numel()) size, the order of the elements may apppear in a different order than with reshape(-1). However, "size" may mean the memory size, rather than the tensor's size.

It would be nice if t.resize(-1) worked for both convenience and efficiency, but with torch 1.0.1.post2, t = torch.rand([2, 3, 5]); t.resize(-1) gives:

RuntimeError: requested resize to -1 (-1 elements in total), but the given 
tensor has a size of 2x2 (4 elements). autograd's resize can only change the 
shape of a given tensor, while preserving the number of elements.

I raised a feature request for this here, but the consensus was that resize() was a low level method, and reshape() should be used in preference.

Answer from Tom Hale on Stack Overflow
Top answer
1 of 4
71

TL;DR: torch.flatten()

Use torch.flatten() which was introduced in v0.4.1 and documented in v1.0rc1:

>>> t = torch.tensor([[[1, 2],
                       [3, 4]],
                      [[5, 6],
                       [7, 8]]])
>>> torch.flatten(t)
tensor([1, 2, 3, 4, 5, 6, 7, 8])
>>> torch.flatten(t, start_dim=1)
tensor([[1, 2, 3, 4],
        [5, 6, 7, 8]])

For v0.4.1 and earlier, use t.reshape(-1).


With t.reshape(-1):

If the requested view is contiguous in memory this will equivalent to t.view(-1) and memory will not be copied.

Otherwise it will be equivalent to t.contiguous().view(-1).


Other non-options:

  • t.view(-1) won't copy memory, but may not work depending on original size and stride

  • t.resize(-1) gives RuntimeError (see below)

  • t.resize(t.numel()) warning about being a low-level method (see discussion below)

(Note: pytorch's reshape() may change data but numpy's reshape() won't.)


t.resize(t.numel()) needs some discussion. The torch.Tensor.resize_ documentation says:

The storage is reinterpreted as C-contiguous, ignoring the current strides (unless the target size equals the current size, in which case the tensor is left unchanged)

Given the current strides will be ignored with the new (1, numel()) size, the order of the elements may apppear in a different order than with reshape(-1). However, "size" may mean the memory size, rather than the tensor's size.

It would be nice if t.resize(-1) worked for both convenience and efficiency, but with torch 1.0.1.post2, t = torch.rand([2, 3, 5]); t.resize(-1) gives:

RuntimeError: requested resize to -1 (-1 elements in total), but the given 
tensor has a size of 2x2 (4 elements). autograd's resize can only change the 
shape of a given tensor, while preserving the number of elements.

I raised a feature request for this here, but the consensus was that resize() was a low level method, and reshape() should be used in preference.

2 of 4
16

Use torch.reshape and only a single dimension can be passed to flatten it. If you do not want the dimension to be hardcoded, just -1 could be specified and the correct dimension would be inferred.

>>> x = torch.tensor([[1,2], [3,4]])
>>> x.reshape(-1)
tensor([1, 2, 3, 4])

EDIT:

For your example:

🌐
Sprintchase
sprintchase.com › home › torch.flatten(): flattening a tensor in pytorch
torch.flatten(): Flattening a Tensor in PyTorch
May 16, 2025 - The torch.flatten() method reshapes one or more dimensional tensors into a single-dimensional tensor.
🌐
DeepLizard
deeplizard.com › learn › video › fCVuiW9AFzY
Flatten, Reshape, and Squeeze Explained - Tensors for Deep Learning with PyTorch - deeplizard
A flatten operation on a tensor reshapes the tensor to have a shape that is equal to the number of elements contained in the tensor.
🌐
CodeSignal
codesignal.com › learn › courses › introduction-to-pytorch-tensors › lessons › reshaping-and-flattening-tensors-in-pytorch
Reshaping and Flattening Tensors in PyTorch
Another common tensor operation is flattening, where a multi-dimensional tensor is transformed into a one-dimensional tensor. Think of it as unwrapping the elements of the tensor and aligning them in a single row.
🌐
Data Science Weekly
datascienceweekly.org › tutorials › flatten-a-tensorflow-tensor
Flatten A TensorFlow Tensor
So it will just be one flat tensor. To flatten the tensor, we’re going to use the TensorFlow reshape operation.
Find elsewhere
🌐
DEV Community
dev.to › hyperkai › flatten-and-ravel-in-pytorch-56k5
flatten and ravel in PyTorch - DEV Community
November 6, 2024 - Basically, Flatten() is used to define a model while flatten() is not used to define a model. import torch my_tensor = torch.tensor(7) torch.flatten(input=my_tensor) my_tensor.flatten() torch.flatten(input=my_tensor, start_dim=0, end_dim=0) torch.flatten(input=my_tensor, start_dim=0, end_dim=-1) torch.flatten(input=my_tensor, start_dim=-1, end_dim=0) torch.flatten(input=my_tensor, start_dim=-1, end_dim=-1) # tensor([7]) my_tensor = torch.tensor([7, 1, -8, 3, -6, 0]) torch.flatten(input=my_tensor) torch.flatten(input=my_tensor, start_dim=0, end_dim=0) torch.flatten(input=my_tensor, start_dim=0,
🌐
Medium
medium.com › pythons-gurus › what-is-the-actual-meaning-of-flattening-a-tensor-b26a0419713c
What is the actual meaning of Flattening a Tensor ? | by Abhishek Kumar Pandey | Python’s Gurus | Medium
June 18, 2024 - The flatten operation takes a multi-dimensional tensor and arranges all its elements into a single dimension. This is done by collapsing all dimensions except the batch dimension, resulting in a one-dimensional array.
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-flatten-an-input-tensor-by-reshaping-it-in-pytorch
How to flatten an input tensor by reshaping it in PyTorch?
January 20, 2022 - A tensor can be flattened into a one-dimensional tensor by reshaping it using the method torch.flatten(). This method supports both real and complex-valued input tensors. It takes a torch tensor as its input and returns a torch tensor flattened into
🌐
DEV Community
dev.to › hyperkai › flatten-in-pytorch-3bl0
Flatten in PyTorch - DEV Community
November 6, 2024 - import torch from torch import nn flatten = nn.Flatten() flatten # Flatten(start_dim=1, end_dim=-1) flatten.start_dim # 1 flatten.end_dim # -1 my_tensor = torch.tensor(7) flatten = nn.Flatten(start_dim=0, end_dim=0) flatten = nn.Flatten(start_dim=0, end_dim=-1) flatten = nn.Flatten(start_dim=-1, end_dim=0) flatten = nn.Flatten(start_dim=-1, end_dim=-1) flatten(input=my_tensor) # tensor([7]) my_tensor = torch.tensor([7, 1, -8, 3, -6, 0]) flatten = nn.Flatten(start_dim=0, end_dim=0) flatten = nn.Flatten(start_dim=0, end_dim=-1) flatten = nn.Flatten(start_dim=-1, end_dim=0) flatten = nn.Flatten(s
🌐
MyScale
myscale.com › blog › effortless-pytorch-flatten-guide-tensor-reshaping
Master PyTorch Flatten: Effortless Guide for Tensor Reshaping
April 24, 2024 - By sequentially arranging elements along a single axis, the original tensor's shape is altered to facilitate efficient computations during model training and inference. In PyTorch flatten, two optional parameters, start_dim and end_dim, offer flexibility in specifying which dimensions to flatten within the input tensor.
🌐
YouTube
youtube.com › watch
Flatten A TensorFlow Tensor - TensorFlow Tutorial - YouTube
Flatten A TensorFlow Tensor - TensorFlow Tutorial
Published: April 25, 2022
🌐
Medium
medium.com › @imabhi1216 › pytorch-zero-to-hero-reshape-flatten-and-concatenate-tensors-2-0adf6d3917c3
PyTorch Zero to Hero (Reshape, Flatten, and Concatenate Tensors)~ 2 | by Abhishek Selokar | Medium
June 7, 2024 - It helps in reshaping input into a one-dimensional tensor. The order of elements in input is unchanged. If start_dim or end_dim are passed, only dimensions starting with start_dim and ending with end_dim are flattened.
🌐
Python Guides
pythonguides.com › pytorch-flatten
How to Use PyTorch Flatten for Neural Network Models
June 19, 2025 - PyTorch Flatten is a layer that reshapes a tensor by “flattening” it across specified dimensions.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › pytorch tutorial › pytorch flatten
PyTorch Flatten | What is PyTorch Flatten along with Examples?
April 6, 2023 - PyTorch Flatten is used to reshape any tensor with different dimensions to a single dimension so that we can do further operations on the same input data. The shape of the tensor will be the same as that of the number of elements in the tensor.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai