pooling.py 55.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from ...fluid.layer_helper import LayerHelper
from .. import functional as F
Z
zhiboniu 已提交
17
from .. import Layer
18

19 20
__all__ = []

21

Z
zhiboniu 已提交
22
class AvgPool1D(Layer):
W
Wei Shengyu 已提交
23
    r"""
24
    This operation applies a 1D average pooling over an input signal composed
25
    of several input planes, based on the input, output_size, return_mask parameters.
26 27 28 29 30
    Input(X) and output(Out) are in NCL format, where N is batch
    size, C is the number of channels, L is the length of the feature.
    The output tensor shape will be [N, C, output_size].

    The output value of the layer with input size (N, C, L),
W
Wei Shengyu 已提交
31
    output (N, C, :math:`L_{out}`) and kernel_size ksize can be precisely described as
32 33 34 35
    For average pool1d:

    ..  math::

W
Wei Shengyu 已提交
36
        Output(N_i, C_i, l) = \frac{Input[N_i, C_i, stride \times l:stride \times l+k]}{ksize}
37

W
Wei Shengyu 已提交
38 39
    Parameters:
        kernel_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
40
            it must contain an integer.
W
Wei Shengyu 已提交
41 42 43
        stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list,
            it must contain an integer. Default None, then stride will be equal to the kernel_size.
        padding(str|int|list|tuple, optional): The padding size. Padding could be in one of the following forms.
44 45 46 47 48 49
            1. A string in ['valid', 'same'].
            2. An int, which means the feature map is zero padded by size of `padding` on every sides.
            3. A list[int] or tuple(int) whose length is 1, which means the feature map is zero padded by the size of `padding[0]` on every sides.
            4. A list[int] or tuple(int) whose length is 2. It has the form [pad_before, pad_after].
            5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
            The default value is 0.
W
Wei Shengyu 已提交
50 51 52 53 54
        exclusive(bool, optional): Whether to exclude padding points in average pooling mode, default is `True`.
        ceil_mode(bool, optional): ${ceil_mode_comment}Whether to use the ceil function to calculate output height
            and width. If it is set to False, the floor function will be used. The default value is False.
        name(str, optional): For eed to detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no nset and None by default.
55

56
    Shape:
W
Wei Shengyu 已提交
57 58 59 60
        - x(Tensor): The input tensor of avg pool1d operator, which is a 3-D tensor.
          The data type can be float32, float64.
        - output(Tensor): The output tensor of avg pool1d  operator, which is a 3-D tensor.
          The data type is same as input x.
61

62 63
    Returns:
        A callable object of AvgPool1D.
L
Ligoml 已提交
64

65 66 67
    Examples:

        .. code-block:: python
68

W
Wei Shengyu 已提交
69 70
            import paddle
            import paddle.nn as nn
71

72
            data = paddle.uniform([1, 3, 32], dtype="float32", min=-1, max=1)
W
Wei Shengyu 已提交
73 74 75
            AvgPool1D = nn.AvgPool1D(kernel_size=2, stride=2, padding=0)
            pool_out = AvgPool1D(data)
            # pool_out shape: [1, 3, 16]
76 77 78

    """

L
Ligoml 已提交
79 80 81 82 83 84 85 86 87
    def __init__(
        self,
        kernel_size,
        stride=None,
        padding=0,
        exclusive=True,
        ceil_mode=False,
        name=None,
    ):
C
cnn 已提交
88
        super(AvgPool1D, self).__init__()
89 90 91 92
        self.kernel_size = kernel_size
        self.stride = stride
        self.padding = padding
        self.ceil_mode = ceil_mode
93
        self.exclusive = exclusive
94 95 96
        self.name = name

    def forward(self, x):
L
Ligoml 已提交
97 98 99 100 101 102 103 104 105
        out = F.avg_pool1d(
            x,
            self.kernel_size,
            self.stride,
            self.padding,
            self.exclusive,
            self.ceil_mode,
            self.name,
        )
106 107
        return out

108 109
    def extra_repr(self):
        return 'kernel_size={kernel_size}, stride={stride}, padding={padding}'.format(
L
Ligoml 已提交
110 111
            **self.__dict__
        )
112

113

Z
zhiboniu 已提交
114
class AvgPool2D(Layer):
115
    r"""
116 117 118 119
    This operation applies 2D average pooling over input features based on the input,
    and kernel_size, stride, padding parameters. Input(X) and Output(Out) are
    in NCHW format, where N is batch size, C is the number of channels,
    H is the height of the feature, and W is the width of the feature.
120

121
    Example:
W
Wei Shengyu 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        Input:
            X shape: :math:`(N, C, :math:`H_{in}`, :math:`W_{in}`)`
        Attr:
            kernel_size: ksize

        Output:
            Out shape: :math:`(N, C, :math:`H_{out}`, :math:`W_{out}`)`

        ..  math::

            Output(N_i, C_j, h, w)  = \frac{\sum_{m=0}^{ksize[0]-1} \sum_{n=0}^{ksize[1]-1}
                Input(N_i, C_j, stride[0] \times h + m, stride[1] \times w + n)}{ksize[0] * ksize[1]}

    Parameters:
        kernel_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
137 138
            it must contain two integers, (pool_size_Height, pool_size_Width).
            Otherwise, the pool kernel size will be a square of an int.
W
Wei Shengyu 已提交
139
        stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list,
140 141
            it must contain two integers, (pool_stride_Height, pool_stride_Width).
            Otherwise, the pool stride size will be a square of an int.
W
Wei Shengyu 已提交
142 143
            Default None, then stride will be equal to the kernel_size.
        padding(str|int|list|tuple, optional): The padding size. Padding could be in one of the following forms.
144 145 146 147 148 149
            1. A string in ['valid', 'same'].
            2. An int, which means the feature map is zero padded by size of `padding` on every sides.
            3. A list[int] or tuple(int) whose length is 2, [pad_height, pad_weight] whose value means the padding size of each dimension.
            4. A list[int] or tuple(int) whose length is 4. [pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side.
            5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
            The default value is 0.
W
Wei Shengyu 已提交
150 151 152 153 154 155 156 157 158 159
        ceil_mode(bool, optional): When True, will use `ceil` instead of `floor` to compute the output shape.
        exclusive(bool, optional): Whether to exclude padding points in average pooling
            mode, default is `true`.
        divisor_override(float, optional): If specified, it will be used as divisor, otherwise kernel_size will be
            used. Default None.
        data_format(str, optional): The data format of the input and output data. An optional string from: `"NCHW"`,
            `"NDHW"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
            `[batch_size, input_channels, input_height, input_width]`.
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
160

161
    Shape:
W
Wei Shengyu 已提交
162 163 164 165
        - x(Tensor): The input tensor of avg pool2d operator, which is a 4-D tensor.
          The data type can be float32, float64.
        - output(Tensor): The output tensor of avg pool2d  operator, which is a 4-D tensor.
          The data type is same as input x.
166

W
Wei Shengyu 已提交
167 168
    Returns:
        A callable object of AvgPool2D.
169

170 171
    Examples:
        .. code-block:: python
172

W
Wei Shengyu 已提交
173 174
            import paddle
            import paddle.nn as nn
175

W
Wei Shengyu 已提交
176
            # max pool2d
177
            input = paddle.uniform([1, 3, 32, 32], dtype="float32", min=-1, max=1)
W
Wei Shengyu 已提交
178
            AvgPool2D = nn.AvgPool2D(kernel_size=2,
179
                                stride=2, padding=0)
W
Wei Shengyu 已提交
180 181
            output = AvgPool2D(input)
            # output.shape [1, 3, 16, 16]
182 183 184

    """

