common.py 66.8 KB
Newer Older
S
shiyutang 已提交
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6
#
# 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
#
S
shiyutang 已提交
7
#    http://www.apache.org/licenses/LICENSE-2.0
8 9 10 11 12 13 14
#
# 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.

15
# TODO: define the common classes to build a neural network
16
import paddle
17 18 19
from paddle import in_dynamic_mode
from paddle.nn import Layer

20
from .. import functional as F
21

22 23
__all__ = []

24

25
def _npairs(x, n):
26
    if isinstance(x, (paddle.Tensor, list, tuple)):
27 28 29 30 31
        return x
    x = [x] * (n * 2)
    return x


S
shiyutang 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
class Identity(Layer):
    r"""

    A placeholder identity operator that is argument-insensitive. For each input :math:`X` ,
    the output :math:`Out` is:

    .. math::

        Out = X

    Parameters:
        args: any argument (unused)
        kwargs: any keyword argument (unused)

    Shape:
        - input: Multi-dimentional tensor with shape :math:`[batch\_size, n1, n2, ...]` .
        - output: Multi-dimentional tensor with shape :math:`[batch\_size, n1, n2, ...]` .

    Examples:
        .. code-block:: python

          import paddle

          input_tensor = paddle.randn(shape=[3, 2])
          layer = paddle.nn.Identity()
          out = layer(input_tensor)
          # input_tensor: [[-0.32342386 -1.200079  ]
          #                [ 0.7979031  -0.90978354]
          #                [ 0.40597573  1.8095392 ]]
          # out: [[-0.32342386 -1.200079  ]
          #      [ 0.7979031  -0.90978354]
          #      [ 0.40597573  1.8095392 ]]


    """

    def __init__(self, *args, **kwargs):
69
        super().__init__()
S
shiyutang 已提交
70 71 72 73 74

    def forward(self, input):
        return input


Z
zhiboniu 已提交
75
class Linear(Layer):
76
    r"""
77 78 79

    Fully-connected linear transformation layer. For each input :math:`X` ,
    the equation is:
80 81 82

    .. math::

83
        Out = XW + b
84

85
    where :math:`W` is the weight and :math:`b` is the bias.
86

87 88 89 90 91 92 93
    Linear layer takes only one multi-dimensional tensor as input with the
    shape :math:`[batch\_size, *, in\_features]` , where :math:`*` means any
    number of additional dimensions. It multiplies input tensor with the weight
    (a 2-D tensor of shape :math:`[in\_features, out\_features]` ) and produces
    an output tensor of shape :math:`[batch\_size, *, out\_features]` .
    If :math:`bias\_attr` is not False, the bias (a 1-D tensor of
    shape :math:`[out\_features]` ) will be created and added to the output.
94 95

    Parameters:
96 97 98
        in_features (int): The number of input units.
        out_features (int): The number of output units.
        weight_attr (ParamAttr, optional): The attribute for the learnable
99 100 101
            weight of this layer. The default value is None. If the Initializer of the
            param_attr is not set, the parameter is initialized with Xavier.
            For detailed information, please refer to paddle.ParamAttr.
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
        bias_attr (ParamAttr|bool, optional): The attribute for the learnable bias
            of this layer. If it is set to False, no bias will be added to the output.
            If it is set to None or one kind of ParamAttr, a bias parameter will
            be created according to ParamAttr. For detailed information, please refer
            to paddle.ParamAttr. The default value is None and the bias will be
            initialized to zero.
        name (str, optional): Normally there is no need for user to set this parameter.
            For detailed information, please refer to :ref:`api_guide_Name` .

    Attribute:
        **weight** (Parameter): the learnable weight of this layer.

        **bias** (Parameter): the learnable bias of this layer.

    Shape:
        - input: Multi-dimentional tensor with shape :math:`[batch\_size, *, in\_features]` .
        - output: Multi-dimentional tensor with shape :math:`[batch\_size, *, out\_features]` .
119 120 121 122 123

    Examples:
        .. code-block:: python

          import paddle
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

          # Define the linear layer.
          weight_attr = paddle.ParamAttr(
              name="weight",
              initializer=paddle.nn.initializer.Constant(value=0.5))
          bias_attr = paddle.ParamAttr(
              name="bias",
              initializer=paddle.nn.initializer.Constant(value=1.0))
          linear = paddle.nn.Linear(2, 4, weight_attr=weight_attr, bias_attr=bias_attr)
          # linear.weight: [[0.5 0.5 0.5 0.5]
          #                 [0.5 0.5 0.5 0.5]]
          # linear.bias: [1. 1. 1. 1.]

          x = paddle.randn((3, 2), dtype="float32")
          # x: [[-0.32342386 -1.200079  ]
          #     [ 0.7979031  -0.90978354]
          #     [ 0.40597573  1.8095392 ]]
          y = linear(x)
          # y: [[0.23824859 0.23824859 0.23824859 0.23824859]
          #     [0.9440598  0.9440598  0.9440598  0.9440598 ]
          #     [2.1077576  2.1077576  2.1077576  2.1077576 ]]
145 146
    """

147 148 149 150 151 152 153 154
    def __init__(
        self,
        in_features,
        out_features,
        weight_attr=None,
        bias_attr=None,
        name=None,
    ):
155
        super().__init__()
156 157 158
        self._dtype = self._helper.get_default_dtype()
        self._weight_attr = weight_attr
        self._bias_attr = bias_attr
159 160 161 162 163 164 165 166 167 168 169 170
        self.weight = self.create_parameter(
            shape=[in_features, out_features],
            attr=self._weight_attr,
            dtype=self._dtype,
            is_bias=False,
        )
        self.bias = self.create_parameter(
            shape=[out_features],
            attr=self._bias_attr,
            dtype=self._dtype,
            is_bias=True,
        )
171 172 173
        self.name = name

    def forward(self, input):
174 175 176
        out = F.linear(
            x=input, weight=self.weight, bias=self.bias, name=self.name
        )
177 178
        return out

179 180 181
    def extra_repr(self):
        name_str = ', name={}'.format(self.name) if self.name else ''
        return 'in_features={}, out_features={}, dtype={}{}'.format(
182 183
            self.weight.shape[0], self.weight.shape[1], self._dtype, name_str
        )
184

185

