pooling.py 56.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   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 .. import functional as F
Z
zhiboniu 已提交
16
from .. import Layer
17

18 19
__all__ = []

20

Z
zhiboniu 已提交
21
class AvgPool1D(Layer):
W
Wei Shengyu 已提交
22
    r"""
23
    This operation applies a 1D average pooling over an input signal composed
24
    of several input planes, based on the input, output_size, return_mask parameters.
25 26 27 28 29
    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 已提交
30
    output (N, C, :math:`L_{out}`) and kernel_size ksize can be precisely described as
31 32 33 34
    For average pool1d:

    ..  math::

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

W
Wei Shengyu 已提交
37 38
    Parameters:
        kernel_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
39
            it must contain an integer.
W
Wei Shengyu 已提交
40 41 42
        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.
43 44 45 46 47 48
            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 已提交
49 50 51 52 53
        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.
54

55
    Shape:
W
Wei Shengyu 已提交
56 57 58 59
        - 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.
60

61 62
    Returns:
        A callable object of AvgPool1D.
63

64 65 66
    Examples:

        .. code-block:: python
67

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

W
Wei Shengyu 已提交
72 73 74 75
            data = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32]).astype(np.float32))
            AvgPool1D = nn.AvgPool1D(kernel_size=2, stride=2, padding=0)
            pool_out = AvgPool1D(data)
            # pool_out shape: [1, 3, 16]
76 77 78 79 80 81 82

    """

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

    def forward(self, x):
        out = F.avg_pool1d(x, self.kernel_size, self.stride, self.padding,
96
                           self.exclusive, self.ceil_mode, self.name)
97 98
        return out

99 100 101 102
    def extra_repr(self):
        return 'kernel_size={kernel_size}, stride={stride}, padding={padding}'.format(
            **self.__dict__)

103

Z
zhiboniu 已提交
104
class AvgPool2D(Layer):
105
    r"""
106 107 108 109
    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.
110

111
    Example:
W
Wei Shengyu 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
        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,
127 128
            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 已提交
129
        stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list,
130 131
            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 已提交
132 133
            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.
134 135 136 137 138 139
            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 已提交
140 141 142 143 144 145 146 147 148 149
        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.
150

151
    Shape:
W
Wei Shengyu 已提交
152 153 154 155
        - 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.
156

W
Wei Shengyu 已提交
157 158
    Returns:
        A callable object of AvgPool2D.
159

160 161
    Examples:
        .. code-block:: python
162

W
Wei Shengyu 已提交
163 164 165
            import paddle
            import paddle.nn as nn
            import numpy as np
166

W
Wei Shengyu 已提交
167 168 169
            # max pool2d
            input = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32, 32]).astype(np.float32))
            AvgPool2D = nn.AvgPool2D(kernel_size=2,
170
                                stride=2, padding=0)
W
Wei Shengyu 已提交
171 172
            output = AvgPool2D(input)
            # output.shape [1, 3, 16, 16]
173 174 175 176 177 178 179 180

    """

    def __init__(self,
                 kernel_size,
                 stride=None,
                 padding=0,
                 ceil_mode=False,
181
                 exclusive=True,
182 183
                 divisor_override=None,
                 data_format="NCHW",
184
                 name=None):
C
cnn 已提交
185
        super(AvgPool2D, self).__init__()
186
        self.ksize = kernel_size
187 188 189
        self.stride = stride
        self.padding = padding
        self.ceil_mode = ceil_mode
190
        self.exclusive = exclusive
191 192
        self.divisor = divisor_override
        self.data_format = data_format
193 194
        self.name = name

195
    def forward(self, x):
196 197 198 199 200 201 202 203 204
        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)
205

206 207 208 209
    def extra_repr(self):
        return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format(
            **self.__dict__)

210