L
Ligoml 已提交
185 186 187 188 189 190 191 192 193 194 195
    def __init__(
        self,
        kernel_size,
        stride=None,
        padding=0,
        ceil_mode=False,
        exclusive=True,
        divisor_override=None,
        data_format="NCHW",
        name=None,
    ):
C
cnn 已提交
196
        super(AvgPool2D, self).__init__()
197
        self.ksize = kernel_size
198 199 200
        self.stride = stride
        self.padding = padding
        self.ceil_mode = ceil_mode
201
        self.exclusive = exclusive
202 203
        self.divisor = divisor_override
        self.data_format = data_format
204 205
        self.name = name

206
    def forward(self, x):
L
Ligoml 已提交
207 208 209 210 211 212 213 214 215 216 217
        return F.avg_pool2d(
            x,
            kernel_size=self.ksize,
            stride=self.stride,
            padding=self.padding,
            ceil_mode=self.ceil_mode,
            exclusive=self.exclusive,
            divisor_override=self.divisor,
            data_format=self.data_format,
            name=self.name,
        )
218

219 220
    def extra_repr(self):
        return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format(
L
Ligoml 已提交
221 222
            **self.__dict__
        )
223

224

Z
zhiboniu 已提交
225
class AvgPool3D(Layer):
226
    """
227 228 229 230
    This operation applies 3D max pooling over input features based on the input,
    and kernel_size, stride, padding parameters. Input(X) and Output(Out) are
    in NCDHW format, where N is batch size, C is the number of channels,
    H is the height of the feature,  D is the depth of the feature, and W is the width of the feature.
231

W
Wei Shengyu 已提交
232 233
    Parameters:
        kernel_size(int|list|tuple): The pool kernel size. If pool kernel size
234 235 236
            is a tuple or list, it must contain three integers,
            (kernel_size_Depth, kernel_size_Height, kernel_size_Width).
            Otherwise, the pool kernel size will be the cube of an int.
W
Wei Shengyu 已提交
237
        stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list,
238 239
            it must contain three integers, [stride_Depth, stride_Height, stride_Width).
            Otherwise, the pool stride size will be a cube of an int.
W
Wei Shengyu 已提交
240 241
            Default None, then stride will be equal to the kernel_size.
        padding(str|int|list|tuple, optional): The padding size. Padding could be in one of the following forms.
242 243 244 245 246 247
            1. A string in ['valid', 'same'].
            2. An int, which means the feature map is zero padded by size of `padding` on every sides.
            3. A list[int] or tuple(int) whose length is 3, [pad_depth, pad_height, pad_weight] whose value means the padding size of each dimension.
            4. A list[int] or tuple(int) whose length is 6. [pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side.
            5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
            The default value is 0.
W
Wei Shengyu 已提交
248 249 250 251 252 253 254
        ceil_mode(bool, optional): ${ceil_mode_comment}
        exclusive(bool, optional): Whether to exclude padding points in average pooling mode, default is True.
        divisor_override(int|float, optional): if specified, it will be used as divisor, otherwise kernel_size will
            be used. Default None.
        data_format(str, optional): The data format of the input and output data. An optional string from: `"NCDHW"`,
             `"NDHWC"`. The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of:
             `[batch_size, input_channels, input_depth, input_height, input_width]`.
255
        name(str, optional): For detailed information, please refer
W
Wei Shengyu 已提交
256 257
             to :ref:`api_guide_Name`. Usually name is no need to set and
             None by default.
258

W
Wei Shengyu 已提交
259 260
    Returns:
        A callable object of AvgPool3D.
261 262

    Shape:
W
Wei Shengyu 已提交
263 264 265 266
        - x(Tensor): The input tensor of avg pool3d operator, which is a 5-D tensor.
          The data type can be float32, float64.
        - output(Tensor): The output tensor of avg pool3d  operator, which is a 5-D tensor.
          The data type is same as input x.
267 268
    Examples:
        .. code-block:: python
269

W
Wei Shengyu 已提交
270 271
            import paddle
            import paddle.nn as nn
272

W
Wei Shengyu 已提交
273
            # avg pool3d
274
            input = paddle.uniform([1, 2, 3, 32, 32], dtype="float32", min=-1, max=1)
W
Wei Shengyu 已提交
275
            AvgPool3D = nn.AvgPool3D(kernel_size=2,
276
                                   stride=2, padding=0)
W
Wei Shengyu 已提交
277 278
            output = AvgPool3D(input)
            # output.shape [1, 2, 3, 16, 16]
279

280 281
    """

L
Ligoml 已提交
282 283 284 285 286 287 288 289 290 291 292
    def __init__(
        self,
        kernel_size,
        stride=None,
        padding=0,
        ceil_mode=False,
        exclusive=True,
        divisor_override=None,
        data_format="NCDHW",
        name=None,
    ):
C
cnn 已提交
293
        super(AvgPool3D, self).__init__()
294 295 296 297
        self.ksize = kernel_size
        self.stride = stride
        self.padding = padding
        self.ceil_mode = ceil_mode
298
        self.exclusive = exclusive
299 300
        self.divisor = divisor_override
        self.data_format = data_format
301 302
        self.name = name

303
    def forward(self, x):
L
Ligoml 已提交
304 305 306 307 308 309 310 311 312 313 314
        return F.avg_pool3d(
            x,
            kernel_size=self.ksize,
            stride=self.stride,
            padding=self.padding,
            ceil_mode=self.ceil_mode,
            exclusive=self.exclusive,
            divisor_override=self.divisor,
            data_format=self.data_format,
            name=self.name,
        )
315

316 317
    def extra_repr(self):
        return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format(
L
Ligoml 已提交
318 319
            **self.__dict__
        )
320

321