Z
zhiboniu 已提交
186
class Upsample(Layer):
187 188
    """
    This op resizes a batch of images.
189

190 191 192
    The input must be a 3-D Tensor of the shape (num_batches, channels, in_w)
    or 4-D (num_batches, channels, in_h, in_w), or a 5-D Tensor of the shape
    (num_batches, channels, in_d, in_h, in_w) or (num_batches, in_d, in_h, in_w, channels),
193 194
    Where in_w is width of the input tensor, in_h is the height of the input tensor,
    in_d is the depth of the intput tensor.
195
    and the resizing only applies on the three dimensions(depth, height and width).
X
xiaoting 已提交
196

197
    Supporting resample methods:
198 199 200 201 202 203
        'linear' : Linear interpolation
        'bilinear' : Bilinear interpolation
        'trilinear' : Trilinear interpolation
        'nearest' : Nearest neighbor interpolation
        'bicubic' : Bicubic interpolation

T
tangwei12 已提交
204 205 206
    Linear interpolation is the method of using a line connecting two known quantities
    to determine the value of an unknown quantity between the two known quantities.

207 208 209 210 211 212 213 214 215
    Nearest neighbor interpolation is to perform nearest neighbor interpolation
    in both the 3rd dimension(in height direction) and the 4th dimension(in width
    direction) on input tensor.

    Bilinear interpolation is an extension of linear interpolation for
    interpolating functions of two variables (e.g. H-direction and
    W-direction in this op) on a rectilinear 2D grid. The key idea is
    to perform linear interpolation first in one direction, and then
    again in the other direction.
T
tangwei12 已提交
216

217 218 219 220
    Bicubic interpolation is an extension of cubic interpolation for interpolating
    data points on a two-dimensional regular grid. The interpolated surface is
    smoother than corresponding surfaces obtained by bilinear interpolation or
    nearest-neighbor interpolation.
221 222 223 224 225

    Trilinear interpolation is an extension of linear interpolation for
    interpolating functions of three variables (e.g. D-direction,
    H-direction and W-direction in this op) on a rectilinear 3D grid.
    The linear interpolation is performed on three directions.
X
xiaoting 已提交
226
    align_corners and align_mode are optional parameters,the calculation method
227 228
    of interpolation can be selected by them.

229 230 231 232 233 234
    Area interpolation is to perform area interpolation
    in both the 3rd dimension(in height direction) , the 4th dimension(in width
    direction) and the 5th dimension(in depth direction) on input tensor. Set to
    area will directly call `paddle.nn.functional.adaptive_avg_pool1d` or
    `paddle.nn.functional.adaptive_avg_pool2d` or `paddle.nn.functional.adaptive_avg_pool3d`.

235 236 237 238
    Example:

    .. code-block:: text

239
        For scale_factor:
240 241 242 243 244
            if align_corners = True && out_size > 1 :
              scale_factor = (in_size-1.0)/(out_size-1.0)
            else:
              scale_factor = float(in_size/out_size)

245 246 247 248 249 250 251 252 253 254
        Linear interpolation:
            if:
                align_corners = False , align_mode = 0
                input : (N,C,W_in)
                output: (N,C,W_out) where:
                W_out = (W_{in}+0.5) * scale_{factor} - 0.5
            else:
                input : (N,C,W_in)
                output: (N,C,W_out) where:
                W_out = W_{in} * scale_{factor}
255 256 257 258 259 260 261 262 263 264 265 266 267 268

        Nearest neighbor interpolation:
          if:
              align_corners = False
              input : (N,C,H_in,W_in)
              output: (N,C,H_out,W_out) where:
              H_out = floor (H_{in} * scale_{factor})
              W_out = floor (W_{in} * scale_{factor})
          else:
              align_corners = True
              input : (N,C,H_in,W_in)
              output: (N,C,H_out,W_out) where:
              H_out = round(H_{in} * scale_{factor})
              W_out = round(W_{in} * scale_{factor})
T
tangwei12 已提交
269

270 271 272
        Bilinear interpolation:
          if:
              align_corners = False , align_mode = 0
273

274 275 276 277 278
              input : (N,C,H_in,W_in)
              output: (N,C,H_out,W_out) where:
              H_out = (H_{in}+0.5) * scale_{factor} - 0.5
              W_out = (W_{in}+0.5) * scale_{factor} - 0.5
          else:
279

280 281 282 283 284 285 286 287 288 289 290 291
              input : (N,C,H_in,W_in)
              output: (N,C,H_out,W_out) where:
              H_out = H_{in} * scale_{factor}
              W_out = W_{in} * scale_{factor}

        Bicubic interpolation:
          if:
              align_corners = False
              input : (N,C,H_in,W_in)
              output: (N,C,H_out,W_out) where:
              H_out = (H_{in}+0.5) * scale_{factor} - 0.5
              W_out = (W_{in}+0.5) * scale_{factor} - 0.5
292

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
          else:
              input : (N,C,H_in,W_in)
              output: (N,C,H_out,W_out) where:
              H_out = H_{in} * scale_{factor}
              W_out = W_{in} * scale_{factor}

        Trilinear interpolation:
          if:
              align_corners = False , align_mode = 0
              input : (N,C,D_in,H_in,W_in)
              output: (N,C,D_out,H_out,W_out) where:
              D_out = (D_{in}+0.5) * scale_{factor} - 0.5
              H_out = (H_{in}+0.5) * scale_{factor} - 0.5
              W_out = (W_{in}+0.5) * scale_{factor} - 0.5
          else:
              input : (N,C,D_in,H_in,W_in)
              output: (N,C,D_out,H_out,W_out) where:
              D_out = D_{in} * scale_{factor}
              H_out = H_{in} * scale_{factor}
              W_out = W_{in} * scale_{factor}

314 315
    https://en.wikipedia.org/wiki/Linear_interpolation.
    For details of linear interpolation, please refer to Wikipedia:
T
tangwei12 已提交
316

317 318
    For details of nearest neighbor interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation.
T
tangwei12 已提交
319

320 321
    For details of bilinear interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Bilinear_interpolation.
T
tangwei12 已提交
322

323 324
    For details of bicubic interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Bicubic_interpolation
T
tangwei12 已提交
325

326 327
    For details of trilinear interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Trilinear_interpolation.
T
tangwei12 已提交
328

329
    Parameters:
X
xiaoting 已提交
330
        x (Tensor): 3-D, 4-D or 5-D Tensor, its data type is float32, float64, or uint8,
331
                          its data format is specified by :attr:`data_format`.
X
xiaoting 已提交
332
        size (list|tuple|Tensor|None): Output shape of image resize
333 334
             layer, the shape is (out_w, ) when input is a 3-D Tensor, the shape is (out_h, out_w)
             when input is a 4-D Tensor and is (out_d, out_h, out_w) when input is a 5-D Tensor.
335
             Default: None. If a list/tuple, each element can be an integer or a Tensor of shape: [1].
X
xiaoting 已提交
336
             If a Tensor , its dimensions size should be a 1.
337 338 339
        scale_factor (float|Tensor|list|tuple|None): The multiplier for the input height or width. At
             least one of :attr:`size` or :attr:`scale_factor` must be set.
             And :attr:`size` has a higher priority than :attr:`scale_factor`. Has to match input size if it is either a list or a tuple or a Tensor.
340
             Default: None.
341 342
        mode (str): The resample method. It supports 'linear', 'nearst', 'bilinear',
                       'bicubic' and 'trilinear' currently. Default: 'nearest'
343 344 345
        align_corners(bool) :  An optional bool, If True, the centers of the 4 corner pixels of the
                               input and output tensors are aligned, preserving the values at the
                               corner pixels.
346 347 348 349
                               Default: False
        align_mode(int)  :  An optional for linear/bilinear/trilinear interpolation. Refer to the formula in the example above,
                            it can be \'0\' for src_idx = scale_factor*(dst_indx+0.5)-0.5 , can be \'1\' for
                            src_idx = scale_factor*dst_index.
350
        data_format (str, optional): Specify the data format of the input, and the data format of the output
351
            will be consistent with that of the input. An optional string from:`NCW`, `NWC`, `"NCHW"`, `"NHWC"`, `"NCDHW"`,
352 353 354
            `"NDHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
            `[batch_size, input_channels, input_height, input_width]`. When it is `"NCHW"`, the data is stored
            in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`.
355 356 357
        name(str, optional): The default value is None.
                             Normally there is no need for user to set this property.
                             For more information, please refer to :ref:`api_guide_Name`
358 359 360
    Returns:
        A 3-D Tensor of the shape (num_batches, channels, out_w) or (num_batches, out_w, channels),
        A 4-D Tensor of the shape (num_batches, channels, out_h, out_w) or (num_batches, out_h, out_w, channels),
361
        or 5-D Tensor of the shape (num_batches, channels, out_d, out_h, out_w) or (num_batches, out_d, out_h, out_w, channels).
362 363 364

    Examples:
        .. code-block:: python
365

366
            import paddle
X
xiaoting 已提交
367

368 369
            input = paddle.rand([2,3,6,10], dtype="float32")
            upsample_out = paddle.nn.Upsample(size=[12,12])
X
xiaoting 已提交
370 371 372

            output = upsample_out(x=input)
            print(output.shape)
373
            # [2, 3, 12, 12]
X
xiaoting 已提交
374

375 376
    """

377 378 379 380 381 382 383 384 385 386
    def __init__(
        self,
        size=None,
        scale_factor=None,
        mode='nearest',
        align_corners=False,
        align_mode=0,
        data_format='NCHW',
        name=None,
    ):
387
        super().__init__()
388 389 390
        self.size = size
        self.scale_factor = scale_factor
        self.mode = mode.lower()
391 392 393
        self.align_corners = align_corners
        self.align_mode = align_mode
        self.data_format = data_format
X
xiaoting 已提交
394
        self.name = name
395

X
xiaoting 已提交
396
    def forward(self, x):
397 398 399 400 401 402 403 404 405 406
        out = F.interpolate(
            x,
            size=self.size,
            scale_factor=self.scale_factor,
            mode=self.mode,
            align_corners=self.align_corners,
            align_mode=self.align_mode,
            data_format=self.data_format,
            name=self.name,
        )
X
xiaoting 已提交
407 408 409

        return out

410 411 412 413 414 415 416
    def extra_repr(self):
        if self.scale_factor is not None:
            main_str = 'scale_factor={}'.format(self.scale_factor)
        else:
            main_str = 'size={}'.format(self.size)
        name_str = ', name={}'.format(self.name) if self.name else ''
        return '{}, mode={}, align_corners={}, align_mode={}, data_format={}{}'.format(
417 418 419 420 421 422 423
            main_str,
            self.mode,
            self.align_corners,
            self.align_mode,
            self.data_format,
            name_str,
        )
424

X
xiaoting 已提交
425