Z
zhiboniu 已提交
211
class AvgPool3D(Layer):
212
    """
213 214 215 216
    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.
217

W
Wei Shengyu 已提交
218 219
    Parameters:
        kernel_size(int|list|tuple): The pool kernel size. If pool kernel size
220 221 222
            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 已提交
223
        stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list,
224 225
            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 已提交
226 227
            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.
228 229 230 231 232 233
            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 已提交
234 235 236 237 238 239 240
        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]`.
241
        name(str, optional): For detailed information, please refer
W
Wei Shengyu 已提交
242 243
             to :ref:`api_guide_Name`. Usually name is no need to set and
             None by default.
244

W
Wei Shengyu 已提交
245 246
    Returns:
        A callable object of AvgPool3D.
247 248

    Shape:
W
Wei Shengyu 已提交
249 250 251 252
        - 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.
253 254
    Examples:
        .. code-block:: python
255

W
Wei Shengyu 已提交
256 257 258
            import paddle
            import paddle.nn as nn
            import numpy as np
259

W
Wei Shengyu 已提交
260 261 262
            # avg pool3d
            input = paddle.to_tensor(np.random.uniform(-1, 1, [1, 2, 3, 32, 32]).astype(np.float32))
            AvgPool3D = nn.AvgPool3D(kernel_size=2,
263
                                   stride=2, padding=0)
W
Wei Shengyu 已提交
264 265
            output = AvgPool3D(input)
            # output.shape [1, 2, 3, 16, 16]
266

267 268
    """

269 270
    def __init__(self,
                 kernel_size,
W
Wei Shengyu 已提交
271
                 stride=None,
272 273
                 padding=0,
                 ceil_mode=False,
274
                 exclusive=True,
275 276 277
                 divisor_override=None,
                 data_format="NCDHW",
                 name=None):
C
cnn 已提交
278
        super(AvgPool3D, self).__init__()
279 280 281 282
        self.ksize = kernel_size
        self.stride = stride
        self.padding = padding
        self.ceil_mode = ceil_mode
283
        self.exclusive = exclusive
284 285
        self.divisor = divisor_override
        self.data_format = data_format
286 287
        self.name = name

288
    def forward(self, x):
289 290 291 292 293 294 295 296 297
        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)
298

299 300 301 302
    def extra_repr(self):
        return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format(
            **self.__dict__)

303

Z
zhiboniu 已提交
304
class MaxPool1D(Layer):
305
    """
W
Wei Shengyu 已提交
306 307 308 309 310
    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.
311

312 313 314
    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:
315 316 317

    ..  math::

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

W
Wei Shengyu 已提交
320 321
    Parameters:
        kernel_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
322
            it must contain an integer.
W
Wei Shengyu 已提交
323 324 325
        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.
326 327 328
            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 已提交
329 330
            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).
331
            The default value is 0.
W
Wei Shengyu 已提交
332 333 334 335 336
        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.
337
    Returns:
W
Wei Shengyu 已提交
338
        A callable object of MaxPool1D.
339

340
    Shape:
W
Wei Shengyu 已提交
341 342 343 344
        - 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.
345 346

    Examples:
347

348 349
        .. code-block:: python

W
Wei Shengyu 已提交
350 351 352
            import paddle
            import paddle.nn as nn
            import numpy as np
353

W
Wei Shengyu 已提交
354 355 356 357
            data = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32]).astype(np.float32))
            MaxPool1D = nn.MaxPool1D(kernel_size=2, stride=2, padding=0)
            pool_out = MaxPool1D(data)
            # pool_out shape: [1, 3, 16]
358

W
Wei Shengyu 已提交
359 360 361
            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]
362 363 364

    """

365 366 367 368
    def __init__(self,
                 kernel_size,
                 stride=None,
                 padding=0,
369
                 return_mask=False,
370 371
                 ceil_mode=False,
                 name=None):
C
cnn 已提交
372
        super(MaxPool1D, self).__init__()
373 374 375 376
        self.kernel_size = kernel_size
        self.stride = stride
        self.padding = padding
        self.ceil_mode = ceil_mode
377
        self.return_mask = return_mask
378 379 380
        self.name = name

    def forward(self, input):
381
        out = F.max_pool1d(input, self.kernel_size, self.stride, self.padding,
382
                           self.return_mask, self.ceil_mode, self.name)
383
        return out
384

385 386 387 388
    def extra_repr(self):
        return 'kernel_size={kernel_size}, stride={stride}, padding={padding}'.format(
            **self.__dict__)

389

