PyTorch torch.nn.AdaptiveMaxPool2d Function
PyTorch torch.nn Reference Manual
torch.nn.AdaptiveMaxPool2dIt is an adaptive max pooling module in PyTorch.
It pools the input to a specified size, retaining 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 with different sizes
x1 = torch.randn(1, 64, 32, 32)
x2 = torch.randn(1, 64, 16, 16)
print("32x32 ->", gap(x1).shape)
print("16x16 ->", gap(x2).shape)
import torch.nn as nn
# Global max pooling
gap = nn.AdaptiveMaxPool2d(1)
# Inputs with different sizes
x1 = torch.randn(1, 64, 32, 32)
x2 = torch.randn(1, 64, 16, 16)
print("32x32 ->", gap(x1).shape)
print("16x16 ->", gap(x2).shape)
Example 2: Returning 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)
print("Output shape:", output.shape)
print("Index shape:", indices.shape)
print("Index values:", indices.item())
import torch.nn as nn
gap = nn.AdaptiveMaxPool2d(1, return_indices=True)
x = torch.randn(1, 64, 8, 8)
output, indices = gap(x)
print("Output shape:", output.shape)
print("Index shape:", indices.shape)
print("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)
print("Input:\n", x[0, 0])
print("Average pooling:", avgpool(x).item())
print("Max pooling:", maxpool(x).item())
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)
print("Input:\n", x[0, 0])
print("Average pooling:", avgpool(x).item())
print("Max pooling:", maxpool(x).item())
Use Cases
- Global max pooling: Extract the most significant features
- Feature aggregation: Preserve key information
- Classification networks: Replace FC layers
Tip: Max pooling retains the most significant features, while average pooling is smoother.
Other Extensions