Z
zhiboniu 已提交
426
class UpsamplingNearest2D(Layer):
X
xiaoting 已提交
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
    """
    This op upsamples a batch of images, using nearest neighbours' pixel values.
    The input must be a 4-D Tensor of the shape (num_batches, channels, in_h, in_w),
    where in_w is width of the input tensor, in_h is the height of the input tensor.
    And the upsampling only applies on the two dimensions(height and width).
    Nearest neighbor interpolation is to perform nearest neighbor interpolation
    in both the 3rd dimension(in height direction) and the 4th dimension(in width
    direction) on input tensor.

    For details of nearest neighbor interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation.

    Parameters:
        x (Tensor): 4-D Tensor, its data type is float32, float64, or uint8,
                          its data format is specified by :attr:`data_format`.
        size (list|tuple|Tensor|None): Output shape of image resize
             layer, the shape is (out_h, out_w) when input is a 4-D Tensor.
444
             Default: None. If a list/tuple, each element can be an integer or a Tensor of shape: [1].
X
xiaoting 已提交
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
             If a Tensor , its dimensions size should be a 1.
        scale_factor (float|int|list|tuple|Tensor|None): The multiplier for the input height or width. At
             least one of :attr:`size` or :attr:`scale_factor` must be set.
             And :attr:`size` has a higher priority than :attr:`scale_factor`.
             Has to match input size if it is either a list or a tuple or a Tensor.
             Default: None.
        data_format (str, optional): Specify the data format of the input, and the data format of the output
            will be consistent with that of the input. An optional string from:`NCW`, `NWC`, `"NCHW"`, `"NHWC"`, `"NCDHW"`,
            `"NDHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
            `[batch_size, input_channels, input_height, input_width]`. When it is `"NCHW"`, the data is stored
            in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`.
        name(str, optional): The default value is None.
                             Normally there is no need for user to set this property.
                             For more information, please refer to :ref:`api_guide_Name`
    Returns:
        A 4-D Tensor of the shape (num_batches, channels, out_h, out_w) or (num_batches, out_h, out_w, channels),


    Examples:
        .. code-block:: python

            import paddle
            import paddle.nn as nn

X
xiaoting 已提交
469
            input_data = paddle.rand(shape=(2,3,6,10)).astype("float32")
X
xiaoting 已提交
470 471 472 473 474 475 476
            upsample_out  = paddle.nn.UpsamplingNearest2D(size=[12,12])
            input = paddle.to_tensor(input_data)
            output = upsample_out(x=input)
            print(output.shape)
            # [2L, 3L, 12L, 12L]
    """

477 478 479
    def __init__(
        self, size=None, scale_factor=None, data_format='NCHW', name=None
    ):
480
        super().__init__()
X
xiaoting 已提交
481 482 483 484 485 486
        self.size = size
        self.scale_factor = scale_factor
        self.data_format = data_format
        self.name = name

    def forward(self, x):
487 488 489 490 491 492 493 494 495 496
        out = F.interpolate(
            x,
            size=self.size,
            scale_factor=self.scale_factor,
            mode='nearest',
            align_corners=False,
            align_mode=0,
            data_format=self.data_format,
            name=self.name,
        )
X
xiaoting 已提交
497 498 499

        return out

500 501 502 503 504 505
    def extra_repr(self):
        if self.scale_factor is not None:
            main_str = 'scale_factor={}'.format(self.scale_factor)
        else:
            main_str = 'size={}'.format(self.size)
        name_str = ', name={}'.format(self.name) if self.name else ''
506 507 508
        return '{}, data_format={}{}'.format(
            main_str, self.data_format, name_str
        )
509

X
xiaoting 已提交
510

Z
zhiboniu 已提交
511
class UpsamplingBilinear2D(Layer):
X
xiaoting 已提交
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
    """
    This op upsamples a batch of images, using bilinear' pixel values.
    The input must be a 4-D Tensor of the shape (num_batches, channels, in_h, in_w),
    where in_w is width of the input tensor, in_h is the height of the input tensor.
    And the upsampling only applies on the two dimensions(height and width).
    Bilinear interpolation is an extension of linear interpolation for
    interpolating functions of two variables (e.g. H-direction and
    W-direction in this op) on a rectilinear 2D grid. The key idea is
    to perform linear interpolation first in one direction, and then
    again in the other direction.

    For details of bilinear interpolation, please refer to Wikipedia:
    https://en.wikipedia.org/wiki/Bilinear_interpolation.

    Parameters:
        x (Tensor): 4-D Tensor, its data type is float32, float64, or uint8,
                          its data format is specified by :attr:`data_format`.
        size (list|tuple|Tensor|None): Output shape of image resize
             layer, the shape is (out_h, out_w) when input is a 4-D Tensor.
531
             Default: None. If a list/tuple, each element can be an integer or a Tensor  of shape: [1].
X
xiaoting 已提交
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
             If a Tensor , its dimensions size should be a 1.
        scale_factor (float|int|list|tuple|Tensor|None): The multiplier for the input height or width. At
             least one of :attr:`size` or :attr:`scale_factor` must be set.
             And :attr:`size` has a higher priority than :attr:`scale_factor`.
             Has to match input size if it is either a list or a tuple or a Tensor.
             Default: None.
        data_format (str, optional): Specify the data format of the input, and the data format of the output
            will be consistent with that of the input. An optional string from:`NCW`, `NWC`, `"NCHW"`, `"NHWC"`, `"NCDHW"`,
            `"NDHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
            `[batch_size, input_channels, input_height, input_width]`. When it is `"NCHW"`, the data is stored
            in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`.
        name(str, optional): The default value is None.
                             Normally there is no need for user to set this property.
                             For more information, please refer to :ref:`api_guide_Name`
    Returns:
        A 4-D Tensor of the shape (num_batches, channels, out_h, out_w) or (num_batches, out_h, out_w, channels),

    Examples:
        .. code-block:: python

            import paddle
            import paddle.nn as nn

X
xiaoting 已提交
555
            input_data = paddle.rand(shape=(2,3,6,10)).astype("float32")
X
xiaoting 已提交
556 557 558 559 560 561 562
            upsample_out  = paddle.nn.UpsamplingBilinear2D(size=[12,12])
            input = paddle.to_tensor(input_data)
            output = upsample_out(x=input)
            print(output.shape)
            # [2L, 3L, 12L, 12L]
    """

563 564 565
    def __init__(
        self, size=None, scale_factor=None, data_format='NCHW', name=None
    ):
566
        super().__init__()
X
xiaoting 已提交
567 568 569 570 571 572
        self.size = size
        self.scale_factor = scale_factor
        self.data_format = data_format
        self.name = name

    def forward(self, x):
573 574 575 576 577 578 579 580 581 582
        out = F.interpolate(
            x,
            size=self.size,
            scale_factor=self.scale_factor,
            mode='bilinear',
            align_corners=True,
            align_mode=0,
            data_format=self.data_format,
            name=self.name,
        )
X
xiaoting 已提交
583 584 585

        return out

586 587 588 589 590 591
    def extra_repr(self):
        if self.scale_factor is not None:
            main_str = 'scale_factor={}'.format(self.scale_factor)
        else:
            main_str = 'size={}'.format(self.size)
        name_str = ', name={}'.format(self.name) if self.name else ''
592 593 594
        return '{}, data_format={}{}'.format(
            main_str, self.data_format, name_str
        )
595

X
xiaoting 已提交
596

Z
zhiboniu 已提交
597
class Bilinear(Layer):
598
    r"""
599 600 601 602

    This layer performs bilinear on two inputs.

    .. math::
603

604
      out_{i} = x1 * W_{i} * {x2^\mathrm{T}}, i=0,1,...,outfeatures-1
605

606 607 608 609 610 611
      out = out + b

    In this formula:
     - :math:`x1`: the first input contains in1_features elements, shape is [batch_size, in1_features].
     - :math:`x2`: the second input contains in2_features elements, shape is [batch_size, in2_features].
     - :math:`W_{i}`: the i-th learned weight, shape is [in1_features, in2_features], and learned weight's shape is [out_features, in1_features, in2_features].
612
     - :math:`out_{i}`: the i-th element of out, shape is [batch_size], and out's shape is [batch_size, out_features].
613 614 615 616 617 618 619
     - :math:`b`: the learned bias, shape is [1, out_features].
     - :math:`x2^\mathrm{T}`: the transpose of :math:`x2`.

    Parameters:
       in1_features (int): The dimension of each first input(`x1`).
       in2_features (int): The dimension of each second input(`x2`).
       out_features (int): The dimension of output of this layer.
T
tangwei12 已提交
620
       weight_attr (ParamAttr, optional): The parameter attribute for the learnable w, parameters/weights of
621 622 623
       this layer. The default value is None.
       bias_attr (ParamAttr, optional): The parameter attribute for the bias
           of this layer. If it is set to False, no bias will be added to the output units.
T
tangwei12 已提交
624
           If it is set to None, the bias is initialized zero. The default value is None.
625 626 627 628 629 630 631 632 633
       name (str, optional): The default value is None. Normally there is no need for user
           to set this property. For more information, please refer to :ref:`api_guide_Name`. Default: None.

    Attribute:
        **weight** (Parameter): the learnable weights of this layer.

        **bias** (Parameter): the learnable bias of this layer.

    Returns:
634
       Tensor: A 2-D Tensor of shape [batch_size, out_features].
635 636 637 638 639 640

    Examples:
       .. code-block:: python

        import paddle

641 642
        layer1 = paddle.rand((5, 5)).astype('float32')
        layer2 = paddle.rand((5, 4)).astype('float32')
643 644
        bilinear = paddle.nn.Bilinear(
            in1_features=5, in2_features=4, out_features=1000)
645
        result = bilinear(layer1,layer2)    # result shape [5, 1000]
646 647 648

    """

649 650 651 652 653 654 655 656 657
    def __init__(
        self,
        in1_features,
        in2_features,
        out_features,
        weight_attr=None,
        bias_attr=None,
        name=None,
    ):
658
        super().__init__()
659 660 661 662 663 664 665 666 667
        self._weight_attr = weight_attr
        self._bias_attr = bias_attr
        self._name = name
        self._in1_features = in1_features
        self._in2_features = in2_features
        self._out_features = out_features
        self._dtype = self._helper.get_default_dtype()

        weight_shape = [
668 669 670
            self._out_features,
            self._in1_features,
            self._in2_features,
671
        ]
