Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.nn.AdaptiveMaxPool2d function

PyTorch torch.nn.AdaptiveMaxPool2d function

PyTorch torch.nn Reference Manual 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


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

)

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

(

"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

(

)

)


Use Cases

Tip: Max pooling preserves the most salient features, while average pooling is smoother.


PyTorch torch.nn Reference Manual PyTorch torch.nn Reference Manual