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.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. # -*- coding: utf-8 -*-
  2. from abc import abstractmethod
  3. from typing import Tuple, Union
  4. from ..functional import avg_pool2d, max_pool2d
  5. from .module import Module
  6. class _PoolNd(Module):
  7. def __init__(
  8. self,
  9. kernel_size: Union[int, Tuple[int, int]],
  10. stride: Union[int, Tuple[int, int]] = None,
  11. padding: Union[int, Tuple[int, int]] = 0,
  12. **kwargs
  13. ):
  14. super(_PoolNd, self).__init__(**kwargs)
  15. self.kernel_size = kernel_size
  16. self.stride = stride or kernel_size
  17. self.padding = padding
  18. @abstractmethod
  19. def forward(self, inp):
  20. pass
  21. def _module_info_string(self) -> str:
  22. return "kernel_size={kernel_size}, stride={stride}, padding={padding}".format(
  23. **self.__dict__
  24. )
  25. class MaxPool2d(_PoolNd):
  26. r"""Applies a 2D max pooling over an input.
  27. For instance, given an input of the size :`(N, C, H_{\text{in}}, W_{\text{in}})` and
  28. :attr:`kernel_size` :math:`(kH, kW)`, this layer generates the output of
  29. the size :math:`(N, C, H_{\text{out}}, W_{\text{out}})` through a process described as:
  30. .. math::
  31. \begin{aligned}
  32. out(N_i, C_j, h, w) ={} & \max_{m=0, \ldots, kH-1} \max_{n=0, \ldots, kW-1}
  33. \text{input}(N_i, C_j, \text{stride[0]} \times h + m,
  34. \text{stride[1]} \times w + n)
  35. \end{aligned}
  36. If :attr:`padding` is non-zero, then the input is implicitly zero-padded on
  37. both sides for :attr:`padding` number of points.
  38. Args:
  39. kernel_size: the size of the window.
  40. stride: the stride of the window. Default value is ``kernel_size``.
  41. padding: implicit zero padding to be added on both sides.Default: 0.
  42. Examples:
  43. >>> import numpy as np
  44. >>> m = M.MaxPool2d(kernel_size=3, stride=1, padding=0)
  45. >>> inp = mge.tensor(np.arange(0, 16).astype("float32").reshape(1, 1, 4, 4))
  46. >>> oup = m(inp)
  47. >>> oup.numpy()
  48. array([[[[10., 11.],
  49. [14., 15.]]]], dtype=float32)
  50. """
  51. def forward(self, inp):
  52. return max_pool2d(inp, self.kernel_size, self.stride, self.padding)
  53. class AvgPool2d(_PoolNd):
  54. r"""Applies a 2D average pooling over an input.
  55. For instance, given an input of the size :math:`(N, C, H_{\text{in}}, W_{\text{in}})` and
  56. :attr:`kernel_size` :math:`(kH, kW)`, this layer generates the output of
  57. the size :math:`(N, C, H_{\text{out}}, W_{\text{out}})` through a process described as:
  58. .. math::
  59. out(N_i, C_j, h, w) = \frac{1}{kH * kW} \sum_{m=0}^{kH-1} \sum_{n=0}^{kW-1}
  60. input(N_i, C_j, stride[0] \times h + m, stride[1] \times w + n)
  61. If :attr:`padding` is non-zero, then the input is implicitly zero-padded on
  62. both sides for :attr:`padding` number of points.
  63. Args:
  64. kernel_size: the size of the window.
  65. stride: the stride of the window. Default value is ``kernel_size``.
  66. padding: implicit zero padding to be added on both sides.Default: 0.
  67. mode: whether to include the padding values while calculating the average, set
  68. to "average" will do counting.
  69. Default: "average_count_exclude_padding"
  70. Examples:
  71. >>> import numpy as np
  72. >>> m = M.AvgPool2d(kernel_size=2, stride=2, padding=[1,0], mode="average")
  73. >>> inp = mge.tensor(np.arange(1 * 1 * 3 * 4).astype(np.float32).reshape(1, 1, 3, 4))
  74. >>> output = m(inp)
  75. >>> output
  76. Tensor([[[[0.25 1.25]
  77. [6.5 8.5 ]]]], device=xpux:0)
  78. """
  79. def __init__(
  80. self,
  81. kernel_size: Union[int, Tuple[int, int]],
  82. stride: Union[int, Tuple[int, int]] = None,
  83. padding: Union[int, Tuple[int, int]] = 0,
  84. mode: str = "average_count_exclude_padding",
  85. **kwargs
  86. ):
  87. super(AvgPool2d, self).__init__(kernel_size, stride, padding, **kwargs)
  88. self.mode = mode
  89. def forward(self, inp):
  90. return avg_pool2d(inp, self.kernel_size, self.stride, self.padding, self.mode)
  91. def _module_info_string(self) -> str:
  92. return "kernel_size={kernel_size}, stride={stride}, padding={padding}, mode={mode}".format(
  93. **self.__dict__
  94. )