672 673 674 675 676 677
        self.weight = self.create_parameter(
            attr=self._weight_attr,
            shape=weight_shape,
            dtype=self._dtype,
            is_bias=False,
        )
678
        bias_shape = [1, self._out_features]
679 680 681 682 683 684
        self.bias = self.create_parameter(
            attr=self._bias_attr,
            shape=bias_shape,
            dtype=self._dtype,
            is_bias=True,
        )
685 686 687 688

    def forward(self, x1, x2):
        return F.bilinear(x1, x2, self.weight, self.bias, self._name)

689 690 691
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'in1_features={}, in2_features={}, out_features={}, dtype={}{}'.format(
692 693 694 695 696 697
            self._in1_features,
            self._in2_features,
            self._out_features,
            self._dtype,
            name_str,
        )
698

699

Z
zhiboniu 已提交
700
class Dropout(Layer):
701
    r"""
702 703
    Dropout is a regularization technique for reducing overfitting by preventing
    neuron co-adaption during training as described in the paper:
T
tangwei12 已提交
704
    `Improving neural networks by preventing co-adaptation of feature detectors <https://arxiv.org/abs/1207.0580>`_
705 706 707
    The dropout operator randomly sets the outputs of some units to zero, while upscale others
    according to the given dropout probability.

708
    See :ref:`api_paddle_nn_functional_dropout` for more details.
709 710

    In dygraph mode, please use ``eval()`` to switch to evaluation mode, where dropout is disabled.
711 712

    Parameters:
713 714
        p (float|int, optional): Probability of setting units to zero. Default: 0.5
        axis (int|list|tuple, optional): The axis along which the dropout is performed. Default: None.
715 716
        mode(str, optional): ['upscale_in_train'(default) | 'downscale_in_infer']

717
                               1. upscale_in_train (default), upscale the output at training time
718

719 720
                                  - train: :math:`out = input \times \frac{mask}{(1.0 - p)}`
                                  - inference: :math:`out = input`
721 722 723

                               2. downscale_in_infer, downscale the output at inference

724 725 726
                                  - train: :math:`out = input \times mask`
                                  - inference: :math:`out = input \times (1.0 - p)`
        name (str, optional): Name for the operation, Default: None. For more information, please refer to :ref:`api_guide_Name`.
727 728 729 730 731

    Shape:
        - input: N-D tensor.
        - output: N-D tensor, the same shape as input.

732

733 734
    Examples:
        .. code-block:: python
735

736 737
            import paddle

738
            x = paddle.to_tensor([[1,2,3], [4,5,6]], dtype="float32")
739
            m = paddle.nn.Dropout(p=0.5)
740

741
            y_train = m(x)
742 743 744 745 746
            print(y_train)
            # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [[2., 0., 6.],
            #         [0., 0., 0.]])

747 748
            m.eval()  # switch the model to test phase
            y_test = m(x)
749
            print(y_test)
750 751 752
            # Tensor(shape=[2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [[1., 2., 3.],
            #         [4., 5., 6.]])
753
    """
754 755

    def __init__(self, p=0.5, axis=None, mode="upscale_in_train", name=None):
756
        super().__init__()
757 758 759 760 761 762 763

        self.p = p
        self.axis = axis
        self.mode = mode
        self.name = name

    def forward(self, input):
764 765 766 767 768 769 770 771
        out = F.dropout(
            input,
            p=self.p,
            axis=self.axis,
            training=self.training,
            mode=self.mode,
            name=self.name,
        )
772 773
        return out

774 775
    def extra_repr(self):
        name_str = ', name={}'.format(self.name) if self.name else ''
776 777 778
        return 'p={}, axis={}, mode={}{}'.format(
            self.p, self.axis, self.mode, name_str
        )
779

780

Z
zhiboniu 已提交
781
class Dropout2D(Layer):
782 783 784 785
    """
    Randomly zero out entire channels (in the batched input 4d tensor with the shape `NCHW` ,
    a channel is a 2D feature map with the shape `HW`). Each channel will be zeroed out independently
    on every forward call with probability `p` using samples from a Bernoulli distribution.
C
cnn 已提交
786
    Dropout2D will help promote independence between feature maps as described in the paper:
T
tangwei12 已提交
787
    `Efficient Object Localization Using Convolutional Networks <https://arxiv.org/abs/1411.4280>`_
788

789
    See :ref:`api_paddle_nn_functional_dropout2d` for more details.
790

791 792
    In dygraph mode, please use ``eval()`` to switch to evaluation mode, where dropout is disabled.

793
    Parameters:
794 795 796
        p (float, optional): Probability of setting units to zero. Default: 0.5.
        data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from `NCHW` or `NHWC`. When it is `NCHW`, the data is stored in the order of: [batch_size, input_channels, input_height, input_width]. Default: `NCHW`.
        name (str, optional): Name for the operation, Default: None. For more information, please refer to :ref:`api_guide_Name`.
797 798 799 800 801

    Shape:
        - input: 4-D tensor.
        - output: 4-D tensor, the same shape as input.

802

803 804
    Examples:
        .. code-block:: python
805

806 807
            import paddle

808 809 810 811 812 813 814 815 816
            x = paddle.rand([2, 2, 1, 3], dtype="float32")
            print(x)
            # Tensor(shape=[2, 2, 1, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [[[[0.10052059, 0.93890846, 0.45351565]],
            #          [[0.47507706, 0.45021373, 0.11331241]]],

            #         [[[0.53358698, 0.97375143, 0.34997326]],
            #          [[0.24758087, 0.52628899, 0.17970420]]]])

C
cnn 已提交
817
            m = paddle.nn.Dropout2D(p=0.5)
818
            y_train = m(x)
819 820 821 822 823 824 825 826
            print(y_train)
            # Tensor(shape=[2, 2, 1, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [[[[0.        , 0.        , 0.        ]],
            #          [[0.95015413, 0.90042746, 0.22662482]]],

            #         [[[1.06717396, 1.94750285, 0.69994652]],
            #          [[0.        , 0.        , 0.        ]]]])

827 828
            m.eval()  # switch the model to test phase
            y_test = m(x)
829
            print(y_test)
830 831 832 833 834 835
            # Tensor(shape=[2, 2, 1, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [[[[0.10052059, 0.93890846, 0.45351565]],
            #          [[0.47507706, 0.45021373, 0.11331241]]],

            #         [[[0.53358698, 0.97375143, 0.34997326]],
            #          [[0.24758087, 0.52628899, 0.17970420]]]])
836
    """
837 838

    def __init__(self, p=0.5, data_format='NCHW', name=None):
839
        super().__init__()
840 841 842 843 844 845

        self.p = p
        self.data_format = data_format
        self.name = name

    def forward(self, input):
846 847 848 849 850 851 852
        out = F.dropout2d(
            input,
            p=self.p,
            training=self.training,
            data_format=self.data_format,
            name=self.name,
        )
853 854
        return out

855 856
    def extra_repr(self):
        name_str = ', name={}'.format(self.name) if self.name else ''
857 858 859
        return 'p={}, data_format={}{}'.format(
            self.p, self.data_format, name_str
        )
860

861

Z
zhiboniu 已提交
862
class Dropout3D(Layer):
863 864 865 866
    """
    Randomly zero out entire channels (in the batched input 5d tensor with the shape `NCDHW` ,
    a channel is a 3D feature map with the shape `DHW` ). Each channel will be zeroed out independently
    on every forward call with probability `p` using samples from a Bernoulli distribution.
C
cnn 已提交
867
    Dropout3D will help promote independence between feature maps as described in the paper:
T
tangwei12 已提交
868
    `Efficient Object Localization Using Convolutional Networks <https://arxiv.org/abs/1411.4280>`_
869

870
    See :ref:`api_paddle_nn_functional_dropout3d` for more details.
871

872 873
    In dygraph mode, please use ``eval()`` to switch to evaluation mode, where dropout is disabled.

874
    Parameters:
875 876 877
        p (float | int, optional): Probability of setting units to zero. Default: 0.5.
        data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from `NCDHW` or `NDHWC`. When it is `NCDHW`, the data is stored in the order of: [batch_size, input_channels, input_depth, input_height, input_width]. Default: `NCDHW`.
        name (str, optional): Name for the operation, Default: None. For more information, please refer to :ref:`api_guide_Name`.
878 879 880 881 882

    Shape:
        - input: 5-D tensor.
        - output: 5-D tensor, the same shape as input.

883

884 885
    Examples:
        .. code-block:: python
886

887 888
            import paddle

889 890 891 892 893 894 895 896 897 898 899 900 901
            x = paddle.arange(24, dtype="float32").reshape((1, 2, 2, 2, 3))
            print(x)
            # Tensor(shape=[1, 2, 2, 2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [[[[[0. , 1. , 2. ],
            #            [3. , 4. , 5. ]],
            #           [[6. , 7. , 8. ],
            #            [9. , 10., 11.]]],

            #          [[[12., 13., 14.],
            #            [15., 16., 17.]],
            #           [[18., 19., 20.],
            #            [21., 22., 23.]]]]])

C
cnn 已提交
902
            m = paddle.nn.Dropout3D(p=0.5)
903
            y_train = m(x)
904 905 906 907 908 909 910 911 912 913 914 915
            print(y_train)
            # Tensor(shape=[1, 2, 2, 2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [[[[[0. , 2. , 4. ],
            #            [6. , 8. , 10.]],
            #           [[12., 14., 16.],
            #            [18., 20., 22.]]],

            #          [[[0. , 0. , 0. ],
            #            [0. , 0. , 0. ]],
            #           [[0. , 0. , 0. ],
            #            [0. , 0. , 0. ]]]]])

916 917
            m.eval()  # switch the model to test phase
            y_test = m(x)
918
            print(y_test)
919 920 921 922 923 924 925 926 927 928
            # Tensor(shape=[1, 2, 2, 2, 3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [[[[[0. , 1. , 2. ],
            #            [3. , 4. , 5. ]],
            #           [[6. , 7. , 8. ],
            #            [9. , 10., 11.]]],

            #          [[[12., 13., 14.],
            #            [15., 16., 17.]],
            #           [[18., 19., 20.],
            #            [21., 22., 23.]]]]])
929
    """
