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 5.7 kB

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

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