Z
zhiboniu 已提交
322
class MaxPool1D(Layer):
323
    """
W
Wei Shengyu 已提交
324 325 326 327 328
    This operation applies 1D max pooling over input signal
    composed of several input planes based on the input,
    and kernel_size, stride, padding parameters. Input(X) and Output(Out) are
    in NCL format, where N is batch size, C is the number of channels,
    L is the length of the feature.
329

330 331 332
    The output value of the layer with input size (N, C, L),
    output (N, C, L_{out}) and kernel_size k can be precisely described as
    For average pool1d:
333 334 335

    ..  math::

W
Wei Shengyu 已提交
336
        Output(N_i, C_i, l) =  max(Input[N_i, C_i, stride \times l:stride \times l+k])
337

W
Wei Shengyu 已提交
338 339
    Parameters:
        kernel_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
340
            it must contain an integer.
W
Wei Shengyu 已提交
341 342 343
        stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list,
            it must contain an integer. Default None, then stride will be equal to the kernel_size.
        padding(str|int|list|tuple, optional): The padding size. Padding could be in one of the following forms.
344 345 346
            1. A string in ['valid', 'same'].
            2. An integer, which means the feature map is zero padded by size of `padding` on every sides.
            3. A list[int] or tuple(int) whose length is 1, which means the feature map is zero padded by the size of `padding[0]` on every sides.
W
Wei Shengyu 已提交
347 348
            4. A list[int] or tuple(int) whose length is 2, It has the form [pad_before, pad_after].
            5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or(0,0).
349
            The default value is 0.
W
Wei Shengyu 已提交
350 351 352 353 354
        return_mask(bool, optional): Whether return the max indices along with the outputs. default is `False`.
        ceil_mode(bool, optional): Whether to use the ceil function to calculate output height and width.
            False is the default. If it is set to False, the floor function will be used. Default False.
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
355
    Returns:
W
Wei Shengyu 已提交
356
        A callable object of MaxPool1D.
357 358

    Raises:
359 360 361 362 363 364 365 366
        ValueError: If `padding` is a string, but not "SAME" or "VALID".
        ValueError: If `padding` is "VALID", but `ceil_mode` is True.
        ValueError: If `padding` is a list or tuple but its length greater than 1.
        ShapeError: If the input is not a 3-D.
        ShapeError: If the output's shape calculated is not greater than 0.


    Shape:
W
Wei Shengyu 已提交
367 368 369 370
        - x(Tensor): The input tensor of max pool1d operator, which is a 3-D tensor.
          The data type can be float32, float64.
        - output(Tensor): The output tensor of max pool1d  operator, which is a 3-D tensor.
          The data type is same as input x.
371 372

    Examples:
373

374 375
        .. code-block:: python

W
Wei Shengyu 已提交
376 377
            import paddle
            import paddle.nn as nn
378

379
            data = paddle.uniform([1, 3, 32], dtype="float32", min=-1, max=1)
W
Wei Shengyu 已提交
380 381 382
            MaxPool1D = nn.MaxPool1D(kernel_size=2, stride=2, padding=0)
            pool_out = MaxPool1D(data)
            # pool_out shape: [1, 3, 16]
383

W
Wei Shengyu 已提交
384 385 386
            MaxPool1D = nn.MaxPool1D(kernel_size=2, stride=2, padding=0, return_mask=True)
            pool_out, indices = MaxPool1D(data)
            # pool_out shape: [1, 3, 16], indices shape: [1, 3, 16]
387 388 389

    """

L
Ligoml 已提交
390 391 392 393 394 395 396 397 398
    def __init__(
        self,
        kernel_size,
        stride=None,
        padding=0,
        return_mask=False,
        ceil_mode=False,
        name=None,
    ):
C
cnn 已提交
399
        super(MaxPool1D, self).__init__()
400 401 402 403
        self.kernel_size = kernel_size
        self.stride = stride
        self.padding = padding
        self.ceil_mode = ceil_mode
404
        self.return_mask = return_mask
405 406 407
        self.name = name

    def forward(self, input):
L
Ligoml 已提交
408 409 410 411 412 413 414 415 416
        out = F.max_pool1d(
            input,
            self.kernel_size,
            self.stride,
            self.padding,
            self.return_mask,
            self.ceil_mode,
            self.name,
        )
417
        return out
418

419 420
    def extra_repr(self):
        return 'kernel_size={kernel_size}, stride={stride}, padding={padding}'.format(
L
Ligoml 已提交
421 422
            **self.__dict__
        )
423

424

Z
zhiboniu 已提交
425
class MaxPool2D(Layer):
426
    r"""
427
    This operation applies 2D max pooling over input feature based on the input,
428 429 430 431 432
    and kernel_size, stride, padding parameters. Input(X) and Output(Out) are
    in NCHW format, where N is batch size, C is the number of channels,
    H is the height of the feature, and W is the width of the feature.

    Example:
W
Wei Shengyu 已提交
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
        - Input:
            X shape: :math:`(N, C, H_{in}, W_{in})`
        - Attr:
            kernel_size: ksize

        - Output:
            Out shape: :math:`(N, C, H_{out}, W_{out})`

        ..  math::

            Output(N_i, C_j, h, w) = \max_{m=0, \ldots, ksize[0] -1} \max_{n=0, \ldots, ksize[1]-1}
                Input(N_i, C_j, stride[0] \times h + m, stride[1] \times w + n)

    Parameters:
        kernel_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
448 449
            it must contain two integers, (pool_size_Height, pool_size_Width).
            Otherwise, the pool kernel size will be a square of an int.
W
Wei Shengyu 已提交
450
        stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list,
451
            it must contain two integers, (pool_stride_Height, pool_stride_Width).
452
            Otherwise, the pool stride size will be a square of an int.
W
Wei Shengyu 已提交
453 454
            Default None, then stride will be equal to the kernel_size.
        padding(str|int|list|tuple, optional): The padding size. Padding could be in one of the following forms.
455 456 457
            1. A string in ['valid', 'same'].
            2. An int, which means the feature map is zero padded by size of `padding` on every sides.
            3. A list[int] or tuple(int) whose length is 2, [pad_height, pad_weight] whose value means the padding size of each dimension.
W
Wei Shengyu 已提交
458
            4. A list[int] or tuple(int) whose length is \4. [pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side.
459 460
            5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
            The default value is 0.
W
Wei Shengyu 已提交
461 462 463 464 465 466 467
        ceil_mode(bool, optional): when True, will use `ceil` instead of `floor` to compute the output shape
        return_mask(bool, optional): Whether to return the max indices along with the outputs.
        data_format(str, optional): The data format of the input and output data. An optional string from: `"NCHW"`, `"NDHW"`.
            The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
            `[batch_size, input_channels, input_height, input_width]`.
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
468

W
Wei Shengyu 已提交
469 470
    Returns:
        A callable object of MaxPool2D.
471 472 473 474
    Raises:
        ValueError: If `padding` is a string, but not "SAME" or "VALID".
        ValueError: If `padding` is "VALID", but `ceil_mode` is True.
        ShapeError: If the output's shape calculated is not greater than 0.
475 476

    Shape:
W
Wei Shengyu 已提交
477 478 479 480
        - x(Tensor): The input tensor of max pool2d operator, which is a 4-D tensor.
          The data type can be float32, float64.
        - output(Tensor): The output tensor of max pool2d  operator, which is a 4-D tensor.
          The data type is same as input x.
481

482 483
    Examples:
        .. code-block:: python
484

W
Wei Shengyu 已提交
485 486
            import paddle
            import paddle.nn as nn
487

W
Wei Shengyu 已提交
488
            # max pool2d
489
            input = paddle.uniform([1, 3, 32, 32], dtype="float32", min=-1, max=1)
W
Wei Shengyu 已提交
490
            MaxPool2D = nn.MaxPool2D(kernel_size=2,
491
                                   stride=2, padding=0)
W
Wei Shengyu 已提交
492 493
            output = MaxPool2D(input)
            # output.shape [1, 3, 16, 16]
494

W
Wei Shengyu 已提交
495 496 497 498
            # for return_mask=True
            MaxPool2D = nn.MaxPool2D(kernel_size=2, stride=2, padding=0, return_mask=True)
            output, max_indices = MaxPool2D(input)
            # output.shape [1, 3, 16, 16], max_indices.shape [1, 3, 16, 16],
499 500
    """