930 931

    def __init__(self, p=0.5, data_format='NCDHW', name=None):
932
        super().__init__()
933 934 935 936 937 938

        self.p = p
        self.data_format = data_format
        self.name = name

    def forward(self, input):
939 940 941 942 943 944 945
        out = F.dropout3d(
            input,
            p=self.p,
            training=self.training,
            data_format=self.data_format,
            name=self.name,
        )
946 947
        return out

948 949
    def extra_repr(self):
        name_str = ', name={}'.format(self.name) if self.name else ''
950 951 952
        return 'p={}, data_format={}{}'.format(
            self.p, self.data_format, name_str
        )
953

954

Z
zhiboniu 已提交
955
class AlphaDropout(Layer):
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
    """
    Alpha Dropout is a type of Dropout that maintains the self-normalizing property. For an input with
    zero mean and unit standard deviation, the output of Alpha Dropout maintains the original mean and
    standard deviation of the input. Alpha Dropout fits well to SELU activate function by randomly setting
    activations to the negative saturation value.

    For more information, please refer to:
    `Self-Normalizing Neural Networks <https://arxiv.org/abs/1706.02515>`_

    In dygraph mode, please use ``eval()`` to switch to evaluation mode, where dropout is disabled.

    Parameters:
        p (float | int): Probability of setting units to zero. Default: 0.5
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: N-D tensor.
        - output: N-D tensor, the same shape as input.

    Examples:
        .. code-block:: python
977

978 979
            import paddle

980
            x = paddle.to_tensor([[-1, 1], [-1, 1]], dtype="float32")
981 982
            m = paddle.nn.AlphaDropout(p=0.5)
            y_train = m(x)
983 984 985 986 987
            print(y_train)
            # Tensor(shape=[2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [[-0.77919382,  1.66559887],
            #         [-0.77919382, -0.77919382]])

988 989
            m.eval()  # switch the model to test phase
            y_test = m(x)
990
            print(y_test)
991 992 993
            # Tensor(shape=[2, 2], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [[-1.,  1.],
            #         [-1.,  1.]])
994
    """
995 996

    def __init__(self, p=0.5, name=None):
997
        super().__init__()
998 999 1000 1001
        self.p = p
        self.name = name

    def forward(self, input):
1002 1003 1004
        out = F.alpha_dropout(
            input, p=self.p, training=self.training, name=self.name
        )
1005 1006
        return out

1007 1008 1009 1010
    def extra_repr(self):
        name_str = ', name={}'.format(self.name) if self.name else ''
        return 'p={}{}'.format(self.p, name_str)

1011

Z
zhiboniu 已提交
1012
class Pad1D(Layer):
L
littletomatodonkey 已提交
1013
    """
L
littletomatodonkey 已提交
1014
    This interface is used to construct a callable object of the ``Pad1D`` class.
1015 1016
    Pad tensor according to ``pad``, ``mode`` and ``value``.
    If mode is ``reflect``, pad[0] and pad[1] must be no greater than width-1.
L
littletomatodonkey 已提交
1017 1018

    Parameters:
1019
        padding (Tensor|list[int]|int): The padding size with data type ``'int'``. If is ``'int'``, use the
1020
            same padding in both dimensions. Else [len(padding)/2] dimensions
L
littletomatodonkey 已提交
1021
            of input will be padded. The pad has the form (pad_left, pad_right).
1022
        mode (str, optional): Four modes: ``'constant'`` (default), ``'reflect'``, ``'replicate'``, ``'circular'``. Default: ``'constant'``.
1023 1024 1025 1026 1027 1028

           - 'constant' mode, uses a constant value to pad the input tensor.
           - 'reflect' mode, uses reflection of the input boundaries to pad the input tensor.
           - 'replicate' mode, uses input boundaries to pad the input tensor.
           - 'circular' mode, uses circular input to pad the input tensor.

1029 1030 1031 1032
        value (float, optional): The value to fill the padded areas. Default is :math:`0.0`.
        data_format (str, optional): An string from: ``'NCL'``, ``'NLC'``. Specify the data format of the input data.
           Default: ``'NCL'``.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: ``'None'``.
1033 1034

    Returns:
L
littletomatodonkey 已提交
1035 1036 1037 1038
        None

    Examples:
        .. code-block:: python
1039

L
littletomatodonkey 已提交
1040 1041 1042 1043 1044
            import paddle
            import paddle.nn as nn

            input_shape = (1, 2, 3)
            pad = [1, 2]
L
littletomatodonkey 已提交
1045
            mode = "constant"
1046
            data = paddle.arange(paddle.prod(paddle.to_tensor(input_shape)), dtype="float32").reshape(input_shape) + 1
L
littletomatodonkey 已提交
1047
            my_pad = nn.Pad1D(padding=pad, mode=mode)
L
littletomatodonkey 已提交
1048
            result = my_pad(data)
L
littletomatodonkey 已提交
1049
            print(result)
L
littletomatodonkey 已提交
1050 1051 1052 1053
            # [[[0. 1. 2. 3. 0. 0.]
            #   [0. 4. 5. 6. 0. 0.]]]
    """

1054 1055 1056
    def __init__(
        self, padding, mode='constant', value=0.0, data_format="NCL", name=None
    ):
1057
        super().__init__()
1058
        self._pad = _npairs(padding, 1)
L
littletomatodonkey 已提交
1059
        self._mode = mode
L
littletomatodonkey 已提交
1060
        self._value = value
L
littletomatodonkey 已提交
1061
        self._data_format = data_format
L
littletomatodonkey 已提交
1062 1063 1064
        self._name = name

    def forward(self, x):
1065 1066 1067 1068 1069 1070 1071 1072
        return F.pad(
            x,
            pad=self._pad,
            mode=self._mode,
            value=self._value,
            data_format=self._data_format,
            name=self._name,
        )
L
littletomatodonkey 已提交
1073

1074 1075 1076
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'padding={}, mode={}, value={}, data_format={}{}'.format(
1077 1078
            self._pad, self._mode, self._value, self._data_format, name_str
        )
1079

L
littletomatodonkey 已提交
1080

Z
zhiboniu 已提交
1081
class Pad2D(Layer):
L
littletomatodonkey 已提交
1082
    """
L
littletomatodonkey 已提交
1083
    This interface is used to construct a callable object of the ``Pad2D`` class.
1084 1085
    Pad tensor according to ``pad``, ``mode`` and ``value``.
    If mode is ``'reflect'``, pad[0] and pad[1] must be no greater
L
littletomatodonkey 已提交
1086
    than width-1. The height dimension has the same condition.
L
littletomatodonkey 已提交
1087 1088

    Parameters:
1089
        padding (Tensor|list[int]|int): The padding size with data type ``'int'``. If is ``'int'``, use the
1090 1091
            same padding in all dimensions. Else [len(padding)/2] dimensions of input will be padded.
            The pad has the form (pad_left, pad_right, pad_top, pad_bottom).
1092
        mode (str, optional): Four modes: ``'constant'`` (default), ``'reflect'``, ``'replicate'``, ``'circular'``. Default: ``'constant'``.
1093 1094 1095 1096 1097 1098

           - 'constant' mode, uses a constant value to pad the input tensor.
           - 'reflect' mode, uses reflection of the input boundaries to pad the input tensor.
           - 'replicate' mode, uses input boundaries to pad the input tensor.
           - 'circular' mode, uses circular input to pad the input tensor.

1099 1100 1101 1102
        value (float, optional): The value to fill the padded areas. Default is :math:`0.0`.
        data_format (str, optional): An string from: ``'NCHW'``, ``'NHWC'``. Specify the data format of the input data.
           Default: ``'NCHW'``.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: ``'None'``.
1103 1104

    Returns:
L
littletomatodonkey 已提交
1105 1106 1107 1108
        None

    Examples:
        .. code-block:: python
1109

L
littletomatodonkey 已提交
1110 1111
            import paddle
            import paddle.nn as nn
1112

L
littletomatodonkey 已提交
1113 1114
            input_shape = (1, 1, 2, 3)
            pad = [1, 0, 1, 2]
L
littletomatodonkey 已提交
1115
            mode = "constant"
1116
            data = paddle.arange(paddle.prod(paddle.to_tensor(input_shape)), dtype="float32").reshape(input_shape) + 1
L
littletomatodonkey 已提交
1117
            my_pad = nn.Pad2D(padding=pad, mode=mode)
L
littletomatodonkey 已提交
1118
            result = my_pad(data)
L
littletomatodonkey 已提交
1119
            print(result)
L
littletomatodonkey 已提交
1120 1121 1122 1123 1124 1125 1126
            # [[[[0. 0. 0. 0.]
            #    [0. 1. 2. 3.]
            #    [0. 4. 5. 6.]
            #    [0. 0. 0. 0.]
            #    [0. 0. 0. 0.]]]]
    """

