PyTorch torch.nn.AdaptiveMaxPool2d function
PyTorch torch.nn Reference Manual
torch.nn.AdaptiveMaxPool2d is the adaptive max pooling module in PyTorch.
It pools the input to a specified size, preserving the maximum value rather than the average.
Function definition
torch.nn.AdaptiveMaxPool2d(output_size, return_indices=False)
Parameters
output_size: Output sizereturn_indices: Whether to return indices
Usage examples
Example 1: Basic usage
Example
import
torch
import
torch.
nn
as
nn
Global max pooling
gap
=
nn.
AdaptiveMaxPool2d
(
1
)
Inputs of different sizes
x1
=
torch.
randn
(
1
,
64
,
32
,
32
)
x2
=
torch.
randn
(
1
,
64
,
16
,
16
)
(
"32x32 ->"
,
gap
(
x1
)
.
shape
)
(
"16x16 ->"
,
gap
(
x2
)
.
shape
)
Example 2: Return indices
Example
import
torch
import
torch.
nn
as
nn
gap
=
nn.
AdaptiveMaxPool2d
(
1
,
return_indices
=
True
)
x
=
torch.
randn
(
1
,
64
,
8
,
8
)
output
,
indices
=
gap
(
x
)
(
"Output shape:"
,
output.
shape
)
(
"Index shape:"
,
indices.
shape
)
(
"Index values:"
,
indices.
item
(
)
)
Example 3: Comparison with AdaptiveAvgPool2d
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
)
avgpool
=
nn.
AdaptiveAvgPool2d
(
1
)
maxpool
=
nn.
AdaptiveMaxPool2d
(
1
)
(
"Input:n"
,
x
[
0
,
0
]
)
(
"Average pooling:"
,
avgpool
(
x
)
.
item
(
)
)
(
"Max pooling:"
,
maxpool
(
x
)
.
item
(
)
)
Use Cases
- Global max pooling: Extracts the most salient features
- Feature aggregation: Preserves key information
- Classification networks: Replaces the FC layer
Tip: Max pooling preserves the most salient features, while average pooling is smoother.