L
Ligoml 已提交
501 502 503 504 505 506 507 508 509 510
    def __init__(
        self,
        kernel_size,
        stride=None,
        padding=0,
        return_mask=False,
        ceil_mode=False,
        data_format="NCHW",
        name=None,
    ):
C
cnn 已提交
511
        super(MaxPool2D, self).__init__()
512 513 514
        self.ksize = kernel_size
        self.stride = stride
        self.padding = padding
515
        self.return_mask = return_mask
516 517 518 519 520
        self.ceil_mode = ceil_mode
        self.data_format = data_format
        self.name = name

    def forward(self, x):
L
Ligoml 已提交
521 522 523 524 525 526 527 528 529 530
        return F.max_pool2d(
            x,
            kernel_size=self.ksize,
            stride=self.stride,
            padding=self.padding,
            return_mask=self.return_mask,
            ceil_mode=self.ceil_mode,
            data_format=self.data_format,
            name=self.name,
        )
531

532 533
    def extra_repr(self):
        return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format(
L
Ligoml 已提交
534 535
            **self.__dict__
        )
536

537

Z
zhiboniu 已提交
538
class MaxPool3D(Layer):
539
    """
540
    This operation applies 3D max pooling over input features based on the input,
541
    and kernel_size, stride, padding parameters. Input(X) and Output(Out) are
542 543
    in NCDHW format, where N is batch size, C is the number of channels,
    H is the height of the feature,  D is the depth of the feature, and W is the width of the feature.
544

W
Wei Shengyu 已提交
545 546
    Parameters:
        kernel_size(int|list|tuple): The pool kernel size. If the kernel size
547
            is a tuple or list, it must contain three integers,
548
            (kernel_size_Depth, kernel_size_Height, kernel_size_Width).
549
            Otherwise, the pool kernel size will be the cube of an int.
W
Wei Shengyu 已提交
550
        stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list,
551 552
            it must contain three integers, [stride_Depth, stride_Height, stride_Width).
            Otherwise, the pool stride size will be a cube of an int.
W
Wei Shengyu 已提交
553 554
            Default None, then stride will be equal to the kernel_size.
        padding(str|int|list|tuple, optional): The padding size. Padding could be in one of the following forms.
555 556 557
            1. A string in ['valid', 'same'].
            2. An int, which means the feature map is zero padded by size of `padding` on every sides.
            3. A list[int] or tuple(int) whose length is 3, [pad_depth, pad_height, pad_weight] whose value means the padding size of each dimension.
W
Wei Shengyu 已提交
558
            4. A list[int] or tuple(int) whose length is \6. [pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side.
559 560
            5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
            The default value is 0.
W
Wei Shengyu 已提交
561 562 563 564 565 566 567
        ceil_mode(bool, optional): ${ceil_mode_comment}
        return_mask(bool, optional): Whether to return the max indices along with the outputs.
        data_format(str, optional): The data format of the input and output data. An optional string from: `"NCDHW"`,
            `"NDHWC"`. The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of:
            `[batch_size, input_channels, input_depth, input_height, input_width]`.
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
568 569


W
Wei Shengyu 已提交
570 571
    Returns:
        A callable object of MaxPool3D.
572 573 574 575
    Raises:
        ValueError: If `padding` is a string, but not "SAME" or "VALID".
        ValueError: If `padding` is "VALID", but `ceil_mode` is True.
        ShapeError: If the output's shape calculated is not greater than 0.
576 577

    Shape:
W
Wei Shengyu 已提交
578 579 580 581
        - x(Tensor): The input tensor of max pool3d operator, which is a 5-D tensor.
          The data type can be float32, float64.
        - output(Tensor): The output tensor of max pool3d  operator, which is a 5-D tensor.
          The data type is same as input x.
582

583 584
    Examples:
        .. code-block:: python
585

W
Wei Shengyu 已提交
586 587
            import paddle
            import paddle.nn as nn
588

W
Wei Shengyu 已提交
589
            # max pool3d
590
            input = paddle.uniform([1, 2, 3, 32, 32], dtype="float32", min=-1, max=1)
W
Wei Shengyu 已提交
591
            MaxPool3D = nn.MaxPool3D(kernel_size=2,
592
                                   stride=2, padding=0)
W
Wei Shengyu 已提交
593 594
            output = MaxPool3D(input)
            # output.shape [1, 2, 3, 16, 16]
595

W
Wei Shengyu 已提交
596 597 598 599
            # for return_mask=True
            MaxPool3D = nn.MaxPool3D(kernel_size=2, stride=2, padding=0, return_mask=True)
            output, max_indices = MaxPool3D(input)
            # output.shape [1, 2, 3, 16, 16], max_indices.shape [1, 2, 3, 16, 16],
600 601
    """

L
Ligoml 已提交
602 603 604 605 606 607 608 609 610 611
    def __init__(
        self,
        kernel_size,
        stride=None,
        padding=0,
        return_mask=False,
        ceil_mode=False,
        data_format="NCDHW",
        name=None,
    ):
C
cnn 已提交
612
        super(MaxPool3D, self).__init__()
613 614 615
        self.ksize = kernel_size
        self.stride = stride
        self.padding = padding
616
        self.return_mask = return_mask
617 618 619 620 621
        self.ceil_mode = ceil_mode
        self.data_format = data_format
        self.name = name

    def forward(self, x):
L
Ligoml 已提交
622 623 624 625 626 627 628 629 630 631
        return F.max_pool3d(
            x,
            kernel_size=self.ksize,
            stride=self.stride,
            padding=self.padding,
            return_mask=self.return_mask,
            ceil_mode=self.ceil_mode,
            data_format=self.data_format,
            name=self.name,
        )
632

633 634
    def extra_repr(self):
        return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format(
L
Ligoml 已提交
635 636
            **self.__dict__
        )
637

638

Z
zhiboniu 已提交
639
class AdaptiveAvgPool1D(Layer):
640
    r"""
641

642 643 644 645 646
    A 1D adaptive average pooling over an input signal composed
    of several input planes, based on :attr:`output_size`.
    Input and output are in NCL format, where N is batch
    size, C is the number of channels and L is the length of the feature.
    The shape of output will be :math:`[N, C, output\_size]`.
647

648
    The formulation for average adaptive pool1d is
649 650 651

    ..  math::

652
        lstart &= \lfloor i * L_{in} / L_{out}\rfloor,
653

654
        lend &= \lceil(i + 1) * L_{in} / L_{out}\rceil,
655

656
        Output(i) &= \frac{\sum Input[lstart:lend]}{lend - lstart}.
657

W
Wei Shengyu 已提交
658
    Parameters:
659 660
        output_size(int): The target output size. Its data type must be int.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
661

662
    Returns:
663
        A callable object for computing 1D adaptive average pooling.
664

665 666
    Examples:
        .. code-block:: python
667

W
Wei Shengyu 已提交
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
            # average adaptive pool1d
            # suppose input data in shape of [N, C, L], `output_size` is m or [m],
            # output shape is [N, C, m], adaptive pool divide L dimension
            # of input data into m grids averagely and performs poolings in each
            # grid to get output.
            # adaptive max pool performs calculations as follow:
            #
            #     for i in range(m):
            #         lstart = floor(i * L / m)
            #         lend = ceil((i + 1) * L / m)
            #         output[:, :, i] = sum(input[:, :, lstart: lend])/(lend - lstart)
            #
            import paddle
            import paddle.nn as nn

683
            data = paddle.uniform([1, 3, 32], dtype="float32", min=-1, max=1)
W
Wei Shengyu 已提交
684 685 686
            AdaptiveAvgPool1D = nn.AdaptiveAvgPool1D(output_size=16)
            pool_out = AdaptiveAvgPool1D(data)
            # pool_out shape: [1, 3, 16]
687 688
    """

