PyTorch torch.nn.Flatten function
PyTorch torch.nn Reference Manual
torch.nn.Flatten is a tensor flattening module in PyTorch.
It flattens a multi-dimensional tensor into one dimension and is often used to connect convolutional layers to fully connected layers.
Function definition
torch.nn.Flatten(start_dim=1, end_dim=-1)
Parameter Description:
start_dim(int): the dimension at which flattening starts. Default is 1 (keeping the batch dimension).end_dim(int): the dimension at which flattening ends. Default is -1 (the last dimension).
Usage examples
Example 1: Basic usage
Example
import
torch
import
torch.
nn
as
nn
flatten
=
nn.
Flatten
(
)
4D input: (batch, channels, height, width)
x
=
torch.
randn
(
4
,
3
,
32
,
32
)
output
=
flatten
(
x
)
(
"Input shape:"
,
x.
shape
)
(
"Output shape:"
,
output.
shape
)
(
"After flattening: 33232 = 3072 dimensions"
)
Example 2: Keeping the batch dimension
Example
import
torch
import
torch.
nn
as
nn
start_dim=1 keeps the batch dimension
x
=
torch.
randn
(
8
,
64
,
8
,
8
)
(
"Input:"
,
x.
shape
)
Flatten to (8, 4096)
out1
=
nn.
Flatten
(
start_dim
=
1
)
(
x
)
(
"Starting from dimension 1:"
,
out1.
shape
)
Do not keep the batch dimension
out2
=
nn.
Flatten
(
start_dim
=
0
)
(
x
)
(
"Starting from dimension 0:"
,
out2.
shape
)
Example 3: 3D input
Example
import
torch
import
torch.
nn
as
nn
3D input: (batch, seq_len, features)
x
=
torch.
randn
(
4
,
100
,
512
)
Flatten the sequence and feature dimensions
flatten
=
nn.
Flatten
(
start_dim
=
1
)
output
=
flatten
(
x
)
(
"Input shape:"
,
x.
shape
)
(
"Output shape:"
,
output.
shape
)
Example 4: A complete CNN example
Example
import
torch
import
torch.
nn
as
nn
model
=
nn.
Sequential
(
nn.
Conv2d
(
3
,
32
,
3
,
padding
=
1
)
,
nn.
ReLU
(
)
,
nn.
MaxPool2d
(
2
)
,
nn.
Conv2d
(
32
,
64
,
3
,
padding
=
1
)
,
nn.
ReLU
(
)
,
nn.
AdaptiveAvgPool2d
(
1
)
,
nn.
Flatten
(
)
,
nn.
Linear
(
64
,
10
)
)
x
=
torch.
randn
(
4
,
3
,
32
,
32
)
output
=
model
(
x
)
(
"Input:"
,
x.
shape
,
"-> Output:"
,
output.
shape
)
Use Cases
- CNN to FC: flatten the convolutional layer output before connecting to a fully connected layer
- Dimension transformation: reshape tensors