Z
zhiboniu 已提交
390
class MaxPool2D(Layer):
391
    r"""
392
    This operation applies 2D max pooling over input feature based on the input,
393 394 395 396 397
    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 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
        - 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,
413 414
            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 已提交
415
        stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list,
416
            it must contain two integers, (pool_stride_Height, pool_stride_Width).
417
            Otherwise, the pool stride size will be a square of an int.
W
Wei Shengyu 已提交
418 419
            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.
420 421 422
            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 已提交
423
            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.
424 425
            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 已提交
426 427 428 429 430 431 432
        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.
433

W
Wei Shengyu 已提交
434 435
    Returns:
        A callable object of MaxPool2D.
436 437

    Shape:
W
Wei Shengyu 已提交
438 439 440 441
        - 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.
442

443 444
    Examples:
        .. code-block:: python
445

W
Wei Shengyu 已提交
446 447 448
            import paddle
            import paddle.nn as nn
            import numpy as np
449

W
Wei Shengyu 已提交
450 451 452
            # max pool2d
            input = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32, 32]).astype(np.float32))
            MaxPool2D = nn.MaxPool2D(kernel_size=2,
453
                                   stride=2, padding=0)
W
Wei Shengyu 已提交
454 455
            output = MaxPool2D(input)
            # output.shape [1, 3, 16, 16]
456

W
Wei Shengyu 已提交
457 458 459 460
            # 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],
461 462 463 464 465 466
    """

    def __init__(self,
                 kernel_size,
                 stride=None,
                 padding=0,
467
                 return_mask=False,
468 469 470
                 ceil_mode=False,
                 data_format="NCHW",
                 name=None):
C
cnn 已提交
471
        super(MaxPool2D, self).__init__()
472 473 474
        self.ksize = kernel_size
        self.stride = stride
        self.padding = padding
475
        self.return_mask = return_mask
476 477 478 479 480
        self.ceil_mode = ceil_mode
        self.data_format = data_format
        self.name = name

    def forward(self, x):
481 482 483 484 485 486 487 488
        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)
489

490 491 492 493
    def extra_repr(self):
        return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format(
            **self.__dict__)

494

Z
zhiboniu 已提交
495
class MaxPool3D(Layer):
496
    """
497
    This operation applies 3D max pooling over input features based on the input,
498
    and kernel_size, stride, padding parameters. Input(X) and Output(Out) are
499 500
    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.
501

W
Wei Shengyu 已提交
502 503
    Parameters:
        kernel_size(int|list|tuple): The pool kernel size. If the kernel size
504
            is a tuple or list, it must contain three integers,
505
            (kernel_size_Depth, kernel_size_Height, kernel_size_Width).
506
            Otherwise, the pool kernel size will be the cube of an int.
W
Wei Shengyu 已提交
507
        stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list,
508 509
            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 已提交
510 511
            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.
512 513 514
            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 已提交
515
            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.
516 517
            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 已提交
518 519 520 521 522 523 524
        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.
525 526


W
Wei Shengyu 已提交
527 528
    Returns:
        A callable object of MaxPool3D.
529 530

    Shape:
W
Wei Shengyu 已提交
531 532 533 534
        - 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.
535

536 537
    Examples:
        .. code-block:: python
538

W
Wei Shengyu 已提交
539 540 541
            import paddle
            import paddle.nn as nn
            import numpy as np
542

W
Wei Shengyu 已提交
543 544 545
            # max pool3d
            input = paddle.to_tensor(np.random.uniform(-1, 1, [1, 2, 3, 32, 32]).astype(np.float32))
            MaxPool3D = nn.MaxPool3D(kernel_size=2,
546
                                   stride=2, padding=0)
W
Wei Shengyu 已提交
547 548
            output = MaxPool3D(input)
            # output.shape [1, 2, 3, 16, 16]
549

W
Wei Shengyu 已提交
550 551 552 553
            # 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],
554 555 556 557
    """

    def __init__(self,
                 kernel_size,
P
parap1uie-s 已提交
558 559
                 stride=None,
                 padding=0,
560
                 return_mask=False,
561 562 563
                 ceil_mode=False,
                 data_format="NCDHW",
                 name=None):
C
cnn 已提交
564
        super(MaxPool3D, self).__init__()
565 566 567
        self.ksize = kernel_size
        self.stride = stride
        self.padding = padding
568
        self.return_mask = return_mask
569 570 571 572 573
        self.ceil_mode = ceil_mode
        self.data_format = data_format
        self.name = name

    def forward(self, x):
574 575 576 577 578 579 580 581
        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)