689
    def __init__(self, output_size, name=None):
C
cnn 已提交
690
        super(AdaptiveAvgPool1D, self).__init__()
691
        self.output_size = output_size
692 693
        self.name = name

694 695 696
    def forward(self, input):
        return F.adaptive_avg_pool1d(input, self.output_size, self.name)

697 698 699
    def extra_repr(self):
        return 'output_size={}'.format(self.output_size)

700

Z
zhiboniu 已提交
701
class AdaptiveAvgPool2D(Layer):
702
    r"""
703 704 705 706 707 708 709 710

    This operation applies 2D adaptive avg pooling on input tensor. The h and w dimensions
    of the output tensor are determined by the parameter output_size.

    For avg adaptive pool2d:

    ..  math::

W
Wei Shengyu 已提交
711
        hstart &= floor(i * H_{in} / H_{out})
712

W
Wei Shengyu 已提交
713
        hend &= ceil((i + 1) * H_{in} / H_{out})
714

W
Wei Shengyu 已提交
715
        wstart &= floor(j * W_{in} / W_{out})
716

W
Wei Shengyu 已提交
717
        wend &= ceil((j + 1) * W_{in} / W_{out})
718

W
Wei Shengyu 已提交
719
        Output(i ,j) &= \frac{\sum Input[hstart:hend, wstart:wend]}{(hend - hstart) * (wend - wstart)}
720 721 722


    Parameters:
W
Wei Shengyu 已提交
723
        output_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
724 725
            it must contain two element, (H, W). H and W can be either a int, or None which means
            the size will be the same as that of the input.
W
Wei Shengyu 已提交
726
        data_format(str, optional): The data format of the input and output data. An optional string
727 728
            from: "NCHW", "NHWC". The default is "NCHW". When it is "NCHW", the data is stored in
            the order of: [batch_size, input_channels, input_height, input_width].
W
Wei Shengyu 已提交
729 730
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
731 732

    Shape:
W
Wei Shengyu 已提交
733 734 735 736
        - x(Tensor): The input tensor of adaptive avg pool2d operator, which is a 4-D tensor.
          The data type can be float32, float64.
        - output(Tensor): The output tensor of adaptive avg pool2d operator, which is a 4-D tensor.
          The data type is same as input x.
737 738

    Returns:
C
cnn 已提交
739
        A callable object of AdaptiveAvgPool2D.
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759

    Examples:
        .. code-block:: python

            # adaptive avg pool2d
            # suppose input data in shape of [N, C, H, W], `output_size` is [m, n],
            # output shape is [N, C, m, n], adaptive pool divide H and W dimensions
            # of input data into m * n grids averagely and performs poolings in each
            # grid to get output.
            # adaptive avg pool performs calculations as follow:
            #
            #     for i in range(m):
            #         for j in range(n):
            #             hstart = floor(i * H / m)
            #             hend = ceil((i + 1) * H / m)
            #             wstart = floor(i * W / n)
            #             wend = ceil((i + 1) * W / n)
            #             output[:, :, i, j] = avg(input[:, :, hstart: hend, wstart: wend])
            #
            import paddle
760

761 762
            x = paddle.rand([2, 3, 32, 32])

C
cnn 已提交
763
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool2D(output_size=3)
764 765 766 767 768
            pool_out = adaptive_avg_pool(x = x)
            # pool_out.shape is [2, 3, 3, 3]
    """

    def __init__(self, output_size, data_format="NCHW", name=None):
C
cnn 已提交
769
        super(AdaptiveAvgPool2D, self).__init__()
770 771 772 773 774
        self._output_size = output_size
        self._data_format = data_format
        self._name = name

    def forward(self, x):
L
Ligoml 已提交
775 776 777 778 779 780
        return F.adaptive_avg_pool2d(
            x,
            output_size=self._output_size,
            data_format=self._data_format,
            name=self._name,
        )
781

782 783 784
    def extra_repr(self):
        return 'output_size={}'.format(self._output_size)

785

Z
zhiboniu 已提交
786
class AdaptiveAvgPool3D(Layer):
787
    r"""
788 789 790 791 792 793 794 795

    This operation applies 3D adaptive avg pooling on input tensor. The h and w dimensions
    of the output tensor are determined by the parameter output_size.

    For avg adaptive pool3d:

    ..  math::

W
Wei Shengyu 已提交
796
        dstart &= floor(i * D_{in} / D_{out})
797

W
Wei Shengyu 已提交
798
        dend &= ceil((i + 1) * D_{in} / D_{out})
799

W
Wei Shengyu 已提交
800
        hstart &= floor(j * H_{in} / H_{out})
801

W
Wei Shengyu 已提交
802
        hend &= ceil((j + 1) * H_{in} / H_{out})
803

W
Wei Shengyu 已提交
804
        wstart &= floor(k * W_{in} / W_{out})
805

W
Wei Shengyu 已提交
806
        wend &= ceil((k + 1) * W_{in} / W_{out})
807

W
Wei Shengyu 已提交
808 809
        Output(i ,j, k) &= \frac{\sum Input[dstart:dend, hstart:hend, wstart:wend]}
            {(dend - dstart) * (hend - hstart) * (wend - wstart)}
810 811 812


    Parameters:
W
Wei Shengyu 已提交
813
        output_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
814 815
            it must contain three elements, (D, H, W). D, H and W can be either a int, or None which means
            the size will be the same as that of the input.
W
Wei Shengyu 已提交
816
        data_format(str, optional): The data format of the input and output data. An optional string
817 818
            from: "NCDHW", "NDHWC". The default is "NCDHW". When it is "NCDHW", the data is stored in
            the order of: [batch_size, input_channels, input_depth, input_height, input_width].
W
Wei Shengyu 已提交
819 820
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
821
    Shape:
W
Wei Shengyu 已提交
822 823 824 825
        - x(Tensor): The input tensor of adaptive avg pool3d operator, which is a 5-D tensor.
          The data type can be float32, float64\.
        - output(Tensor): The output tensor of adaptive avg pool3d operator, which is a 5-D tensor.
          The data type is same as input x.
826 827

    Returns:
C
cnn 已提交
828
        A callable object of AdaptiveAvgPool3D.
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851

    Examples:
        .. code-block:: python

            # adaptive avg pool3d
            # suppose input data in shape of [N, C, D, H, W], `output_size` is [l, m, n],
            # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions
            # of input data into l * m * n grids averagely and performs poolings in each
            # grid to get output.
            # adaptive avg pool performs calculations as follow:
            #
            #     for i in range(l):
            #         for j in range(m):
            #             for k in range(n):
            #                 dstart = floor(i * D / l)
            #                 dend = ceil((i + 1) * D / l)
            #                 hstart = floor(j * H / m)
            #                 hend = ceil((j + 1) * H / m)
            #                 wstart = floor(k * W / n)
            #                 wend = ceil((k + 1) * W / n)
            #                 output[:, :, i, j, k] =
            #                     avg(input[:, :, dstart:dend, hstart: hend, wstart: wend])
            import paddle
852

853 854
            x = paddle.rand([2, 3, 8, 32, 32])

C
cnn 已提交
855
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool3D(output_size=3)
856 857 858 859 860
            pool_out = adaptive_avg_pool(x = x)
            # pool_out = [2, 3, 3, 3, 3]
    """

    def __init__(self, output_size, data_format="NCDHW", name=None):
