YouTip LogoYouTip

Pytorch Torch Nn Adaptivemaxpool2D

# PyTorch torch.nn.AdaptiveMaxPool2d Function [![Image 3: PyTorch torch.nn Reference Manual](https://example.com/images/up.gif) PyTorch torch.nn Reference Manual](https://example.com/pytorch/pytorch-torch-nn-ref.html) * * * `torch.nn.AdaptiveMaxPool2d` 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 size * `return_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) # Different input 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: 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) print("Output shape:", output.shape) print("Indices shape:", indices.shape) print("Index value:", 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("Avg pool:", avgpool(x).item()) print("Max pool:", maxpool(x).item()) * * * ## Use Cases * **Global max pooling**: Extract the most salient features * **Feature aggregation**: Retain key information * **Classification networks**: Replace FC layers > Tip: Max pooling retains the most salient features, while average pooling is smoother. * * * [![Image 4: PyTorch torch.nn Reference Manual](https://example.com/images/up.gif) PyTorch torch.nn Reference Manual](https://example.com/pytorch/pytorch-torch-nn-ref.html)
← Pytorch Torch Nn BcewithlogitsPytorch Torch Zeros β†’