582

583 584 585 586
    def extra_repr(self):
        return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format(
            **self.__dict__)

587

Z
zhiboniu 已提交
588
class AdaptiveAvgPool1D(Layer):
589
    r"""
590

591 592 593 594 595
    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]`.
596

597
    The formulation for average adaptive pool1d is
598 599 600

    ..  math::

601
        lstart &= \lfloor i * L_{in} / L_{out}\rfloor,
602

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

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

W
Wei Shengyu 已提交
607
    Parameters:
608 609
        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.
610

611
    Returns:
612
        A callable object for computing 1D adaptive average pooling.
613

614 615
    Examples:
        .. code-block:: python
616

W
Wei Shengyu 已提交
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
            # 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
            import numpy as np

            data = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32]).astype(np.float32))
            AdaptiveAvgPool1D = nn.AdaptiveAvgPool1D(output_size=16)
            pool_out = AdaptiveAvgPool1D(data)
            # pool_out shape: [1, 3, 16]
637 638
    """

639
    def __init__(self, output_size, name=None):
C
cnn 已提交
640
        super(AdaptiveAvgPool1D, self).__init__()
641
        self.output_size = output_size
642 643
        self.name = name

644 645 646
    def forward(self, input):
        return F.adaptive_avg_pool1d(input, self.output_size, self.name)

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

650

Z
zhiboniu 已提交
651
class AdaptiveAvgPool2D(Layer):
652
    r"""
653 654 655 656 657 658 659 660

    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 已提交
661
        hstart &= floor(i * H_{in} / H_{out})
662

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

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

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

W
Wei Shengyu 已提交
669
        Output(i ,j) &= \frac{\sum Input[hstart:hend, wstart:wend]}{(hend - hstart) * (wend - wstart)}
670 671 672


    Parameters:
W
Wei Shengyu 已提交
673
        output_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
674 675
            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 已提交
676
        data_format(str, optional): The data format of the input and output data. An optional string
677 678
            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 已提交
679 680
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
681 682

    Shape:
W
Wei Shengyu 已提交
683 684 685 686
        - 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.
687 688

    Returns:
C
cnn 已提交
689
        A callable object of AdaptiveAvgPool2D.
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710

    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
            import numpy as np
711

712 713 714
            input_data = np.random.rand(2, 3, 32, 32)
            x = paddle.to_tensor(input_data)
            # x.shape is [2, 3, 32, 32]
C
cnn 已提交
715
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool2D(output_size=3)
716 717 718 719 720
            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 已提交
721
        super(AdaptiveAvgPool2D, self).__init__()
722 723 724 725 726
        self._output_size = output_size
        self._data_format = data_format
        self._name = name

    def forward(self, x):
727 728 729 730
        return F.adaptive_avg_pool2d(x,
                                     output_size=self._output_size,
                                     data_format=self._data_format,
                                     name=self._name)
731

732 733 734
    def extra_repr(self):
        return 'output_size={}'.format(self._output_size)

735

Z
zhiboniu 已提交
736
class AdaptiveAvgPool3D(Layer):
737
    r"""
738 739 740 741 742 743 744 745

    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 已提交
746
        dstart &= floor(i * D_{in} / D_{out})
747

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

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

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

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

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

W
Wei Shengyu 已提交
758 759
        Output(i ,j, k) &= \frac{\sum Input[dstart:dend, hstart:hend, wstart:wend]}
            {(dend - dstart) * (hend - hstart) * (wend - wstart)}
760 761 762


    Parameters:
W
Wei Shengyu 已提交
763
        output_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
764 765
            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 已提交
766
        data_format(str, optional): The data format of the input and output data. An optional string
767 768
            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 已提交
769 770
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
771
    Shape:
W
Wei Shengyu 已提交
772 773 774 775
        - 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.
776 777

    Returns:
C
cnn 已提交
778
        A callable object of AdaptiveAvgPool3D.
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802

    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
            import numpy as np
803

804 805 806
            input_data = np.random.rand(2, 3, 8, 32, 32)
            x = paddle.to_tensor(input_data)
            # x.shape is [2, 3, 8, 32, 32]
C
cnn 已提交
807
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool3D(output_size=3)
808 809 810 811 812
            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 已提交
813
        super(AdaptiveAvgPool3D, self).__init__()
