PyTorch torch.nn.Dropout2d function
PyTorch torch.nn Reference Manual
torch.nn.Dropout2d is a 2D Dropout module in PyTorch.
It randomly zeroes out entire channels, making it suitable for feature maps in convolutional layers.
Function definition
torch.nn.Dropout2d(p=0.5, inplace=False)
Feature
- Randomly zero out along the channel dimension
- All channels of each sample keep a consistent dropout pattern
Usage examples
Example 1: Basic usage
Example
import
torch
import
torch.
nn
as
nn
dropout2d
=
nn.
Dropout2d
(
p
=
0.5
)
dropout2d.
train
(
)
Input: batch=4, channels=8, height=16, width=16
x
=
torch.
ones
(
4
,
8
,
16
,
16
)
output
=
dropout2d
(
x
)
Count the dropped channels
non_zero_channels
=
(
output.
sum
(
dim
=
(
2
,
3
)
)
!=
0
)
.
float
(
)
(
"Ratio of non-zero channels:"
,
non_zero_channels.
mean
(
)
.
item
(
)
)
(
"About 0.5 of the channels are expected to be kept"
)
Example 2: Comparing Dropout
Example
import
torch
import
torch.
nn
as
nn
dropout1d
=
nn.
Dropout
(
0.5
)
dropout2d
=
nn.
Dropout2d
(
0.5
)
Input
x
=
torch.
randn
(
2
,
4
,
8
,
8
)
Dropout: randomly zero out individual elements
out1
=
dropout1d
(
x
)
Dropout2d: zero out by channel
out2
=
dropout2d
(
x
)
(
"Dropout shape:"
,
out1.
shape
)
(
"Dropout2d shape:"
,
out2.
shape
)
Example 3: Use in a CNN
Example
import
torch
import
torch.
nn
as
nn
A CNN with Dropout2d
model
=
nn.
Sequential
(
nn.
Conv2d
(
3
,
64
,
3
,
padding
=
1
)
,
nn.
BatchNorm2d
(
64
)
,
nn.
ReLU
(
)
,
nn.
Dropout2d
(
0.3
)
,
Drop at the feature-map level
nn.
Conv2d
(
64
,
128
,
3
,
padding
=
1
)
,
nn.
BatchNorm2d
(
128
)
,
nn.
ReLU
(
)
,
nn.
AdaptiveAvgPool2d
(
1
)
,
nn.
Flatten
(
)
,
nn.
Linear
(
128
,
10
)
)
x
=
torch.
randn
(
4
,
3
,
32
,
32
)
output
=
model
(
x
)
(
"Input:"
,
x.
shape
,
"-> Output:"
,
output.
shape
)
Use Cases
- Convolutional networks: feature-map level regularization
- Reduce channel dependency
Note: Dropout2d drops channels during training and has no effect during evaluation.