You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

pooling.py 4.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. from abc import abstractmethod
  10. from typing import Tuple, Union
  11. from ..functional import avg_pool2d, max_pool2d
  12. from .module import Module
  13. class _PoolNd(Module):
  14. def __init__(
  15. self,
  16. kernel_size: Union[int, Tuple[int, int]],
  17. stride: Union[int, Tuple[int, int]] = None,
  18. padding: Union[int, Tuple[int, int]] = 0,
  19. **kwargs
  20. ):
  21. super(_PoolNd, self).__init__(**kwargs)
  22. self.kernel_size = kernel_size
  23. self.stride = stride or kernel_size
  24. self.padding = padding
  25. @abstractmethod
  26. def forward(self, inp):
  27. pass
  28. def _module_info_string(self) -> str:
  29. return "kernel_size={kernel_size}, stride={stride}, padding={padding}".format(
  30. **self.__dict__
  31. )
  32. class MaxPool2d(_PoolNd):
  33. r"""
  34. Applies a 2D max pooling over an input.
  35. For instance, given an input of the size :math:`(N, C, H, W)` and
  36. :attr:`kernel_size` :math:`(kH, kW)`, this layer generates the output of
  37. the size :math:`(N, C, H_{out}, W_{out})` through a process described as:
  38. .. math::
  39. \begin{aligned}
  40. out(N_i, C_j, h, w) ={} & \max_{m=0, \ldots, kH-1} \max_{n=0, \ldots, kW-1}
  41. \text{input}(N_i, C_j, \text{stride[0]} \times h + m,
  42. \text{stride[1]} \times w + n)
  43. \end{aligned}
  44. If :attr:`padding` is non-zero, then the input is implicitly zero-padded on
  45. both sides for :attr:`padding` number of points.
  46. :param kernel_size: the size of the window to take a max over.
  47. :param stride: the stride of the window. Default value is kernel_size.
  48. :param padding: implicit zero padding to be added on both sides.
  49. Examples:
  50. .. testcode::
  51. import numpy as np
  52. import megengine as mge
  53. import megengine.module as M
  54. m = M.MaxPool2d(kernel_size=3, stride=1, padding=0)
  55. inp = mge.tensor(np.arange(0, 16).astype("float32").reshape(1, 1, 4, 4))
  56. oup = m(inp)
  57. print(oup.numpy())
  58. Outputs:
  59. .. testoutput::
  60. [[[[10. 11.]
  61. [14. 15.]]]]
  62. """
  63. def forward(self, inp):
  64. return max_pool2d(inp, self.kernel_size, self.stride, self.padding)
  65. class AvgPool2d(_PoolNd):
  66. r"""
  67. Applies a 2D average pooling over an input.
  68. For instance, given an input of the size :math:`(N, C, H, W)` and
  69. :attr:`kernel_size` :math:`(kH, kW)`, this layer generates the output of
  70. the size :math:`(N, C, H_{out}, W_{out})` through a process described as:
  71. .. math::
  72. out(N_i, C_j, h, w) = \frac{1}{kH * kW} \sum_{m=0}^{kH-1} \sum_{n=0}^{kW-1}
  73. input(N_i, C_j, stride[0] \times h + m, stride[1] \times w + n)
  74. If :attr:`padding` is non-zero, then the input is implicitly zero-padded on
  75. both sides for :attr:`padding` number of points.
  76. :param kernel_size: the size of the window.
  77. :param stride: the stride of the window. Default value is kernel_size。
  78. :param padding: implicit zero padding to be added on both sides.
  79. :param mode: whether to count padding values. "average" mode will do counting and
  80. "average_count_exclude_padding" mode won't do counting.
  81. Default: "average_count_exclude_padding"
  82. Examples:
  83. .. testcode::
  84. import numpy as np
  85. import megengine as mge
  86. import megengine.module as M
  87. m = M.AvgPool2d(kernel_size=3, stride=1, padding=0)
  88. inp = mge.tensor(np.arange(0, 16).astype("float32").reshape(1, 1, 4, 4))
  89. oup = m(inp)
  90. print(oup.numpy())
  91. Outputs:
  92. .. testoutput::
  93. [[[[ 5. 6.]
  94. [ 9. 10.]]]]
  95. """
  96. def __init__(
  97. self,
  98. kernel_size: Union[int, Tuple[int, int]],
  99. stride: Union[int, Tuple[int, int]] = None,
  100. padding: Union[int, Tuple[int, int]] = 0,
  101. mode: str = "average_count_exclude_padding",
  102. **kwargs
  103. ):
  104. super(AvgPool2d, self).__init__(kernel_size, stride, padding, **kwargs)
  105. self.mode = mode
  106. def forward(self, inp):
  107. return avg_pool2d(inp, self.kernel_size, self.stride, self.padding, self.mode)
  108. def _module_info_string(self) -> str:
  109. return "kernel_size={kernel_size}, stride={stride}, padding={padding}, mode={mode}".format(
  110. **self.__dict__
  111. )

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台