Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.nn.Flatten function

PyTorch torch.nn.Flatten function

PyTorch torch.nn Reference Manual 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:


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

)

print

(

"Input shape:"

,

x.

shape

)

print

(

"Output shape:"

,

output.

shape

)

print

(

"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

)

print

(

"Input:"

,

x.

shape

)

Flatten to (8, 4096)

out1

=

nn.

Flatten

(

start_dim

=

1

)

(

x

)

print

(

"Starting from dimension 1:"

,

out1.

shape

)

Do not keep the batch dimension

out2

=

nn.

Flatten

(

start_dim

=

0

)

(

x

)

print

(

"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

)

print

(

"Input shape:"

,

x.

shape

)

print

(

"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

)

print

(

"Input:"

,

x.

shape

,

"-> Output:"

,

output.

shape

)


Use Cases


PyTorch torch.nn Reference Manual PyTorch torch.nn Reference Manual