pooling.py 57.2 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 64
    Returns:
        A callable object of AvgPool1D.
        
65 66 67
    Examples:

        .. code-block:: python
68

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

W
Wei Shengyu 已提交
73 74 75 76
            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]
77 78 79 80 81 82 83

    """

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

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

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

104

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

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

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

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

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

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

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

    """

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

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

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

211

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

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

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

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

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

W
Wei Shengyu 已提交
261 262 263
            # 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,
264
                                   stride=2, padding=0)
W
Wei Shengyu 已提交
265 266
            output = AvgPool3D(input)
            # output.shape [1, 2, 3, 16, 16]
267

268 269
    """

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

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

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

304

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

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

    ..  math::

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

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

    Raises:
342 343 344 345 346 347 348 349
        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 已提交
350 351 352 353
        - 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.
354 355

    Examples:
356

357 358
        .. code-block:: python

W
Wei Shengyu 已提交
359 360 361
            import paddle
            import paddle.nn as nn
            import numpy as np
362

W
Wei Shengyu 已提交
363 364 365 366
            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]
367

W
Wei Shengyu 已提交
368 369 370
            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]
371 372 373

    """

374 375 376 377
    def __init__(self,
                 kernel_size,
                 stride=None,
                 padding=0,
378
                 return_mask=False,
379 380
                 ceil_mode=False,
                 name=None):
C
cnn 已提交
381
        super(MaxPool1D, self).__init__()
382 383 384 385
        self.kernel_size = kernel_size
        self.stride = stride
        self.padding = padding
        self.ceil_mode = ceil_mode
386
        self.return_mask = return_mask
387 388 389
        self.name = name

    def forward(self, input):
390
        out = F.max_pool1d(input, self.kernel_size, self.stride, self.padding,
391
                           self.return_mask, self.ceil_mode, self.name)
392
        return out
393

394 395 396 397
    def extra_repr(self):
        return 'kernel_size={kernel_size}, stride={stride}, padding={padding}'.format(
            **self.__dict__)

398

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

W
Wei Shengyu 已提交
443 444
    Returns:
        A callable object of MaxPool2D.
445 446 447 448
    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.
449 450

    Shape:
W
Wei Shengyu 已提交
451 452 453 454
        - 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.
455

456 457
    Examples:
        .. code-block:: python
458

W
Wei Shengyu 已提交
459 460 461
            import paddle
            import paddle.nn as nn
            import numpy as np
462

W
Wei Shengyu 已提交
463 464 465
            # max pool2d
            input = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32, 32]).astype(np.float32))
            MaxPool2D = nn.MaxPool2D(kernel_size=2,
466
                                   stride=2, padding=0)
W
Wei Shengyu 已提交
467 468
            output = MaxPool2D(input)
            # output.shape [1, 3, 16, 16]
469

W
Wei Shengyu 已提交
470 471 472 473
            # 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],
474 475 476 477 478 479
    """

    def __init__(self,
                 kernel_size,
                 stride=None,
                 padding=0,
480
                 return_mask=False,
481 482 483
                 ceil_mode=False,
                 data_format="NCHW",
                 name=None):
C
cnn 已提交
484
        super(MaxPool2D, self).__init__()
485 486 487
        self.ksize = kernel_size
        self.stride = stride
        self.padding = padding
488
        self.return_mask = return_mask
489 490 491 492 493
        self.ceil_mode = ceil_mode
        self.data_format = data_format
        self.name = name

    def forward(self, x):
494 495 496 497 498 499 500 501
        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)
502

503 504 505 506
    def extra_repr(self):
        return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format(
            **self.__dict__)

507

Z
zhiboniu 已提交
508
class MaxPool3D(Layer):
509
    """
510
    This operation applies 3D max pooling over input features based on the input,
511
    and kernel_size, stride, padding parameters. Input(X) and Output(Out) are
512 513
    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.
514

W
Wei Shengyu 已提交
515 516
    Parameters:
        kernel_size(int|list|tuple): The pool kernel size. If the kernel size
517
            is a tuple or list, it must contain three integers,
518
            (kernel_size_Depth, kernel_size_Height, kernel_size_Width).
519
            Otherwise, the pool kernel size will be the cube of an int.