814 815 816 817 818
        self._output_size = output_size
        self._data_format = data_format
        self._name = name

    def forward(self, x):
819 820 821 822
        return F.adaptive_avg_pool3d(x,
                                     output_size=self._output_size,
                                     data_format=self._data_format,
                                     name=self._name)
823

824 825 826
    def extra_repr(self):
        return 'output_size={}'.format(self._output_size)

827

Z
zhiboniu 已提交
828
class AdaptiveMaxPool1D(Layer):
829 830 831
    """

    This operation applies a 1D adaptive max pooling over an input signal composed
832
    of several input planes, based on the input, output_size, return_mask parameters.
833 834 835 836 837 838 839 840
    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 已提交
841
        lstart &= floor(i * L_{in} / L_{out})
842

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

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

W
Wei Shengyu 已提交
847 848 849 850
    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
851
            with outputs. It cannot be set in average pooling type. Default False.
W
Wei Shengyu 已提交
852 853
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
854
    Returns:
W
Wei Shengyu 已提交
855
        A callable object of AdaptiveMaxPool1D.
856 857

    Shape:
W
Wei Shengyu 已提交
858 859 860 861
        - 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.
862 863 864 865

    Examples:
        .. code-block:: python

W
Wei Shengyu 已提交
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
            # 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
            import numpy as np

            data = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32]).astype(np.float32))
            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]
891 892 893

    """

894
    def __init__(self, output_size, return_mask=False, name=None):
C
cnn 已提交
895
        super(AdaptiveMaxPool1D, self).__init__()
896
        self.output_size = output_size
897
        self.return_mask = return_mask
898 899 900
        self.name = name

    def forward(self, input):
901 902
        return F.adaptive_max_pool1d(input, self.output_size, self.return_mask,
                                     self.name)
903

904 905 906 907
    def extra_repr(self):
        return 'output_size={}, return_mask={}'.format(self.output_size,
                                                       self.return_mask)

908

Z
zhiboniu 已提交
909
class AdaptiveMaxPool2D(Layer):
910 911
    """
    This operation applies 2D adaptive max pooling on input tensor. The h and w dimensions
W
Wei Shengyu 已提交
912 913
    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.
914

915
    For adaptive max pool2d:
916

917
    ..  math::
918

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

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

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

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

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

929
    Parameters:
W
Wei Shengyu 已提交
930 931 932 933 934 935 936
        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.
937
    Shape:
W
Wei Shengyu 已提交
938 939 940 941
        - 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 已提交
942

943
    Returns:
C
cnn 已提交
944
        A callable object of AdaptiveMaxPool2D.
945 946
    Examples:
        .. code-block:: python
947

948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
            # 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
            import numpy as np
965

966 967
            input_data = np.random.rand(2, 3, 32, 32)
            x = paddle.to_tensor(input_data)
968
            adaptive_max_pool = paddle.nn.AdaptiveMaxPool2D(output_size=3, return_mask=True)
969 970 971
            pool_out, indices = adaptive_max_pool(x = x)
    """

972
    def __init__(self, output_size, return_mask=False, name=None):
C
cnn 已提交
973
        super(AdaptiveMaxPool2D, self).__init__()
974
        self._output_size = output_size
975
        self._return_mask = return_mask
976 977 978
        self._name = name

    def forward(self, x):
979 980 981 982
        return F.adaptive_max_pool2d(x,
                                     output_size=self._output_size,
                                     return_mask=self._return_mask,
                                     name=self._name)
983

984 985 986 987
    def extra_repr(self):
        return 'output_size={}, return_mask={}'.format(self._output_size,
                                                       self._return_mask)

988