C
cnn 已提交
861
        super(AdaptiveAvgPool3D, self).__init__()
862 863 864 865 866
        self._output_size = output_size
        self._data_format = data_format
        self._name = name

    def forward(self, x):
L
Ligoml 已提交
867 868 869 870 871 872
        return F.adaptive_avg_pool3d(
            x,
            output_size=self._output_size,
            data_format=self._data_format,
            name=self._name,
        )
873

874 875 876
    def extra_repr(self):
        return 'output_size={}'.format(self._output_size)

877

Z
zhiboniu 已提交
878
class AdaptiveMaxPool1D(Layer):
879 880 881
    """

    This operation applies a 1D adaptive max pooling over an input signal composed
882
    of several input planes, based on the input, output_size, return_mask parameters.
883 884 885 886 887 888 889 890
    Input(X) and output(Out) are in NCL format, where N is batch
    size, C is the number of channels, L is the length of the feature.
    The output tensor shape will be [N, C, output_size].

    For max adaptive pool1d:

    ..  math::

W
Wei Shengyu 已提交
891
        lstart &= floor(i * L_{in} / L_{out})
892

W
Wei Shengyu 已提交
893
        lend &= ceil((i + 1) * L_{in} / L_{out})
894

W
Wei Shengyu 已提交
895
        Output(i) &= max(Input[lstart:lend])
896

W
Wei Shengyu 已提交
897 898 899 900
    Parameters:
        output_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
            it must contain one int.
        return_mask(bool, optional): If true, the index of max pooling point will be returned along
901
            with outputs. It cannot be set in average pooling type. Default False.
W
Wei Shengyu 已提交
902 903
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
904
    Returns:
W
Wei Shengyu 已提交
905
        A callable object of AdaptiveMaxPool1D.
906 907 908 909 910

    Raises:
        ValueError: 'pool_size' should be a integer or list or tuple with length as 1.

    Shape:
W
Wei Shengyu 已提交
911 912 913 914
        - x(Tensor): The input tensor of adaptive max pool1d operator, which is a 3-D tensor.
          The data type can be float32, float64.
        - output(Tensor): The output tensor of adaptive max pool1d operator, which is a 3-D tensor.
          The data type is same as input x.
915 916 917 918

    Examples:
        .. code-block:: python

W
Wei Shengyu 已提交
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
            # max adaptive pool1d
            # suppose input data in shape of [N, C, L], `output_size` is m or [m],
            # output shape is [N, C, m], adaptive pool divide L dimension
            # of input data into m grids averagely and performs poolings in each
            # grid to get output.
            # adaptive max pool performs calculations as follow:
            #
            #     for i in range(m):
            #         lstart = floor(i * L / m)
            #         lend = ceil((i + 1) * L / m)
            #         output[:, :, i] = max(input[:, :, lstart: lend])
            #
            import paddle
            import paddle.nn as nn

934
            data = paddle.uniform([1, 3, 32], dtype="float32", min=-1, max=1)
W
Wei Shengyu 已提交
935 936 937 938 939 940 941 942
            AdaptiveMaxPool1D = nn.AdaptiveMaxPool1D(output_size=16)
            pool_out = AdaptiveMaxPool1D(data)
            # pool_out shape: [1, 3, 16]

            # for return_mask = true
            AdaptiveMaxPool1D = nn.AdaptiveMaxPool1D(output_size=16, return_mask=True)
            pool_out, indices = AdaptiveMaxPool1D(data)
            # pool_out shape: [1, 3, 16], indices shape: [1, 3, 16]
943 944 945

    """

946
    def __init__(self, output_size, return_mask=False, name=None):
C
cnn 已提交
947
        super(AdaptiveMaxPool1D, self).__init__()
948
        self.output_size = output_size
949
        self.return_mask = return_mask
950 951 952
        self.name = name

    def forward(self, input):
L
Ligoml 已提交
953 954 955
        return F.adaptive_max_pool1d(
            input, self.output_size, self.return_mask, self.name
        )
956

957
    def extra_repr(self):
L
Ligoml 已提交
958 959 960
        return 'output_size={}, return_mask={}'.format(
            self.output_size, self.return_mask
        )
961

962

Z
zhiboniu 已提交
963
class AdaptiveMaxPool2D(Layer):
964 965
    """
    This operation applies 2D adaptive max pooling on input tensor. The h and w dimensions
W
Wei Shengyu 已提交
966 967
    of the output tensor are determined by the parameter output_size. The difference between adaptive pooling and
    pooling is adaptive one focus on the output size.
968

969
    For adaptive max pool2d:
970

971
    ..  math::
972

W
Wei Shengyu 已提交
973
        hstart &= floor(i * H_{in} / H_{out})
974

W
Wei Shengyu 已提交
975
        hend &= ceil((i + 1) * H_{in} / H_{out})
976

W
Wei Shengyu 已提交
977
        wstart &= floor(j * W_{in} / W_{out})
978

W
Wei Shengyu 已提交
979
        wend &= ceil((j + 1) * W_{in} / W_{out})
980

W
Wei Shengyu 已提交
981
        Output(i ,j) &= max(Input[hstart:hend, wstart:wend])
982

983
    Parameters:
W
Wei Shengyu 已提交
984 985 986 987 988 989 990
        output_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain
            two element, (H, W). H and W can be either a int, or None which means the size will be the same as that of
            the input.
        return_mask(bool, optional): If true, the index of max pooling point will be returned along with outputs.
            It cannot be set in average pooling type. Default False.
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
991
    Shape:
W
Wei Shengyu 已提交
992 993 994 995
        - x(Tensor): The input tensor of adaptive max pool2d operator, which is a 4-D tensor.
          The data type can be float32, float64.
        - output(Tensor): The output tensor of adaptive max pool2d operator, which is a 4-D tensor.
          The data type is same as input x.
D
Double_V 已提交
996

997
    Returns:
C
cnn 已提交
998
        A callable object of AdaptiveMaxPool2D.
999 1000
    Examples:
        .. code-block:: python
1001

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
            # adaptive max pool2d
            # suppose input data in shape of [N, C, H, W], `output_size` is [m, n],
            # output shape is [N, C, m, n], adaptive pool divide H and W dimensions
            # of input data into m * n grids averagely and performs poolings in each
            # grid to get output.
            # adaptive max pool performs calculations as follow:
            #
            #     for i in range(m):
            #         for j in range(n):
            #             hstart = floor(i * H / m)
            #             hend = ceil((i + 1) * H / m)
            #             wstart = floor(i * W / n)
            #             wend = ceil((i + 1) * W / n)
            #             output[:, :, i, j] = max(input[:, :, hstart: hend, wstart: wend])
            #
            import paddle
1018

1019 1020
            x = paddle.rand([2, 3, 32, 32])

1021
            adaptive_max_pool = paddle.nn.AdaptiveMaxPool2D(output_size=3, return_mask=True)
1022 1023 1024
            pool_out, indices = adaptive_max_pool(x = x)
    """