W
Wei Shengyu 已提交
520
        stride(int|list|tuple, optional): The pool stride size. If pool stride size is a tuple or list,
521 522
            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 已提交
523 524
            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.
525 526 527
            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 已提交
528
            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.
529 530
            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 已提交
531 532 533 534 535 536 537
        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.
538 539


W
Wei Shengyu 已提交
540 541
    Returns:
        A callable object of MaxPool3D.
542 543 544 545
    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.
546 547

    Shape:
W
Wei Shengyu 已提交
548 549 550 551
        - 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.
552

553 554
    Examples:
        .. code-block:: python
555

W
Wei Shengyu 已提交
556 557 558
            import paddle
            import paddle.nn as nn
            import numpy as np
559

W
Wei Shengyu 已提交
560 561 562
            # 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,
563
                                   stride=2, padding=0)
W
Wei Shengyu 已提交
564 565
            output = MaxPool3D(input)
            # output.shape [1, 2, 3, 16, 16]
566

W
Wei Shengyu 已提交
567 568 569 570
            # 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],
571 572 573 574
    """

    def __init__(self,
                 kernel_size,
P
parap1uie-s 已提交
575 576
                 stride=None,
                 padding=0,
577
                 return_mask=False,
578 579 580
                 ceil_mode=False,
                 data_format="NCDHW",
                 name=None):
C
cnn 已提交
581
        super(MaxPool3D, self).__init__()
582 583 584
        self.ksize = kernel_size
        self.stride = stride
        self.padding = padding
585
        self.return_mask = return_mask
586 587 588 589 590
        self.ceil_mode = ceil_mode
        self.data_format = data_format
        self.name = name

    def forward(self, x):
591 592 593 594 595 596 597 598
        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)
599

600 601 602 603
    def extra_repr(self):
        return 'kernel_size={ksize}, stride={stride}, padding={padding}'.format(
            **self.__dict__)

604

Z
zhiboniu 已提交
605
class AdaptiveAvgPool1D(Layer):
606
    r"""
607

