-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
Copy pathpooling.py
executable file
·2097 lines (1838 loc) · 80.9 KB
/
pooling.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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.
import numpy as np
from paddle import _C_ops, _legacy_C_ops, in_dynamic_mode
from paddle.base.framework import Variable, in_dygraph_mode
from ...base.data_feeder import check_type, check_variable_and_dtype
from ...base.layers import LayerHelper
from ...tensor.manipulation import squeeze, unsqueeze
# TODO: define pooling functions
from ...utils import (
_contain_var,
_convert_to_tensor_list,
_is_symmetric_padding,
convert_to_list,
)
__all__ = []
def _is_list_or_tuple(input):
return isinstance(input, (list, tuple))
def _check_input(x, dimension):
if len(x.shape) != dimension:
raise ValueError(
"Excepted Input X is {}-D tensor, but received {}-D {}".format(
dimension, len(x.shape), type(x)
)
)
def _check_instance(x, x_name, types=(int, float)):
if not isinstance(x, types):
raise ValueError(
"Excepted {} type for {} but received type: {}. ".format(
types, x_name, type(x)
)
)
def _check_value_limitation(x, x_name, min_limit=1e-3):
def _check_value(x, x_name, min_limit=1e-3):
if isinstance(x, int) and min_limit is not None and x < min_limit:
raise ValueError(
"Excepted the input {} to be greater than {} but received x: {}. ".format(
x_name, min_limit, x
)
)
for ele in x:
_check_value(ele, x_name)
def _zero_padding_in_batch_and_channel(padding, channel_last):
if channel_last:
return list(padding[0]) == [0, 0] and list(padding[-1]) == [0, 0]
else:
return list(padding[0]) == [0, 0] and list(padding[1]) == [0, 0]
def _exclude_padding_in_batch_and_channel(padding, channel_last):
padding_ = padding[1:-1] if channel_last else padding[2:]
padding_ = [elem for pad_a_dim in padding_ for elem in pad_a_dim]
return padding_
def _channel_last(data_format, num_dims):
if num_dims == 1:
if data_format not in ['NCL', 'NLC']:
raise ValueError(
"Attr(data_format) should be 'NCL' or 'NLC'. Received "
"Attr(data_format): %s" % str(data_format)
)
else:
return True if data_format == "NLC" else False
if num_dims == 2:
if data_format not in ['NCHW', 'NHWC']:
raise ValueError(
"Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
"Attr(data_format): %s" % str(data_format)
)
else:
return True if data_format == "NHWC" else False
if num_dims == 3:
if data_format not in ['NCDHW', 'NDHWC']:
raise ValueError(
"Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received "
"Attr(data_format): %s" % str(data_format)
)
else:
return True if data_format == "NDHWC" else False
def _update_padding_nd(padding, num_dims, channel_last=False, ceil_mode=False):
if isinstance(padding, str):
padding = padding.upper()
if padding not in ["SAME", "VALID"]:
raise ValueError(
"Unknown padding: '{}'. It can only be 'SAME' or 'VALID'.".format(
padding
)
)
if padding == "VALID":
if ceil_mode is not False:
raise ValueError(
"When Attr(padding) is \"VALID\", Attr(ceil_mode) must be False. "
"Received ceil_mode: True."
)
padding_algorithm = "VALID"
padding = [0] * num_dims
else:
padding_algorithm = "SAME"
padding = [0] * num_dims
elif _is_list_or_tuple(padding):
# for padding like
# [(pad_before, pad_after), (pad_before, pad_after), ...]
# padding for batch_dim and channel_dim included
if len(padding) == 2 + num_dims and _is_list_or_tuple(padding[0]):
if not _zero_padding_in_batch_and_channel(padding, channel_last):
raise ValueError(
"Non-zero padding({}) in the batch or channel dimensions "
"is not supported.".format(padding)
)
padding_algorithm = "EXPLICIT"
padding = _exclude_padding_in_batch_and_channel(
padding, channel_last
)
if _is_symmetric_padding(padding, num_dims):
padding = padding[0::2]
# for padding like [pad_before, pad_after, pad_before, pad_after, ...]
elif len(padding) == 2 * num_dims and isinstance(padding[0], int):
padding_algorithm = "EXPLICIT"
padding = convert_to_list(padding, 2 * num_dims, 'padding')
if _is_symmetric_padding(padding, num_dims):
padding = padding[0::2]
# for padding like [pad_d1, pad_d2, ...]
elif len(padding) == num_dims and isinstance(padding[0], int):
padding_algorithm = "EXPLICIT"
padding = convert_to_list(padding, num_dims, 'padding')
else:
raise ValueError(f"Invalid padding: {padding}")
# for integer padding
else:
padding_algorithm = "EXPLICIT"
padding = convert_to_list(padding, num_dims, 'padding')
return padding, padding_algorithm
def _expand_low_nd_padding(padding):
# 1d to 2d fake input
if len(padding) == 2:
padding = [0] * 2 + padding
elif len(padding) == 1:
padding = [0] + padding
else:
raise ValueError(
"The size of padding's dimmention should be 1 or 2. But got padding={}".format(
padding
)
)
return padding
def avg_pool1d(
x,
kernel_size,
stride=None,
padding=0,
exclusive=True,
ceil_mode=False,
name=None,
):
"""
This API implements average pooling 1d operation,
See more details in :ref:`api_nn_pooling_AvgPool1d` .
Args:
x (Tensor): The input tensor of pooling operator which is a 3-D tensor with
shape [N, C, L]. where `N` is batch size, `C` is the number of channels,
`L` is the length of the feature. The data type is float16, float32 or float64.
kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
it must contain an integer.
stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
it must contain an integer.
padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
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.
exclusive (bool): Whether to exclude padding points in average pooling
mode, default is `True`.
ceil_mode (bool): ${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 detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Tensor: The output tensor of pooling result. The data type is same as input tensor.
Examples:
.. code-block:: python
>>> import paddle
>>> import paddle.nn as nn
>>> data = paddle.uniform([1, 3, 32], paddle.float32)
>>> AvgPool1D = nn.AvgPool1D(kernel_size=2, stride=2, padding=0)
>>> pool_out = AvgPool1D(data)
>>> print(pool_out.shape)
[1, 3, 16]
"""
"""NCL to NCHW"""
data_format = "NCHW"
if not in_dynamic_mode():
check_variable_and_dtype(
x, 'x', ['float16', 'float32', 'float64'], 'avg_pool1d'
)
_check_input(x, 3)
x = unsqueeze(x, [2])
kernel_size = convert_to_list(kernel_size, 1, 'kernel_size')
kernel_size = [1] + kernel_size
if stride is None:
stride = kernel_size
else:
stride = convert_to_list(stride, 1, 'pool_stride')
stride = [1] + stride
_check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3)
_check_value_limitation(stride, "stride", min_limit=1e-3)
channel_last = _channel_last("NCL", 1)
padding, padding_algorithm = _update_padding_nd(
padding, 1, channel_last=channel_last, ceil_mode=ceil_mode
)
# use 2d to implenment 1d should expand padding in advance.
padding = _expand_low_nd_padding(padding)
if in_dygraph_mode():
output = _C_ops.pool2d(
x,
kernel_size,
stride,
padding,
ceil_mode,
exclusive,
data_format,
'avg',
False,
False,
padding_algorithm,
)
return squeeze(output, [2])
else:
op_type = 'pool2d'
helper = LayerHelper(op_type, **locals())
dtype = helper.input_dtype(input_param_name='x')
pool_out = helper.create_variable_for_type_inference(dtype)
helper.append_op(
type=op_type,
inputs={"X": x},
outputs={"Out": pool_out},
attrs={
"pooling_type": 'avg',
"ksize": kernel_size,
"global_pooling": False,
"strides": stride,
"paddings": padding,
"padding_algorithm": padding_algorithm,
"use_cudnn": True,
"ceil_mode": ceil_mode,
"use_mkldnn": False,
"exclusive": exclusive,
"data_format": data_format,
},
)
return squeeze(pool_out, [2])
def avg_pool2d(
x,
kernel_size,
stride=None,
padding=0,
ceil_mode=False,
exclusive=True,
divisor_override=None,
data_format="NCHW",
name=None,
):
"""
This API implements average pooling 2d operation.
See more details in :ref:`api_nn_pooling_AvgPool2d` .
Args:
x (Tensor): The input tensor of pooling operator which is a 4-D tensor with
shape [N, C, H, W]. The format of input tensor is `"NCHW"` or
`"NHWC"`, 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. The data type if float32 or float64.
kernel_size (int|list|tuple): The pool kernel size. If it is a tuple or list,
it must contain two integers, (kernel_size_Height, kernel_size_Width).
Otherwise, the pool kernel size will be a square of an int.
stride (int|list|tuple): The stride size. If it is a tuple or list,
it must contain two integers, (stride_Height, stride_Width).
Otherwise, the stride size will be a square of an int.
padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
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.
ceil_mode (bool): when True, will use `ceil` instead of `floor` to compute the output shape
exclusive (bool): Whether to exclude padding points in average pooling
mode, default is `true`.
divisor_override (float): if specified, it will be used as divisor, otherwise kernel_size will be used. Default None.
data_format (string): The data format of the input and output data. An optional string 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]`.
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:
Tensor: The output tensor of pooling result. The data type is same as input tensor.
Examples:
.. code-block:: python
>>> import paddle
>>> import paddle.nn.functional as F
>>> # avg pool2d
>>> x = paddle.uniform([1, 3, 32, 32], paddle.float32)
>>> out = F.avg_pool2d(x,
... kernel_size=2,
... stride=2, padding=0)
>>> print(out.shape)
[1, 3, 16, 16]
"""
kernel_size = convert_to_list(kernel_size, 2, 'pool_size')
if stride is None:
stride = kernel_size
else:
stride = convert_to_list(stride, 2, 'pool_stride')
_check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3)
_check_value_limitation(stride, "stride", min_limit=1e-3)
channel_last = _channel_last(data_format, 2)
padding, padding_algorithm = _update_padding_nd(
padding, 2, channel_last, ceil_mode=ceil_mode
)
if in_dygraph_mode():
output = _C_ops.pool2d(
x,
kernel_size,
stride,
padding,
ceil_mode,
exclusive,
data_format,
'avg',
False,
False,
padding_algorithm,
)
if divisor_override is None:
return output
else:
_check_instance(divisor_override, "divisor_override")
return output * (kernel_size[0] * kernel_size[1]) / divisor_override
else:
op_type = 'pool2d'
helper = LayerHelper(op_type, **locals())
check_variable_and_dtype(
x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'avg_pool2d'
)
dtype = helper.input_dtype(input_param_name='x')
pool_out = helper.create_variable_for_type_inference(dtype)
helper.append_op(
type=op_type,
inputs={"X": x},
outputs={"Out": pool_out},
attrs={
"pooling_type": "avg",
"ksize": kernel_size,
"global_pooling": False,
"strides": stride,
"paddings": padding,
"padding_algorithm": padding_algorithm,
"use_cudnn": True,
"ceil_mode": ceil_mode,
"use_mkldnn": False,
"exclusive": exclusive,
"data_format": data_format,
},
)
if divisor_override is None:
return pool_out
else:
_check_instance(divisor_override, "divisor_override")
return (
pool_out * (kernel_size[0] * kernel_size[1]) / divisor_override
)
def avg_pool3d(
x,
kernel_size,
stride=None,
padding=0,
ceil_mode=False,
exclusive=True,
divisor_override=None,
data_format="NCDHW",
name=None,
):
"""
This API implements average pooling 3d operation.
See more details in :ref:`api_nn_pooling_AvgPool3d` .
Args:
x (Tensor): The input tensor of pooling operator, which is a 5-D tensor with
shape [N, C, D, H, W], where `N` represents the batch size, `C` represents
the number of channels, `D`, `H` and `W` represent the depth, height and width of the feature respectively.
kernel_size (int|list|tuple): The pool kernel size. If pool kernel size
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.
stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
it must contain three integers, [stride_Depth, stride_Height, stride_Width).
Otherwise, the pool stride size will be a cube of an int.
padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
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.
ceil_mode (bool): ${ceil_mode_comment}
exclusive (bool): Whether to exclude padding points in average pooling
mode, default is True.
divisor_override (int|float) if specified, it will be used as divisor, otherwise kernel_size will be used. Default None.
data_format (string): 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.
Returns:
Tensor: The output tensor of pooling result. The data type is same as input tensor.
Examples:
.. code-block:: python
>>> import paddle
>>> x = paddle.uniform([1, 3, 32, 32, 32], paddle.float32)
>>> # avg pool3d
>>> out = paddle.nn.functional.avg_pool3d(x,
... kernel_size = 2,
... stride = 2,
... padding=0)
>>> print(out.shape)
[1, 3, 16, 16, 16]
"""
kernel_size = convert_to_list(kernel_size, 3, 'pool_size')
if stride is None:
stride = kernel_size
else:
stride = convert_to_list(stride, 3, 'pool_stride')
channel_last = _channel_last(data_format, 3)
padding, padding_algorithm = _update_padding_nd(
padding, 3, channel_last=channel_last, ceil_mode=ceil_mode
)
_check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3)
_check_value_limitation(stride, "stride", min_limit=1e-3)
if in_dygraph_mode():
pool_out = _C_ops.pool3d(
x,
kernel_size,
stride,
padding,
ceil_mode,
exclusive,
data_format,
'avg',
False,
False,
padding_algorithm,
)
else:
op_type = "pool3d"
helper = LayerHelper(op_type, **locals())
check_variable_and_dtype(
x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'avg_pool3d'
)
dtype = helper.input_dtype(input_param_name='x')
pool_out = helper.create_variable_for_type_inference(dtype)
outputs = {"Out": pool_out}
helper.append_op(
type=op_type,
inputs={"X": x},
outputs=outputs,
attrs={
"pooling_type": 'avg',
"ksize": kernel_size,
"global_pooling": False,
"strides": stride,
"paddings": padding,
"padding_algorithm": padding_algorithm,
"use_cudnn": True,
"ceil_mode": ceil_mode,
"use_mkldnn": False,
"exclusive": exclusive,
"data_format": data_format,
},
)
if divisor_override is None:
return pool_out
else:
_check_instance(divisor_override, "divisor_override")
return (
pool_out
* (kernel_size[0] * kernel_size[1] * kernel_size[2])
/ divisor_override
)
def max_pool1d(
x,
kernel_size,
stride=None,
padding=0,
return_mask=False,
ceil_mode=False,
name=None,
):
"""
This API implements max pooling 1d opereation.
See more details in :ref:`api_nn_pooling_MaxPool1d` .
Args:
x (Tensor): The input tensor of pooling operator which is a 3-D tensor with
shape [N, C, L], where `N` is batch size, `C` is the number of channels,
`L` is the length of the feature. The data type if float32 or float64.
kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
it must contain an integer.
stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
it must contain an integer.
padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
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.
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.
return_mask (bool): Whether return the max indices along with the outputs. default is `False`.
ceil_mode (bool): 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.
Returns:
Tensor: The output tensor of pooling result. The data type is same as input tensor.
Examples:
.. code-block:: python
>>> import paddle
>>> import paddle.nn.functional as F
>>> data = paddle.uniform([1, 3, 32], paddle.float32)
>>> pool_out = F.max_pool1d(data, kernel_size=2, stride=2, padding=0)
>>> print(pool_out.shape)
[1, 3, 16]
>>> pool_out, indices = F.max_pool1d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
>>> print(pool_out.shape)
[1, 3, 16]
>>> print(indices.shape)
[1, 3, 16]
"""
"""NCL to NCHW"""
data_format = "NCHW"
_check_input(x, 3)
x = unsqueeze(x, [2])
kernel_size = [1] + convert_to_list(kernel_size, 1, 'pool_size')
if stride is None:
stride = kernel_size
else:
stride = [1] + convert_to_list(stride, 1, 'pool_stride')
padding, padding_algorithm = _update_padding_nd(
padding, 1, ceil_mode=ceil_mode
)
# use 2d to implenment 1d should expand padding in advance.
padding = _expand_low_nd_padding(padding)
if in_dygraph_mode():
if return_mask:
pool_out = _C_ops.max_pool2d_with_index(
x, kernel_size, stride, padding, False, False
)
return (
(squeeze(pool_out[0], [2]), squeeze(pool_out[1], [2]))
if return_mask
else squeeze(pool_out[0], [2])
)
else:
pool_out = _C_ops.pool2d(
x,
kernel_size,
stride,
padding,
ceil_mode,
True,
data_format,
'max',
False,
False,
padding_algorithm,
)
return squeeze(pool_out, [2])
else:
check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool1d')
op_type = 'max_pool2d_with_index' if return_mask else "pool2d"
helper = LayerHelper(op_type, **locals())
dtype = helper.input_dtype(input_param_name='x')
pool_out = helper.create_variable_for_type_inference(dtype)
mask = helper.create_variable_for_type_inference('int32')
outputs = {"Out": pool_out, "Mask": mask}
helper.append_op(
type=op_type,
inputs={"X": x},
outputs=outputs,
attrs={
"pooling_type": 'max',
"ksize": kernel_size,
"global_pooling": False,
"strides": stride,
"paddings": padding,
"padding_algorithm": padding_algorithm,
"use_cudnn": True,
"ceil_mode": ceil_mode,
"use_mkldnn": False,
"exclusive": True,
"data_format": data_format,
},
)
return (
(squeeze(pool_out, [2]), squeeze(mask, [2]))
if return_mask
else squeeze(pool_out, [2])
)
def _unpool_output_size(x, kernel_size, stride, padding, output_size):
assert output_size is None or isinstance(output_size, (list, tuple)), (
"Required output_size is None|list|tuple, but received %s" % output_size
)
input_size = x.shape
default_size = []
for d in range(len(kernel_size)):
default_size.append(
(input_size[-len(kernel_size) + d] - 1) * stride[d]
+ kernel_size[d]
- 2 * padding[d]
)
has_static_var = False
if output_size is None:
return default_size
elif _contain_var(output_size):
if not in_dygraph_mode():
has_static_var = True
output_size = _convert_to_tensor_list(output_size)
else:
for i, var in enumerate(output_size):
if isinstance(var, Variable):
output_size[i] = np.array(var).item()
if len(output_size) == len(kernel_size) + 2:
output_size = output_size[2:]
if len(output_size) != len(kernel_size):
raise ValueError(
"output_size should be a sequence containing "
"{} or {} elements, but it has a length of '{}'".format(
len(kernel_size), len(kernel_size) + 2, len(output_size)
)
)
if not has_static_var:
for d in range(len(kernel_size)):
min_size = default_size[d] - stride[d]
max_size = default_size[d] + stride[d]
if not (min_size < output_size[d] < max_size):
raise ValueError(
'invalid output_size "{}" (dim {} must be between {} and {})'.format(
output_size, d, min_size, max_size
)
)
return output_size
def max_unpool1d(
x,
indices,
kernel_size,
stride=None,
padding=0,
data_format="NCL",
output_size=None,
name=None,
):
r"""
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.
Args:
x (Tensor): The input tensor of unpooling operator which is a 3-D tensor with
shape [N, C, L]. The format of input tensor is `"NCL"`,
where `N` is batch size, `C` is the number of channels, `L` is
the length of the feature. The data type is float32 or float64.
indices (Tensor): The indices given out by maxpooling1d which is a 3-D tensor with
shape [N, C, L]. The format of input tensor is `"NCL"` ,
where `N` is batch size, `C` is the number of channels, `L` is
the length of the featuree. The data type is float32 or float64.
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:
Tensor: The output tensor of unpooling result.
Examples:
.. code-block:: python
>>> import paddle
>>> import paddle.nn.functional as F
>>> data = paddle.rand(shape=[1, 3, 16])
>>> pool_out, indices = F.max_pool1d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
>>> print(pool_out.shape)
[1, 3, 8]
>>> print(indices.shape)
[1, 3, 8]
>>> unpool_out = F.max_unpool1d(pool_out, indices, kernel_size=2, padding=0)
>>> print(unpool_out.shape)
[1, 3, 16]
"""
"""NCL to NCHW"""
if data_format not in ["NCL"]:
raise ValueError(
"Attr(data_format) should be 'NCL'. Received "
"Attr(data_format): %s." % str(data_format)
)
data_format = "NCHW"
x = unsqueeze(x, [2])
indices = unsqueeze(indices, [2])
kernel_size = [1] + convert_to_list(kernel_size, 1, 'pool_size')
if stride is None:
stride = kernel_size
else:
stride = [1] + convert_to_list(stride, 1, 'pool_stride')
padding, padding_algorithm = _update_padding_nd(padding, 1)
# use 2d to implenment 1d should expand padding in advance.
padding = _expand_low_nd_padding(padding)
output_size = _unpool_output_size(
x, kernel_size, stride, padding, output_size
)
if in_dygraph_mode():
output = _C_ops.unpool(
x, indices, kernel_size, stride, padding, output_size, data_format
)
return squeeze(output, [2])
elif in_dynamic_mode():
output = _legacy_C_ops.unpool(
x,
indices,
'unpooling_type',
'max',
'ksize',
kernel_size,
'strides',
stride,
'paddings',
padding,
"output_size",
output_size,
"data_format",
data_format,
)
return squeeze(output, [2])
op_type = "unpool"
helper = LayerHelper(op_type, **locals())
dtype = helper.input_dtype(input_param_name="x")
unpool_out = helper.create_variable_for_type_inference(dtype)
helper.append_op(
type=op_type,
inputs={"X": x, "Indices": indices},
outputs={"Out": unpool_out},
attrs={
"unpooling_type": "max",
"ksize": kernel_size,
"strides": stride,
"paddings": padding,
"output_size": output_size,
},
)
return squeeze(unpool_out, [2])
def max_unpool2d(
x,
indices,
kernel_size,
stride=None,
padding=0,
data_format="NCHW",
output_size=None,
name=None,
):
r"""
This API implements max unpooling 2d opereation.
See more details in :ref:`api_nn_pooling_MaxUnPool2D` .
Args:
x (Tensor): The input tensor of unpooling operator which is a 4-D tensor with
shape [N, C, H, W]. The format of input tensor is `"NCHW"`,
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. The data type if float32 or float64.
indices (Tensor): The indices given out by maxpooling2d which is a 4-D tensor with
shape [N, C, H, W]. The format of input tensor is `"NCHW"` ,
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. The data type if float32 or float64.
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, 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:
Tensor: The output tensor of unpooling result.
Raises:
ValueError: If the input is not a 4-D tensor.
ValueError: If indeces shape is not equal input shape.
Examples:
.. code-block:: python
>>> import paddle
>>> import paddle.nn.functional as F
>>> data = paddle.rand(shape=[1, 1, 6, 6])
>>> pool_out, indices = F.max_pool2d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
>>> print(pool_out.shape)
[1, 1, 3, 3]
>>> print(indices.shape)
[1, 1, 3, 3]
>>> unpool_out = F.max_unpool2d(pool_out, indices, kernel_size=2, padding=0)
>>> print(unpool_out.shape)
[1, 1, 6, 6]
>>> # specify a different output size than input size
>>> unpool_out = F.max_unpool2d(pool_out, indices, kernel_size=2, padding=0, output_size=[7, 7])
>>> print(unpool_out.shape)
[1, 1, 7, 7]
"""
if x.ndim != 4:
raise ValueError(
f'The x should have [N, C, H, W] format, but received {x.shape}.'
)
if indices.ndim != 4:
raise ValueError(
f'The indices should have [N, C, H, W] format, but received {indices.shape}.'
)
kernel_size = convert_to_list(kernel_size, 2, 'pool_size')
if stride is None:
stride = kernel_size
else:
stride = convert_to_list(stride, 2, 'pool_stride')
padding = convert_to_list(padding, 2, 'padding')
if data_format not in ["NCHW"]:
raise ValueError(
"Attr(data_format) should be 'NCHW'. Received "
"Attr(data_format): %s." % str(data_format)
)
output_size = _unpool_output_size(
x, kernel_size, stride, padding, output_size
)
if in_dygraph_mode():
output = _C_ops.unpool(
x, indices, kernel_size, stride, padding, output_size, data_format
)
return output
elif in_dynamic_mode():
output = _legacy_C_ops.unpool(
x,
indices,
'unpooling_type',
'max',
'ksize',
kernel_size,
'strides',
stride,
'paddings',
padding,