1025
    def __init__(self, output_size, return_mask=False, name=None):
C
cnn 已提交
1026
        super(AdaptiveMaxPool2D, self).__init__()
1027
        self._output_size = output_size
1028
        self._return_mask = return_mask
1029 1030 1031
        self._name = name

    def forward(self, x):
L
Ligoml 已提交
1032 1033 1034 1035 1036 1037
        return F.adaptive_max_pool2d(
            x,
            output_size=self._output_size,
            return_mask=self._return_mask,
            name=self._name,
        )
1038

1039
    def extra_repr(self):
L
Ligoml 已提交
1040 1041 1042
        return 'output_size={}, return_mask={}'.format(
            self._output_size, self._return_mask
        )
1043

1044

Z
zhiboniu 已提交
1045
class AdaptiveMaxPool3D(Layer):
1046
    """
W
Wei Shengyu 已提交
1047 1048 1049
    This operation applies 3D adaptive max pooling on input tensor. The h and w dimensions of the output tensor are
    determined by the parameter output_size. The difference between adaptive pooling and pooling is adaptive one focus
    on the output size.
1050

1051
    For adaptive max pool3d:
1052

1053
    ..  math::
1054

W
Wei Shengyu 已提交
1055
        dstart &= floor(i * D_{in} / D_{out})
1056

W
Wei Shengyu 已提交
1057
        dend &= ceil((i + 1) * D_{in} / D_{out})
1058

W
Wei Shengyu 已提交
1059
        hstart &= floor(j * H_{in} / H_{out})
1060

W
Wei Shengyu 已提交
1061
        hend &= ceil((j + 1) * H_{in} / H_{out})
1062

W
Wei Shengyu 已提交
1063
        wstart &= floor(k * W_{in} / W_{out})
1064

W
Wei Shengyu 已提交
1065
        wend &= ceil((k + 1) * W_{in} / W_{out})
1066

W
Wei Shengyu 已提交
1067
        Output(i ,j, k) &= max(Input[dstart:dend, hstart:hend, wstart:wend])
1068

1069
    Parameters:
W
Wei Shengyu 已提交
1070 1071 1072 1073 1074 1075 1076
        output_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain
            three elements, (D, H, W). D, H and W can be either a int, or None which means the size will be the same as
            that of the input.
        return_mask(bool, optional): If true, the index of max pooling point will be returned along with outputs.
            Default False.
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
1077
    Shape:
W
Wei Shengyu 已提交
1078 1079 1080 1081 1082
        - x(Tensor): The input tensor of adaptive max pool3d operator, which is a 5-D tensor.
          The data type can be float32, float64.
        - output(Tensor): The output tensor of adaptive max pool3d operator, which is a 5-D tensor.
          The data type is same as input x.

1083
    Returns:
C
cnn 已提交
1084
        A callable object of AdaptiveMaxPool3D.
1085 1086
    Examples:
        .. code-block:: python
1087

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
            # adaptive max pool3d
            # suppose input data in shape of [N, C, D, H, W], `output_size` is [l, m, n],
            # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions
            # of input data into l * m * n grids averagely and performs poolings in each
            # grid to get output.
            # adaptive max pool performs calculations as follow:
            #
            #     for i in range(l):
            #         for j in range(m):
            #             for k in range(n):
            #                 dstart = floor(i * D / l)
            #                 dend = ceil((i + 1) * D / l)
            #                 hstart = floor(j * H / m)
            #                 hend = ceil((j + 1) * H / m)
            #                 wstart = floor(k * W / n)
            #                 wend = ceil((k + 1) * W / n)
            #                 output[:, :, i, j, k] =
            #                     max(input[:, :, dstart:dend, hstart: hend, wstart: wend])
            import paddle
1107

1108
            x = paddle.rand([2, 3, 8, 32, 32])
C
cnn 已提交
1109
            pool = paddle.nn.AdaptiveMaxPool3D(output_size=4)
1110 1111
            out = pool(x)
            # out shape: [2, 3, 4, 4, 4]
1112
            pool = paddle.nn.AdaptiveMaxPool3D(output_size=3, return_mask=True)
1113
            out, indices = pool(x)
1114
            # out shape: [2, 3, 4, 4, 4], indices shape: [2, 3, 4, 4, 4]
D
Double_V 已提交
1115

1116 1117
    """

1118
    def __init__(self, output_size, return_mask=False, name=None):
C
cnn 已提交
1119
        super(AdaptiveMaxPool3D, self).__init__()
1120
        self._output_size = output_size
1121
        self._return_mask = return_mask
1122 1123 1124
        self._name = name

    def forward(self, x):
L
Ligoml 已提交
1125 1126 1127 1128 1129 1130
        return F.adaptive_max_pool3d(
            x,
            output_size=self._output_size,
            return_mask=self._return_mask,
            name=self._name,
        )
1131 1132

    def extra_repr(self):
L
Ligoml 已提交
1133 1134 1135
        return 'output_size={}, return_mask={}'.format(
            self._output_size, self._return_mask
        )
1136 1137


1138
class MaxUnPool1D(Layer):
1139
    r"""
1140 1141
    This API implements max unpooling 1d opereation.

L
Ligoml 已提交
1142 1143
    `max_unpool1d` accepts the output of `max_pool1d` as input,
    including the indices of the maximum value and calculate the partial inverse.
1144 1145 1146 1147
    All non-maximum values ​​are set to zero.

    - Input: :math:`(N, C, L_{in})`
    - Output: :math:`(N, C, L_{out})`, where
L
Ligoml 已提交
1148

1149 1150 1151 1152
    .. math::
        L_{out} = (L_{in} - 1) * stride - 2 * padding + kernel\_size

    or as given by :attr:`output_size` in the call operator.
L
Ligoml 已提交
1153

1154 1155 1156 1157 1158 1159
    Parameters:
        kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list,
            it must contain an integer.
        stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list,
            it must contain an integer.
        padding (int | tuple): Padding that was added to the input.
L
Ligoml 已提交
1160
        output_size(list|tuple, optional): The target output size. If output_size is not specified,
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
                           the actual output shape will be automatically calculated by (input_shape,
                           kernel_size, stride, padding).
        data_format (string): The data format of the input and output data.
                        The default is `"NCL"`. When it is `"NCL"`, the data is stored in the order of:
                        `[batch_size, input_channels, input_length]`.
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.


    Returns:
        A callable object of MaxUnPool1D.

    Examples:
        .. code-block:: python
L
Ligoml 已提交
1176

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
            import paddle
            import paddle.nn.functional as F

            data = paddle.rand(shape=[1, 3, 16])
            pool_out, indices = F.max_pool1d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
            # pool_out shape: [1, 3, 8],  indices shape: [1, 3, 8]
            Unpool1D = paddle.nn.MaxUnPool1D(kernel_size=2, padding=0)
            unpool_out = Unpool1D(pool_out, indices)
            # unpool_out shape: [1, 3, 16]

    """