608 609 610 611 612
    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]`.
613

614
    The formulation for average adaptive pool1d is
615 616 617

    ..  math::

618
        lstart &= \lfloor i * L_{in} / L_{out}\rfloor,
619

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

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

W
Wei Shengyu 已提交
624
    Parameters:
625 626
        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.
627

628
    Returns:
629
        A callable object for computing 1D adaptive average pooling.
630

631 632
    Examples:
        .. code-block:: python
633

W
Wei Shengyu 已提交
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
            # 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]
654 655
    """

656
    def __init__(self, output_size, name=None):
C
cnn 已提交
657
        super(AdaptiveAvgPool1D, self).__init__()
658
        self.output_size = output_size
659 660
        self.name = name

661 662 663
    def forward(self, input):
        return F.adaptive_avg_pool1d(input, self.output_size, self.name)

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

667

Z
zhiboniu 已提交
668
class AdaptiveAvgPool2D(Layer):
669
    r"""
670 671 672 673 674 675 676 677

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

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

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

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

W
Wei Shengyu 已提交
686
        Output(i ,j) &= \frac{\sum Input[hstart:hend, wstart:wend]}{(hend - hstart) * (wend - wstart)}
687 688 689


    Parameters:
W
Wei Shengyu 已提交
690
        output_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
691 692
            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 已提交
693
        data_format(str, optional): The data format of the input and output data. An optional string
694 695
            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 已提交
696 697
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
698 699

    Shape:
W
Wei Shengyu 已提交
700 701 702 703
        - 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.
704 705

    Returns:
C
cnn 已提交
706
        A callable object of AdaptiveAvgPool2D.
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727

    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
728

729 730 731
            input_data = np.random.rand(2, 3, 32, 32)
            x = paddle.to_tensor(input_data)
            # x.shape is [2, 3, 32, 32]
C
cnn 已提交
732
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool2D(output_size=3)
733 734 735 736 737
            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 已提交
738
        super(AdaptiveAvgPool2D, self).__init__()
739 740 741 742 743
        self._output_size = output_size
        self._data_format = data_format
        self._name = name

    def forward(self, x):
744 745 746 747
        return F.adaptive_avg_pool2d(x,
                                     output_size=self._output_size,
                                     data_format=self._data_format,
                                     name=self._name)
748

749 750 751
    def extra_repr(self):
        return 'output_size={}'.format(self._output_size)

752

Z
zhiboniu 已提交
753
class AdaptiveAvgPool3D(Layer):
754
    r"""
755 756 757 758 759 760 761 762

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

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

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

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

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

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

W
Wei Shengyu 已提交
775 776
        Output(i ,j, k) &= \frac{\sum Input[dstart:dend, hstart:hend, wstart:wend]}
            {(dend - dstart) * (hend - hstart) * (wend - wstart)}
777 778 779


    Parameters:
W
Wei Shengyu 已提交
780
        output_size(int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
781 782
            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 已提交
783
        data_format(str, optional): The data format of the input and output data. An optional string
784 785
            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 已提交
786 787
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
788
    Shape:
W
Wei Shengyu 已提交
789 790 791 792
        - 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.
793 794

    Returns:
C
cnn 已提交
795
        A callable object of AdaptiveAvgPool3D.
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819

    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
820

821 822 823
            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 已提交
824
            adaptive_avg_pool = paddle.nn.AdaptiveAvgPool3D(output_size=3)
825 826 827 828 829
            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 已提交
830
        super(AdaptiveAvgPool3D, self).__init__()
831 832 833 834 835
        self._output_size = output_size
        self._data_format = data_format
        self._name = name

    def forward(self, x):
836 837 838 839
        return F.adaptive_avg_pool3d(x,
                                     output_size=self._output_size,
                                     data_format=self._data_format,
                                     name=self._name)
840

841 842 843
    def extra_repr(self):
        return 'output_size={}'.format(self._output_size)

844

Z
zhiboniu 已提交
845
class AdaptiveMaxPool1D(Layer):
846 847 848
    """

    This operation applies a 1D adaptive max pooling over an input signal composed
849
    of several input planes, based on the input, output_size, return_mask parameters.
850 851 852 853 854 855 856 857
    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 已提交
858
        lstart &= floor(i * L_{in} / L_{out})
859

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

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

W
Wei Shengyu 已提交
864 865 866 867
    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
868
            with outputs. It cannot be set in average pooling type. Default False.
W
Wei Shengyu 已提交
869 870
        name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
            Usually name is no need to set and None by default.
871
    Returns:
W
Wei Shengyu 已提交
872
        A callable object of AdaptiveMaxPool1D.
873 874 875 876 877

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

    Shape:
W
Wei Shengyu 已提交
878 879 880 881
        - 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.
882 883 884 885

    Examples:
        .. code-block:: python

W
Wei Shengyu 已提交
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
            # 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]
911 912 913

    """

914
    def __init__(self, output_size, return_mask=False, name=None):
C
cnn 已提交
915
        super(AdaptiveMaxPool1D, self).__init__()
916
        self.output_size = output_size
917
        self.return_mask = return_mask
918 919 920
        self.name = name

    def forward(self, input):
921 922
        return F.adaptive_max_pool1d(input, self.output_size, self.return_mask,
                                     self.name)
923

924 925 926 927
    def extra_repr(self):
        return 'output_size={}, return_mask={}'.format(self.output_size,
                                                       self.return_mask)

928

Z
zhiboniu 已提交
929
class AdaptiveMaxPool2D(Layer):
930 931
    """
    This operation applies 2D adaptive max pooling on input tensor. The h and w dimensions
W
Wei Shengyu 已提交
932 933
    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.
934

935
    For adaptive max pool2d:
936

937
    ..  math::
938

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

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

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

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

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

949
    Parameters:
W
Wei Shengyu 已提交
950 951 952 953 954 955 956
        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.
957
    Shape:
W
Wei Shengyu 已提交
958 959 960 961
        - 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 已提交
962

963
    Returns:
C
cnn 已提交
964
        A callable object of AdaptiveMaxPool2D.
965 966
    Examples:
        .. code-block:: python
967

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
            # 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
985

986 987
            input_data = np.random.rand(2, 3, 32, 32)
            x = paddle.to_tensor(input_data)
988
            adaptive_max_pool = paddle.nn.AdaptiveMaxPool2D(output_size=3, return_mask=True)
989 990 991
            pool_out, indices = adaptive_max_pool(x = x)
    """

992
    def __init__(self, output_size, return_mask=False, name=None):
C
cnn 已提交
993
        super(AdaptiveMaxPool2D, self).__init__()
994
        self._output_size = output_size
995
        self._return_mask = return_mask
996 997 998
        self._name = name

    def forward(self, x):
999 1000 1001 1002
        return F.adaptive_max_pool2d(x,
                                     output_size=self._output_size,
                                     return_mask=self._return_mask,
                                     name=self._name)
1003

1004 1005 1006 1007
    def extra_repr(self):
        return 'output_size={}, return_mask={}'.format(self._output_size,
                                                       self._return_mask)

1008

Z
zhiboniu 已提交
1009
class AdaptiveMaxPool3D(Layer):
1010
    """
W
Wei Shengyu 已提交
1011 1012 1013
    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.
1014

1015
    For adaptive max pool3d:
1016

1017
    ..  math::
1018

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

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

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

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

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

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

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

1033
    Parameters:
W
Wei Shengyu 已提交
1034 1035 1036 1037 1038 1039 1040
        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.
1041
    Shape:
W
Wei Shengyu 已提交
1042 1043 1044 1045 1046
        - 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.

1047
    Returns:
C
cnn 已提交
1048
        A callable object of AdaptiveMaxPool3D.
1049 1050
    Examples:
        .. code-block:: python
1051

1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
            # 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
1072

1073 1074
            input_data = np.random.rand(2, 3, 8, 32, 32)
            x = paddle.to_tensor(input_data)
C
cnn 已提交
1075
            pool = paddle.nn.AdaptiveMaxPool3D(output_size=4)
1076 1077
            out = pool(x)
            # out shape: [2, 3, 4, 4, 4]
1078
            pool = paddle.nn.AdaptiveMaxPool3D(output_size=3, return_mask=True)
1079
            out, indices = pool(x)
1080
            # out shape: [2, 3, 4, 4, 4], indices shape: [2, 3, 4, 4, 4]
D
Double_V 已提交
1081

1082 1083
    """

1084
    def __init__(self, output_size, return_mask=False, name=None):
C
cnn 已提交
1085
        super(AdaptiveMaxPool3D, self).__init__()
1086
        self._output_size = output_size
1087
        self._return_mask = return_mask
1088 1089 1090
        self._name = name

    def forward(self, x):
1091 1092 1093 1094
        return F.adaptive_max_pool3d(x,
                                     output_size=self._output_size,
                                     return_mask=self._return_mask,
                                     name=self._name)
1095 1096 1097 1098

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


1101
class MaxUnPool1D(Layer):
1102
    r"""
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 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 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
    This API implements max unpooling 1d opereation.

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

    - Input: :math:`(N, C, L_{in})`
    - Output: :math:`(N, C, L_{out})`, where
    
    .. math::
        L_{out} = (L_{in} - 1) * stride - 2 * padding + kernel\_size

    or as given by :attr:`output_size` in the call operator.
    
    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.
        output_size(list|tuple, optional): The target output size. If output_size is not specified, 
                           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
        
            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):
1169 1170 1171 1172 1173 1174 1175 1176
        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)
1177 1178 1179 1180 1181

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


1182
class MaxUnPool2D(Layer):
1183
    r"""
1184 1185
    This API implements max unpooling 2d opereation.

1186 1187 1188
    '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.
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
    

    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.
        output_size(list|tuple, optional): The target output size. If output_size is not specified, 
                           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.

            

    Examples:
        .. code-block:: python
        
        import paddle
        import paddle.nn.functional as F

X
xiaoting 已提交
1228
        data = paddle.rand(shape=[1,1,6,6])
1229 1230 1231
        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 已提交
1232
        unpool_out = Unpool2D(pool_out, indices)
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
        # 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):
1253 1254 1255 1256 1257 1258 1259 1260
        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)
1261 1262 1263

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


class MaxUnPool3D(Layer):
1267
    r"""
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 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 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
    This API implements max unpooling 3d opereation.

    `max_unpool3d` accepts the output of `max_pool3d` as input, 
    including the indices of the maximum value and calculate the partial inverse. 
    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
    
    .. 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

    
    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.
        output_size(list|tuple, optional): The target output size. If output_size is not specified, 
                           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
        
            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):
1341 1342 1343 1344 1345 1346 1347 1348
        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)
1349 1350 1351

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