Z
zhiboniu 已提交
989
class AdaptiveMaxPool3D(Layer):
990
    """
W
Wei Shengyu 已提交
991 992 993
    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.
994

995
    For adaptive max pool3d:
996

997
    ..  math::
998

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

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

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

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

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

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

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

1013
    Parameters:
W
Wei Shengyu 已提交
1014 1015 1016 1017 1018 1019 1020
        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.
1021
    Shape:
W
Wei Shengyu 已提交
1022 1023 1024 1025 1026
        - 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.

1027
    Returns:
C
cnn 已提交
1028
        A callable object of AdaptiveMaxPool3D.
1029 1030
    Examples:
        .. code-block:: python
1031

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
            # 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
            import numpy as np
1052

1053 1054
            input_data = np.random.rand(2, 3, 8, 32, 32)
            x = paddle.to_tensor(input_data)
C
cnn 已提交
1055
            pool = paddle.nn.AdaptiveMaxPool3D(output_size=4)
1056 1057
            out = pool(x)
            # out shape: [2, 3, 4, 4, 4]
1058
            pool = paddle.nn.AdaptiveMaxPool3D(output_size=3, return_mask=True)
1059
            out, indices = pool(x)
1060
            # out shape: [2, 3, 4, 4, 4], indices shape: [2, 3, 4, 4, 4]
D
Double_V 已提交
1061

1062 1063
    """

1064
    def __init__(self, output_size, return_mask=False, name=None):
C
cnn 已提交
1065
        super(AdaptiveMaxPool3D, self).__init__()
1066
        self._output_size = output_size
1067
        self._return_mask = return_mask
1068 1069 1070
        self._name = name

    def forward(self, x):
1071 1072 1073 1074
        return F.adaptive_max_pool3d(x,
                                     output_size=self._output_size,
                                     return_mask=self._return_mask,
                                     name=self._name)
1075 1076 1077 1078

    def extra_repr(self):
        return 'output_size={}, return_mask={}'.format(self._output_size,
                                                       self._return_mask)
1079 1080


1081
class MaxUnPool1D(Layer):
1082
    r"""
1083 1084
    This API implements max unpooling 1d opereation.

1085 1086
    `max_unpool1d` accepts the output of `max_pool1d` as input,
    including the indices of the maximum value and calculate the partial inverse.
1087 1088 1089 1090
    All non-maximum values ​​are set to zero.

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

1092 1093 1094 1095
    .. math::
        L_{out} = (L_{in} - 1) * stride - 2 * padding + kernel\_size

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

1097 1098 1099 1100 1101 1102
    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.
1103
        output_size(list|tuple, optional): The target output size. If output_size is not specified,
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
                           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
1119

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
            import paddle
            import paddle.nn.functional as F
            import numpy as np

            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]

    """

    def __init__(self,
                 kernel_size,
                 stride=None,
                 padding=0,
                 data_format="NCL",
                 output_size=None,
                 name=None):
        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):
1149 1150 1151 1152 1153 1154 1155 1156
        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)
1157 1158 1159 1160 1161

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


1162
class MaxUnPool2D(Layer):
1163
    r"""
1164 1165
    This API implements max unpooling 2d opereation.

1166 1167 1168
    '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.
1169

1170 1171 1172 1173 1174 1175 1176 1177

    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.
1178
        output_size(list|tuple, optional): The target output size. If output_size is not specified,
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
                           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.

1200

1201 1202 1203

    Examples:
        .. code-block:: python
1204

1205 1206 1207
        import paddle
        import paddle.nn.functional as F

X
xiaoting 已提交
1208
        data = paddle.rand(shape=[1,1,6,6])
1209 1210 1211
        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 已提交
1212
        unpool_out = Unpool2D(pool_out, indices)
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
        # unpool_out shape: [1, 1, 6, 6]

    """

    def __init__(self,
                 kernel_size,
                 stride=None,
                 padding=0,
                 data_format="NCHW",
                 output_size=None,
                 name=None):
        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):
1233 1234 1235 1236 1237 1238 1239 1240
        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)
1241 1242 1243

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


class MaxUnPool3D(Layer):
1247
    r"""
1248 1249
    This API implements max unpooling 3d opereation.

1250 1251
    `max_unpool3d` accepts the output of `max_pool3d` as input,
    including the indices of the maximum value and calculate the partial inverse.
1252 1253 1254 1255
    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
1256

1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
    .. 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

1268

1269 1270 1271 1272 1273 1274
    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.
1275
        output_size(list|tuple, optional): The target output size. If output_size is not specified,
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
                           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
1291

1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
            import paddle
            import paddle.nn.functional as F
            import numpy as np

            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]

    """

    def __init__(self,
                 kernel_size,
                 stride=None,
                 padding=0,
                 data_format="NCDHW",
                 output_size=None,
                 name=None):
        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):
1321 1322 1323 1324 1325 1326 1327 1328
        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)
1329 1330 1331

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