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.

activation.py 6.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. import numpy as np
  10. from ..functional import gelu, leaky_relu, prelu, relu, sigmoid, silu, softmax
  11. from ..tensor import Parameter
  12. from .module import Module
  13. class Softmax(Module):
  14. r"""Applies a softmax function. Softmax is defined as:
  15. .. math::
  16. \text{Softmax}(x_{i}) = \frac{exp(x_i)}{\sum_j exp(x_j)}
  17. It is applied to all elements along axis, and rescales elements so that
  18. they stay in the range `[0, 1]` and sum to 1.
  19. Args:
  20. axis: Along which axis softmax will be applied. By default,
  21. softmax will apply along the highest ranked axis.
  22. Examples:
  23. >>> import numpy as np
  24. >>> data = mge.tensor(np.array([-2,-1,0,1,2]).astype(np.float32))
  25. >>> softmax = M.Softmax()
  26. >>> output = softmax(data)
  27. >>> with np.printoptions(precision=6):
  28. ... print(output.numpy())
  29. [0.011656 0.031685 0.086129 0.234122 0.636409]
  30. """
  31. def __init__(self, axis=None, **kwargs):
  32. super().__init__(**kwargs)
  33. self.axis = axis
  34. def forward(self, inputs):
  35. return softmax(inputs, self.axis)
  36. def _module_info_string(self) -> str:
  37. return "axis={axis}".format(axis=self.axis)
  38. class Sigmoid(Module):
  39. r"""Applies the element-wise function:
  40. .. math::
  41. \text{Sigmoid}(x) = \frac{1}{1 + \exp(-x)}
  42. Examples:
  43. >>> import numpy as np
  44. >>> data = mge.tensor(np.array([-2,-1,0,1,2,]).astype(np.float32))
  45. >>> sigmoid = M.Sigmoid()
  46. >>> output = sigmoid(data)
  47. >>> with np.printoptions(precision=6):
  48. ... print(output.numpy())
  49. [0.119203 0.268941 0.5 0.731059 0.880797]
  50. """
  51. def forward(self, inputs):
  52. return sigmoid(inputs)
  53. class SiLU(Module):
  54. r"""Applies the element-wise function:
  55. .. math::
  56. \text{SiLU}(x) = \frac{x}{1 + \exp(-x)}
  57. Examples:
  58. >>> import numpy as np
  59. >>> data = mge.tensor(np.array([-2,-1,0,1,2,]).astype(np.float32))
  60. >>> silu = M.SiLU()
  61. >>> output = silu(data)
  62. >>> with np.printoptions(precision=6):
  63. ... print(output.numpy())
  64. [-0.238406 -0.268941 0. 0.731059 1.761594]
  65. """
  66. def forward(self, inputs):
  67. return silu(inputs)
  68. class GELU(Module):
  69. r"""Applies the element-wise function:
  70. .. math::
  71. \text{GELU}(x) = x\Phi(x)
  72. where :math:`\Phi(x)` is the Cumulative Distribution Function for Gaussian Distribution.
  73. Examples:
  74. >>> import numpy as np
  75. >>> data = mge.tensor(np.array([-2,-1,0,1,2,]).astype(np.float32))
  76. >>> gelu = M.GELU()
  77. >>> output = gelu(data)
  78. >>> with np.printoptions(precision=4):
  79. ... print(output.numpy())
  80. [-0.0455 -0.1587 0. 0.8413 1.9545]
  81. """
  82. def forward(self, inputs):
  83. return gelu(inputs)
  84. class ReLU(Module):
  85. r"""Applies the element-wise function:
  86. .. math::
  87. \text{ReLU}(x) = \max(x, 0)
  88. Examples:
  89. >>> import numpy as np
  90. >>> data = mge.tensor(np.array([-2,-1,0,1,2,]).astype(np.float32))
  91. >>> relu = M.ReLU()
  92. >>> output = relu(data)
  93. >>> with np.printoptions(precision=6):
  94. ... print(output.numpy())
  95. [0. 0. 0. 1. 2.]
  96. """
  97. def forward(self, x):
  98. return relu(x)
  99. class PReLU(Module):
  100. r"""Applies the element-wise function:
  101. .. math::
  102. \text{PReLU}(x) = \max(0,x) + a * \min(0,x)
  103. or
  104. .. math::
  105. \text{PReLU}(x) =
  106. \begin{cases}
  107. x, & \text{ if } x \geq 0 \\
  108. ax, & \text{ otherwise }
  109. \end{cases}
  110. Here :math:`a` is a learnable parameter. When called without arguments, `PReLU()` uses
  111. a single paramter :math:`a` across all input channel. If called with `PReLU(num_of_channels)`, each input channle will has it's own :math:`a`.
  112. Args:
  113. num_parameters: number of :math:`a` to learn, there is only two
  114. values are legitimate: 1, or the number of channels at input. Default: 1
  115. init: the initial value of :math:`a`. Default: 0.25
  116. Examples:
  117. >>> import numpy as np
  118. >>> data = mge.tensor(np.array([-1.2, -3.7, 2.7]).astype(np.float32))
  119. >>> prelu = M.PReLU()
  120. >>> output = prelu(data)
  121. >>> output.numpy()
  122. array([-0.3 , -0.925, 2.7 ], dtype=float32)
  123. """
  124. def __init__(self, num_parameters: int = 1, init: float = 0.25, **kwargs):
  125. super().__init__(**kwargs)
  126. self.num_parameters = num_parameters
  127. if num_parameters > 1:
  128. # Assume format is NCHW
  129. self.weight = Parameter(
  130. data=np.full((1, num_parameters, 1, 1), init, dtype=np.float32)
  131. )
  132. else:
  133. self.weight = Parameter(data=[init])
  134. def forward(self, inputs):
  135. return prelu(inputs, self.weight)
  136. class LeakyReLU(Module):
  137. r"""Applies the element-wise function:
  138. .. math::
  139. \text{LeakyReLU}(x) = \max(0,x) + negative\_slope \times \min(0,x)
  140. or
  141. .. math::
  142. \text{LeakyReLU}(x) =
  143. \begin{cases}
  144. x, & \text{ if } x \geq 0 \\
  145. negative\_slope \times x, & \text{ otherwise }
  146. \end{cases}
  147. Examples:
  148. >>> import numpy as np
  149. >>> data = mge.tensor(np.array([-8, -12, 6, 10]).astype(np.float32))
  150. >>> leakyrelu = M.LeakyReLU(0.01)
  151. >>> output = leakyrelu(data)
  152. >>> output.numpy()
  153. array([-0.08, -0.12, 6. , 10. ], dtype=float32)
  154. """
  155. def __init__(self, negative_slope: float = 0.01, **kwargs):
  156. super().__init__(**kwargs)
  157. self.negative_slope = negative_slope
  158. def forward(self, inputs):
  159. return leaky_relu(inputs, self.negative_slope)