1127 1128 1129
    def __init__(
        self, padding, mode='constant', value=0.0, data_format="NCHW", name=None
    ):
1130
        super().__init__()
1131
        self._pad = _npairs(padding, 2)
L
littletomatodonkey 已提交
1132
        self._mode = mode
L
littletomatodonkey 已提交
1133 1134 1135 1136 1137
        self._value = value
        self._data_format = data_format
        self._name = name

    def forward(self, x):
1138 1139 1140 1141 1142 1143 1144 1145
        return F.pad(
            x,
            pad=self._pad,
            mode=self._mode,
            value=self._value,
            data_format=self._data_format,
            name=self._name,
        )
L
littletomatodonkey 已提交
1146

1147 1148 1149
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'padding={}, mode={}, value={}, data_format={}{}'.format(
1150 1151
            self._pad, self._mode, self._value, self._data_format, name_str
        )
1152

L
littletomatodonkey 已提交
1153

1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
class ZeroPad2D(Layer):
    """
    This interface is used to construct a callable object of the ``ZeroPad2D`` class.
    Pads the input tensor boundaries with zero.

    Parameters:
        padding (Tensor | List[int] | int): The padding size with data type int. If is int, use the
            same padding in all dimensions. Else [len(padding)/2] dimensions of input will be padded.
            The pad has the form (pad_left, pad_right, pad_top, pad_bottom).
        data_format (str): An string from: "NCHW", "NHWC". Specify the data format of the input data.
           Default is  "NCHW"
        name (str, optional) : The default value is None.  Normally there is no need for
            user to set this property.  For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - x(Tensor): The input tensor of zeropad2d operator, which is a 4-D tensor.
          The data type can be float32, float64.
        - output(Tensor): The output tensor of zeropad2d operator, which is a 4-D tensor.
          The data type is same as input x.

    Examples:
        Examples are as follows.

        .. code-block:: python

            import paddle
            import paddle.nn as nn
            import numpy as np

            input_shape = (1, 1, 2, 3)
            pad = [1, 0, 1, 2]
            data = paddle.arange(np.prod(input_shape), dtype="float32").reshape(input_shape) + 1

            my_pad = nn.ZeroPad2D(padding=pad)
            result = my_pad(data)

            print(result)
            # [[[[0. 0. 0. 0.]
            #    [0. 1. 2. 3.]
            #    [0. 4. 5. 6.]
            #    [0. 0. 0. 0.]
            #    [0. 0. 0. 0.]]]]
    """

    def __init__(self, padding, data_format="NCHW", name=None):
1199
        super().__init__()
1200 1201
        self._pad = _npairs(padding, 2)
        self._mode = 'constant'
1202
        self._value = 0.0
1203 1204 1205 1206
        self._data_format = data_format
        self._name = name

    def forward(self, x):
1207 1208 1209 1210 1211 1212 1213 1214
        return F.pad(
            x,
            pad=self._pad,
            mode=self._mode,
            value=self._value,
            data_format=self._data_format,
            name=self._name,
        )
1215 1216 1217

    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
1218 1219 1220
        return 'padding={}, data_format={}{}'.format(
            self._pad, self._data_format, name_str
        )
1221 1222


Z
zhiboniu 已提交
1223
class Pad3D(Layer):
L
littletomatodonkey 已提交
1224
    """
L
littletomatodonkey 已提交
1225
    This interface is used to construct a callable object of the ``Pad3D`` class.
1226 1227
    Pad tensor according to ``'pad'``, ``'mode'`` and ``'value'``.
    If mode is ``'reflect'``, pad[0] and pad[1] must be no greater
L
littletomatodonkey 已提交
1228
    than width-1. The height and depth dimension has the same condition.
L
littletomatodonkey 已提交
1229 1230

    Parameters:
1231
        padding (Tensor|list[int]|int): The padding size with data type ``'int'``. If is ``'int'``, use the
1232
            same padding in all dimensions. Else [len(padding)/2] dimensions
L
littletomatodonkey 已提交
1233
            of input will be padded. The pad has the form (pad_left, pad_right, pad_top, pad_bottom, pad_front, pad_back).
1234
        mode (str, optional): Four modes: ``'constant'`` (default), ``'reflect'``, ``'replicate'``, ``'circular'``. Default: ``'constant'``.
1235 1236 1237 1238 1239 1240

           - 'constant' mode, uses a constant value to pad the input tensor.
           - 'reflect' mode, uses reflection of the input boundaries to pad the input tensor.
           - 'replicate' mode, uses input boundaries to pad the input tensor.
           - 'circular' mode, uses circular input to pad the input tensor.

1241 1242 1243 1244
        value (float, optional): The value to fill the padded areas. Default is :math:`0.0`.
        data_format (str, optional): An string from: ``'NCDHW'``, ``'NDHWC'``. Specify the data format of the input data.
           Default:  ``'NCDHW'``。
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: ``'None'``.
1245 1246

    Returns:
L
littletomatodonkey 已提交
1247 1248 1249 1250
        None

    Examples:
        .. code-block:: python
1251

L
littletomatodonkey 已提交
1252 1253
            import paddle
            import paddle.nn as nn
1254

L
littletomatodonkey 已提交
1255 1256
            input_shape = (1, 1, 1, 2, 3)
            pad = [1, 0, 1, 2, 0, 0]
L
littletomatodonkey 已提交
1257
            mode = "constant"
1258
            data = paddle.arange(paddle.prod(paddle.to_tensor(input_shape)), dtype="float32").reshape(input_shape) + 1
L
littletomatodonkey 已提交
1259
            my_pad = nn.Pad3D(padding=pad, mode=mode)
L
littletomatodonkey 已提交
1260
            result = my_pad(data)
L
littletomatodonkey 已提交
1261
            print(result)
L
littletomatodonkey 已提交
1262 1263 1264 1265 1266 1267 1268
            # [[[[[0. 0. 0. 0.]
            #     [0. 1. 2. 3.]
            #     [0. 4. 5. 6.]
            #     [0. 0. 0. 0.]
            #     [0. 0. 0. 0.]]]]]
    """

1269 1270 1271 1272 1273 1274 1275 1276
    def __init__(
        self,
        padding,
        mode='constant',
        value=0.0,
        data_format="NCDHW",
        name=None,
    ):
1277
        super().__init__()
1278
        self._pad = _npairs(padding, 3)
L
littletomatodonkey 已提交
1279
        self._mode = mode
L
littletomatodonkey 已提交
1280 1281 1282 1283 1284
        self._value = value
        self._data_format = data_format
        self._name = name

    def forward(self, x):
1285 1286 1287 1288 1289 1290 1291 1292
        return F.pad(
            x,
            pad=self._pad,
            mode=self._mode,
            value=self._value,
            data_format=self._data_format,
            name=self._name,
        )
L
littletomatodonkey 已提交
1293

1294 1295 1296
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'padding={}, mode={}, value={}, data_format={}{}'.format(
1297 1298
            self._pad, self._mode, self._value, self._data_format, name_str
        )
1299

L
littletomatodonkey 已提交
1300

Z
zhiboniu 已提交
1301
class CosineSimilarity(Layer):
L
littletomatodonkey 已提交
1302
    """
1303
    This interface is used to compute cosine similarity between x1 and x2 along axis.
L
littletomatodonkey 已提交
1304 1305

    Parameters:
1306
        axis (int): Dimension of vectors to compute cosine similarity. Default is 1.
L
littletomatodonkey 已提交
1307
        eps(float): Small value to avoid division by zero. Default is 1e-8.
1308
    Returns:
L
littletomatodonkey 已提交
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
        None

    Examples:
        .. code-block:: text

            Case 0:
                x1 = [[0.8024077  0.9927354  0.27238318 0.8344984 ]
                     [0.48949873 0.5797396  0.65444374 0.66510963]
                     [0.1031398  0.9614342  0.08365563 0.6796464 ]
                     [0.10760343 0.7461209  0.7726148  0.5801006 ]]
                x2 = [[0.62913156 0.1536727  0.9847992  0.04591406]
                     [0.9098952  0.15715368 0.8671125  0.3156102 ]
                     [0.4427798  0.54136837 0.5276275  0.32394758]
                     [0.3769419  0.8535014  0.48041078 0.9256797 ]]
1323
                axis = 1
L
littletomatodonkey 已提交
1324 1325 1326 1327 1328
                eps = 1e-8
                Out: [0.5275037  0.8368967  0.75037485 0.9245899]

    Code Examples:
        .. code-block:: python
1329

L
littletomatodonkey 已提交
1330 1331 1332
            import paddle
            import paddle.nn as nn

1333 1334 1335 1336
            x1 = paddle.to_tensor([[1., 2., 3.],
                                [2., 3., 4.]], dtype="float32")
            x2 = paddle.to_tensor([[8., 3., 3.],
                                [2., 3., 4.]], dtype="float32")
L
littletomatodonkey 已提交
1337

1338
            cos_sim_func = nn.CosineSimilarity(axis=0)
L
littletomatodonkey 已提交
1339
            result = cos_sim_func(x1, x2)
L
littletomatodonkey 已提交
1340
            print(result)
1341 1342
            # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [0.65079135, 0.98058069, 1.        ])
L
littletomatodonkey 已提交
1343 1344
    """