L
Ligoml 已提交
1189 1190 1191 1192 1193 1194 1195 1196 1197
    def __init__(
        self,
        kernel_size,
        stride=None,
        padding=0,
        data_format="NCL",
        output_size=None,
        name=None,
    ):
1198 1199 1200 1201 1202 1203 1204 1205 1206
        super(MaxUnPool1D, self).__init__()
        self.ksize = kernel_size
        self.stride = stride
        self.padding = padding
        self.data_format = data_format
        self.output_size = output_size
        self.name = name

    def forward(self, x, indices):
L
Ligoml 已提交
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
        return F.max_unpool1d(
            x,
            indices,
            kernel_size=self.ksize,
            stride=self.stride,
            padding=self.padding,
            data_format=self.data_format,
            output_size=self.output_size,
            name=self.name,
        )
1217 1218 1219 1220 1221

    def extra_repr(self):
        return 'output_size={}'.format(self.output_size)


1222
class MaxUnPool2D(Layer):
1223
    r"""
1224 1225
    This API implements max unpooling 2d opereation.

1226 1227 1228
    'max_unpool2d' accepts the output of 'max_unpool2d' as input
    Including the indices of the maximum value and calculating the partial inverse
    All non-maximum values ​​are set to zero.
L
Ligoml 已提交
1229

1230 1231 1232 1233 1234 1235 1236 1237

    Parameters:
        kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list,
            it must contain an integer.
        stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list,
            it must contain an integer.
        kernel_size (int|tuple): Size of the max unpooling window.
        padding (int | tuple): Padding that was added to the input.
L
Ligoml 已提交
1238
        output_size(list|tuple, optional): The target output size. If output_size is not specified,
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
                           the actual output shape will be automatically calculated by (input_shape,
                           kernel_size, padding).
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.


        - Input: :math:`(N, C, H_{in}, W_{in})`
        - Output: :math:`(N, C, H_{out}, W_{out})`, where

          .. math::
            H_{out} = (H_{in} - 1) \times \text{stride[0]} - 2 \times \text{padding[0]} + \text{kernel\_size[0]}

          .. math::
            W_{out} = (W_{in} - 1) \times \text{stride[1]} - 2 \times \text{padding[1]} + \text{kernel\_size[1]}

          or as given by :attr:`output_size` in the call operator

    Returns:
        A callable object of MaxUnPool2D.

L
Ligoml 已提交
1260

1261 1262 1263

    Examples:
        .. code-block:: python
L
Ligoml 已提交
1264

1265 1266 1267
        import paddle
        import paddle.nn.functional as F

X
xiaoting 已提交
1268
        data = paddle.rand(shape=[1,1,6,6])
1269 1270 1271
        pool_out, indices = F.max_pool2d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
        # pool_out shape: [1, 1, 3, 3],  indices shape: [1, 1, 3, 3]
        Unpool2D = paddle.nn.MaxUnPool2D(kernel_size=2, padding=0)
X
xiaoting 已提交
1272
        unpool_out = Unpool2D(pool_out, indices)
1273 1274 1275 1276
        # unpool_out shape: [1, 1, 6, 6]

    """

L
Ligoml 已提交
1277 1278 1279 1280 1281 1282 1283 1284 1285
    def __init__(
        self,
        kernel_size,
        stride=None,
        padding=0,
        data_format="NCHW",
        output_size=None,
        name=None,
    ):
1286 1287 1288 1289 1290 1291 1292 1293 1294
        super(MaxUnPool2D, self).__init__()
        self.ksize = kernel_size
        self.stride = stride
        self.padding = padding
        self.data_format = data_format
        self.output_size = output_size
        self.name = name

    def forward(self, x, indices):
L
Ligoml 已提交
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
        return F.max_unpool2d(
            x,
            indices,
            kernel_size=self.ksize,
            stride=self.stride,
            padding=self.padding,
            data_format=self.data_format,
            output_size=self.output_size,
            name=self.name,
        )
1305 1306 1307

    def extra_repr(self):
        return 'output_size={}'.format(self.output_size)
1308 1309 1310


class MaxUnPool3D(Layer):
1311
    r"""
1312 1313
    This API implements max unpooling 3d opereation.

L
Ligoml 已提交
1314 1315
    `max_unpool3d` accepts the output of `max_pool3d` as input,
    including the indices of the maximum value and calculate the partial inverse.
1316 1317 1318 1319
    All non-maximum values ​​are set to zero.

    - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})`
    - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})`, where
L
Ligoml 已提交
1320

1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
    .. math::
        D_{out} = (D_{in} - 1) * stride[0] - 2 * padding[0] + kernel\_size[0]

    .. math::
        H_{out} = (H_{in} - 1) * stride[1] - 2 * padding[1] + kernel\_size[1]

    .. math::
        W_{out} = (W_{in} - 1) * stride[2] - 2 * padding[2] + kernel\_size[2]

    or as given by :attr:`output_size` in the call operator

L
Ligoml 已提交
1332

1333 1334 1335 1336 1337 1338
    Parameters:
        kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list,
            it must contain an integer.
        stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list,
            it must contain an integer.
        padding (int | tuple): Padding that was added to the input.
L
Ligoml 已提交
1339
        output_size(list|tuple, optional): The target output size. If output_size is not specified,
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
                           the actual output shape will be automatically calculated by (input_shape,
                           kernel_size, stride, padding).
        data_format (string): The data format of the input and output data.
                        The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of:
                        `[batch_size, input_channels, input_depth, input_height, input_width]`.
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.


    Returns:
        A callable object of MaxUnPool3D.

    Examples:
        .. code-block:: python
L
Ligoml 已提交
1355

1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
            import paddle
            import paddle.nn.functional as F

            data = paddle.rand(shape=[1, 1, 4, 4, 6])
            pool_out, indices = F.max_pool3d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
            # pool_out shape: [1, 1, 2, 2, 3],  indices shape: [1, 1, 2, 2, 3]
            Unpool3D = paddle.nn.MaxUnPool3D(kernel_size=2, padding=0)
            unpool_out = Unpool3D(pool_out, indices)
            # unpool_out shape: [1, 1, 4, 4, 6]

    """

L
Ligoml 已提交
1368 1369 1370 1371 1372 1373 1374 1375 1376
    def __init__(
        self,
        kernel_size,
        stride=None,
        padding=0,
        data_format="NCDHW",
        output_size=None,
        name=None,
    ):
1377 1378 1379 1380 1381 1382 1383 1384 1385
        super(MaxUnPool3D, self).__init__()
        self.ksize = kernel_size
        self.stride = stride
        self.padding = padding
        self.data_format = data_format
        self.output_size = output_size
        self.name = name

    def forward(self, x, indices):
L
Ligoml 已提交
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
        return F.max_unpool3d(
            x,
            indices,
            kernel_size=self.ksize,
            stride=self.stride,
            padding=self.padding,
            data_format=self.data_format,
            output_size=self.output_size,
            name=self.name,
        )
1396 1397 1398

    def extra_repr(self):
        return 'output_size={}'.format(self.output_size)