PyTorch torch.nn.AvgPool2d function
PyTorch torch.nn Reference Manual
torch.nn.AvgPool2d is the two-dimensional average pooling module in PyTorch.
It computes the average over each window of the input, commonly used for downsampling and feature aggregation.
Function definition
torch.nn.AvgPool2d(kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True)
Parameter Description
kernel_size: Pooling window sizestride: Stride, defaults to kernel_sizepadding: Padding sizeceil_mode: Whether to use ceil to compute the output size
Usage examples
Example 1: Basic usage
Example
import
torch
import
torch.
nn
as
nn
pool
=
nn.
AvgPool2d
(
kernel_size
=
2
,
stride
=
2
)
x
=
torch.
randn
(
1
,
1
,
4
,
4
)
output
=
pool
(
x
)
(
"Input:n"
,
x.
squeeze
(
)
.
tolist
(
)
)
(
"nOutput:n"
,
output.
squeeze
(
)
.
tolist
(
)
)
(
"Shape:"
,
x.
shape
,
"->"
,
output.
shape
)
Example 2: Global average pooling
Example
import
torch
import
torch.
nn
as
nn
Global average pooling
gap
=
nn.
AdaptiveAvgPool2d
(
1
)
x
=
torch.
randn
(
4
,
64
,
16
,
16
)
out
=
gap
(
x
)
(
"Input:"
,
x.
shape
)
(
"Output:"
,
out.
shape
)
(
"Number of averages per channel:"
,
out.
numel
(
)
//
64
)
Example 3: Comparison with MaxPool
Example
import
torch
import
torch.
nn
as
nn
x
=
torch.
tensor
(
[
[
[
[
1
,
2
,
3
,
4
]
,
[
5
,
6
,
7
,
8
]
,
[
9
,
10
,
11
,
12
]
,
[
13
,
14
,
15
,
16
]
]
]
]
,
dtype
=
torch.
float32
)
maxpool
=
nn.
MaxPool2d
(
2
,
2
)
avgpool
=
nn.
AvgPool2d
(
2
,
2
)
(
"Input:n"
,
x
[
0
,
0
]
)
(
"nMaxPool:n"
,
maxpool
(
x
)
[
0
,
0
]
)
(
"nAvgPool:n"
,
avgpool
(
x
)
[
0
,
0
]
)
Use Cases
- Feature aggregation: Reduces spatial dimensions
- Global average pooling: Replaces fully connected layers
- Smooths featuresReduces noise