1345
    def __init__(self, axis=1, eps=1e-8):
1346
        super().__init__()
1347
        self._axis = axis
L
littletomatodonkey 已提交
1348 1349 1350
        self._eps = eps

    def forward(self, x1, x2):
1351
        return F.cosine_similarity(x1, x2, axis=self._axis, eps=self._eps)
T
tangwei12 已提交
1352

1353 1354 1355
    def extra_repr(self):
        return 'axis={_axis}, eps={_eps}'.format(**self.__dict__)

T
tangwei12 已提交
1356

Z
zhiboniu 已提交
1357
class Embedding(Layer):
1358
    r"""
1359

1360
    Embedding Layer, used to construct a callable object of the ``Embedding`` class.
T
tangwei12 已提交
1361
    For specific usage, refer to code examples. It implements the function of the Embedding Layer.
T
tangwei12 已提交
1362
    This layer is used to lookup embeddings vector of ids provided by :attr:`x` .
T
tangwei12 已提交
1363
    It automatically constructs a 2D embedding matrix based on the
T
tangwei12 已提交
1364
    input :attr:`num_embeddings` and :attr:`embedding_dim`.
T
tangwei12 已提交
1365 1366 1367 1368

    The shape of output Tensor is generated by appending an emb_size dimension to the
    last dimension of the input Tensor shape.

1369 1370 1371
    Note:
        The id in :attr:`x` must satisfy :math:`0 =< id < num_embeddings` ,
        otherwise the program will throw an exception and exit.
T
tangwei12 已提交
1372 1373 1374 1375 1376

    .. code-block:: text

        Case 1:

T
tangwei12 已提交
1377 1378 1379
        x is a Tensor. padding_idx = -1
            x.data = [[1, 3], [2, 4], [4, 127]
            x.shape = [3, 2]
T
tangwei12 已提交
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
        Given size = [128, 16]
        output is a Tensor:
            out.shape = [3, 2, 16]
            out.data = [[[0.129435295, 0.244512452, ..., 0.436322452],
                        [0.345421456, 0.524563927, ..., 0.144534654]],

                        [[0.345249859, 0.124939536, ..., 0.194353745],
                        [0.945345345, 0.435394634, ..., 0.435345365]],

                        [[0.945345345, 0.435394634, ..., 0.435345365],
                        [0.0,         0.0,         ..., 0.0        ]]]  # padding data
        The input padding_idx is less than 0, it is automatically converted to padding_idx = -1 + 128 = 127
        It will pad all-zero data when ids is 127.

    Parameters:
        num_embeddings (int): Just one element which indicate the size
            of the dictionary of embeddings.
T
tangwei12 已提交
1397
        embedding_dim (int):  Just one element which indicate the size of each embedding vector respectively.
1398
        padding_idx(int|long|None, optional): padding_idx needs to be in the interval [-num_embeddings, num_embeddings).
T
tangwei12 已提交
1399 1400 1401 1402
            If :math:`padding\_idx < 0`, the :math:`padding\_idx` will automatically be converted
            to :math:`vocab\_size + padding\_idx` . It will output all-zero padding data whenever lookup
            encounters :math:`padding\_idx` in id. And the padding data will not be updated while training.
            If set None, it makes no effect to output. Default: None.
1403
        sparse(bool, optional): The flag indicating whether to use sparse update. This parameter only
T
tangwei12 已提交
1404 1405
            affects the performance of the backwards gradient update. It is recommended to set
            True because sparse update is faster. But some optimizer does not support sparse update,
T
tangwei12 已提交
1406
            such as :ref:`api_paddle_optimizer_adadelta_Adadelta` , :ref:`api_paddle_optimizer_adamax_Adamax` , :ref:`api_paddle_optimizer_lamb_Lamb`.
T
tangwei12 已提交
1407
            In these case, sparse must be False. Default: False.
1408
        weight_attr(ParamAttr, optional): To specify the weight parameter property. Default: None, which means the
T
tangwei12 已提交
1409
            default weight parameter property is used. See usage for details in :ref:`api_ParamAttr` . In addition,
T
tangwei12 已提交
1410 1411
            user-defined or pre-trained word vectors can be loaded with the :attr:`param_attr` parameter.
            The local word vector needs to be transformed into numpy format, and the shape of local word
T
tangwei12 已提交
1412 1413
            vector should be consistent with :attr:`num_embeddings` . Then :ref:`api_initializer_NumpyArrayInitializer`
            is used to load custom or pre-trained word vectors. See code example for details.
1414
        name(str|None, optional): For detailed information, please refer
T
tangwei12 已提交
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
               to :ref:`api_guide_Name`. Usually name is no need to set and
               None by default.

    Attribute:
        **weight** (Parameter): the learnable weights of this layer.

    Returns:
        None

    Examples:

        .. code-block:: python

T
tangwei12 已提交
1428 1429
            import paddle

1430 1431
            x = paddle.to_tensor([[0], [1], [3]], dtype="int64", stop_gradient=False)
            embedding = paddle.nn.Embedding(4, 3, sparse=True)
T
tangwei12 已提交
1432

1433 1434 1435 1436
            w0 = paddle.to_tensor([[0., 0., 0.],
                                [1., 1., 1.],
                                [2., 2., 2.],
                                [3., 3., 3.]], dtype="float32")
T
tangwei12 已提交
1437
            embedding.weight.set_value(w0)
1438 1439 1440 1441 1442 1443
            print(embedding.weight)
            # Tensor(shape=[4, 3], dtype=float32, place=Place(gpu:0), stop_gradient=False,
            #        [[0., 0., 0.],
            #         [1., 1., 1.],
            #         [2., 2., 2.],
            #         [3., 3., 3.]])
T
tangwei12 已提交
1444

T
tangwei12 已提交
1445 1446 1447 1448
            adam = paddle.optimizer.Adam(parameters=[embedding.weight], learning_rate=0.01)
            adam.clear_grad()


1449 1450 1451 1452 1453 1454
            out = embedding(x)
            print(out)
            # Tensor(shape=[3, 1, 3], dtype=float32, place=Place(gpu:0), stop_gradient=False,
            #        [[[0., 0., 0.]],
            #         [[1., 1., 1.]],
            #         [[3., 3., 3.]]])
T
tangwei12 已提交
1455 1456 1457

            out.backward()
            adam.step()
T
tangwei12 已提交
1458 1459 1460

    """

1461 1462 1463 1464 1465 1466 1467 1468 1469
    def __init__(
        self,
        num_embeddings,
        embedding_dim,
        padding_idx=None,
        sparse=False,
        weight_attr=None,
        name=None,
    ):
1470
        super().__init__()
T
tangwei12 已提交
1471 1472 1473 1474
        self._num_embeddings = num_embeddings
        self._embedding_dim = embedding_dim
        self._sparse = sparse
        self._is_distributed = False
1475
        self._padding_idx = padding_idx
T
tangwei12 已提交
1476 1477 1478 1479 1480 1481 1482

        if self._num_embeddings <= 0:
            raise ValueError("num_embeddings must be gather than 0")

        if self._embedding_dim <= 0:
            raise ValueError("embedding_dim must be gather than 0")

1483 1484 1485 1486 1487 1488 1489
        padding_idx = (
            -1
            if padding_idx is None
            else padding_idx
            if padding_idx >= 0
            else (num_embeddings + padding_idx)
        )
1490 1491

        if padding_idx >= num_embeddings or padding_idx < -num_embeddings:
1492 1493 1494 1495 1496
            raise ValueError(
                "padding_idx must be within [-{}, {})".format(
                    num_embeddings, num_embeddings
                )
            )
T
tangwei12 已提交
1497

T
tangwei12 已提交
1498 1499 1500 1501 1502 1503
        self._dtype = self._helper.get_default_dtype()
        self._size = [self._num_embeddings, self._embedding_dim]

        self._weight_attr = weight_attr
        self._remote_prefetch = False
        self._name = name
1504 1505 1506 1507 1508 1509
        self.weight = self.create_parameter(
            attr=self._weight_attr,
            shape=self._size,
            dtype=self._dtype,
            is_bias=False,
        )
T
tangwei12 已提交
1510

Z
zhiboniu 已提交
1511
        if in_dynamic_mode() and padding_idx != -1:
