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

PyTorch torch.nn.AvgPool2d function

PyTorch torch.nn.AvgPool2d function

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


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

)

print

(

"Input:n"

,

x.

squeeze

(

)

.

tolist

(

)

)

print

(

"nOutput:n"

,

output.

squeeze

(

)

.

tolist

(

)

)

print

(

"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

)

print

(

"Input:"

,

x.

shape

)

print

(

"Output:"

,

out.

shape

)

print

(

"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

)

print

(

"Input:n"

,

x

[

0

,

0

]

)

print

(

"nMaxPool:n"

,

maxpool

(

x

)

[

0

,

0

]

)

print

(

"nAvgPool:n"

,

avgpool

(

x

)

[

0

,

0

]

)


Use Cases


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