1512 1513
            with paddle.no_grad():
                self.weight[padding_idx] = 0.0
T
tangwei12 已提交
1514

T
tangwei12 已提交
1515
    def forward(self, x):
1516 1517 1518 1519 1520 1521 1522
        return F.embedding(
            x,
            weight=self.weight,
            padding_idx=self._padding_idx,
            sparse=self._sparse,
            name=self._name,
        )
1523 1524 1525 1526 1527 1528 1529 1530 1531

    def extra_repr(self):
        main_str = '{_num_embeddings}, {_embedding_dim}'
        if self._padding_idx is not None:
            main_str += ', padding_idx={_padding_idx}'
        main_str += ', sparse={_sparse}'
        if self._name is not None:
            main_str += ', name={_name}'
        return main_str.format(**self.__dict__)
F
FNRE 已提交
1532 1533


Z
zhiboniu 已提交
1534
class Unfold(Layer):
F
FNRE 已提交
1535
    """
1536
    Returns a col buffer of sliding local blocks of input x, also known
F
FNRE 已提交
1537 1538 1539 1540 1541 1542 1543 1544 1545
    as im2col for batched 2D image tensors. For each block under the convolution filter,
    all element will be rearranged as a column. While the convolution filter sliding over
    the input feature map, a series of such columns will be formed.

    For each input :math:`x` with shape [N, C, H, W], the output shape [N, Cout, Lout]
    can be calculated as following.

    See ``paddle.nn.functional.unfold`` for more details.

1546

F
FNRE 已提交
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
    Parameters:
        kernel_sizes(int|list):   The size of convolution kernel, should be [k_h, k_w]
                                  or an integer k treated as [k, k].
        strides(int|list):        The strides, should be [stride_h, stride_w]
                                  or an integer stride treated as [sride, stride].
                                  For default, strides will be [1, 1].
        paddings(int|list):       The paddings of each dimension, should be
                                  [padding_top, padding_left, padding_bottom, padding_right]
                                  or [padding_h, padding_w] or an integer padding.
                                  If [padding_h, padding_w] was given, it will expanded to
                                  [padding_h, padding_w, padding_h, padding_w]. If an integer
                                  padding was given, [padding, padding, padding, padding] will
                                  be used. For default, paddings will be [0, 0, 0, 0]
        dilations(int|list):      the dilations of convolution kernel, should be
                                  [dilation_h, dilation_w], or an integer dilation treated as
                                  [dilation, dilation]. For default, it will be [1, 1].
        name(str, optional): The default value is None.
                             Normally there is no need for user to set this property.
                             For more information, please refer to :ref:`api_guide_Name`


    Examples:
        .. code-block:: python

            import paddle
            import paddle.nn as nn

            x = paddle.randn((100,3,224,224))
            unfold = nn.Unfold(kernel_sizes=[3, 3])
            result = unfold(x)
            print(result)
X
xiaoting 已提交
1578
    """
F
FNRE 已提交
1579

1580 1581 1582
    def __init__(
        self, kernel_sizes, dilations=1, paddings=0, strides=1, name=None
    ):
1583
        super().__init__()
F
FNRE 已提交
1584 1585 1586 1587 1588 1589 1590 1591

        self.kernel_sizes = kernel_sizes
        self.dilations = dilations
        self.paddings = paddings
        self.strides = strides
        self.name = name

    def forward(self, input):
1592 1593 1594 1595 1596 1597 1598 1599
        return F.unfold(
            input,
            kernel_sizes=self.kernel_sizes,
            strides=self.strides,
            paddings=self.paddings,
            dilations=self.dilations,
            name=self.name,
        )
F
FNRE 已提交
1600 1601 1602

    def extra_repr(self):
        name_str = ', name={}'.format(self.name) if self.name else ''
1603 1604 1605 1606 1607 1608 1609
        return 'kernel_size={}, dilation={}, padding={}, stride={}{}'.format(
            self.kernel_sizes,
            self.dilations,
            self.paddings,
            self.strides,
            name_str,
        )
X
xiaoting 已提交
1610 1611 1612


class Fold(Layer):
1613
    r"""
X
xiaoting 已提交
1614

1615
    Combines an array of sliding local blocks into a large containing
1616 1617
    tensor. also known as col2im when operated on batched 2D image tensor. Fold calculates each
    combined value in the resulting large tensor by summing all values from all containing blocks.
X
xiaoting 已提交
1618 1619 1620 1621 1622 1623


    For each input :math:`x` with shape [N, C_in , L], the output shape [N, C_out, H_out, W_out]
    can be calculated as following.

    .. math::
1624

1625 1626 1627
        H_{out} &= output\_size[0] \\
        W_{out} &= output\_size[1] \\
        C_{out} &= \frac{C_{in}}{kernel\_sizes[0]\times kernel\_sizes[1]} \\
X
xiaoting 已提交
1628 1629 1630 1631

    Parameters:
        output_sizes(list):       The size of output size, should be [output_size_h, output_size_w]
                                  or an interger o treated as [o, o].
X
xiaoting 已提交
1632
        kernel_sizes(int|list|tuple):   The size of convolution kernel, should be [k_h, k_w]
X
xiaoting 已提交
1633
                                  or an integer k treated as [k, k].
1634
        strides(int|list|tuple, optional):        The strides, should be [stride_h, stride_w]
X
xiaoting 已提交
1635 1636
                                  or an integer stride treated as [sride, stride].
                                  For default, strides will be [1, 1].
1637
        paddings(int|list|tuple, optional):       The paddings of each dimension, should be
X
xiaoting 已提交
1638 1639 1640 1641 1642 1643
                                  [padding_top, padding_left, padding_bottom, padding_right]
                                  or [padding_h, padding_w] or an integer padding.
                                  If [padding_h, padding_w] was given, it will expanded to
                                  [padding_h, padding_w, padding_h, padding_w]. If an integer
                                  padding was given, [padding, padding, padding, padding] will
                                  be used. For default, paddings will be [0, 0, 0, 0]
1644
        dilations(int|list|tuple, optional):      the dilations of convolution kernel, should be
X
xiaoting 已提交
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
                                  [dilation_h, dilation_w], or an integer dilation treated as
                                  [dilation, dilation]. For default, it will be [1, 1].
        name(str, optional): The default value is None.
                             Normally there is no need for user to set this property.
                             For more information, please refer to :ref:`api_guide_Name`


    Returns:
        The tensor formed by combining a group of sliding local blocks
        The output shape is [N, Cout, H, W] as decriabled above.

    Examples:

        .. code-block:: python

            import paddle
            import paddle.nn as nn

X
xiaoting 已提交
1663 1664
            x = paddle.randn([2,3*2*2,12])
            fold = nn.Fold(output_sizes=[4, 5], kernel_sizes=2)
X
xiaoting 已提交
1665
            y = fold(x)
X
xiaoting 已提交
1666
            # y.shape = [2,3,4,5]
X
xiaoting 已提交
1667 1668
   """

1669 1670 1671 1672 1673 1674 1675 1676 1677
    def __init__(
        self,
        output_sizes,
        kernel_sizes,
        dilations=1,
        paddings=0,
        strides=1,
        name=None,
    ):
1678
        super().__init__()
X
xiaoting 已提交
1679 1680 1681 1682 1683 1684 1685 1686 1687

        self.output_sizes = output_sizes
        self.kernel_sizes = kernel_sizes
        self.dilations = dilations
        self.paddings = paddings
        self.strides = strides
        self.name = name

    def forward(self, input):
1688 1689 1690 1691 1692 1693 1694 1695 1696
        return F.fold(
            input,
            output_sizes=self.output_sizes,
            kernel_sizes=self.kernel_sizes,
            strides=self.strides,
            paddings=self.paddings,
            dilations=self.dilations,
            name=self.name,
        )
X
xiaoting 已提交
1697 1698 1699

    def extra_repr(self):
        name_str = ', name={}'.format(self.name) if self.name else ''
1700 1701 1702 1703 1704 1705 1706
        return 'kernel_size={}, dilation={}, padding={}, stride={}{}'.format(
            self.kernel_sizes,
            self.dilations,
            self.paddings,
            self.strides,
            name_str,
        )
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739


class Flatten(Layer):
    """
    This interface is used to construct a callable object of the ``FLatten`` class.
    For more details, refer to code examples.
    It implements flatten a contiguous range of dims into a tensor.

    Parameters:
        start_axis(int): first dim to flatten (default = 1)
        stop_axis(int): last dim to flatten (default = -1).

    Returns:
        None

    Examples:

        .. code-block:: python

          import paddle

          inp = paddle.ones([5, 2, 3, 4]).astype('float32')
          flatten = paddle.nn.Flatten(start_axis=1, stop_axis=2)
          y = flatten(inp)
          # y.shape = [5, 6, 4]

    """

    def __init__(self, start_axis=1, stop_axis=-1):
        super().__init__()
        self.start_axis = start_axis
        self.stop_axis = stop_axis

1740
    def forward(self, input):
1741
        out = paddle.flatten(
1742
            input, start_axis=self.start_axis, stop_axis=self.stop_axis
1743 1744
        )
        return out