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.

math.py 8.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 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 typing import Optional
  10. import megengine._internal as mgb
  11. from ..core import Tensor, wrap_io_tensor
  12. from .elemwise import clamp
  13. @wrap_io_tensor
  14. def sum(inp: Tensor, axis: Optional[int] = None, keepdims: bool = False) -> Tensor:
  15. r"""Returns the sum of each row of the ``inp`` tensor in the given ``axis``.
  16. :param inp: The input tensor.
  17. :param axis: The dimension to reduce. If None, all the dimensions will be reduced.
  18. Default: None
  19. :param keepdims: Whether the output tensor has ``axis`` retained or not.
  20. Default: False
  21. :return: The output tensor
  22. Examples:
  23. .. testcode::
  24. import numpy as np
  25. from megengine import tensor
  26. import megengine.functional as F
  27. data = tensor(np.arange(1, 7, dtype=np.int32).reshape(2, 3))
  28. out = F.sum(data)
  29. print(out.numpy())
  30. .. testoutput::
  31. [21]
  32. """
  33. return mgb.opr.reduce_(inp, "SUM", axis, keepdims)
  34. @wrap_io_tensor
  35. def prod(inp: Tensor, axis: Optional[int] = None, keepdims=False) -> Tensor:
  36. r"""
  37. Returns the element product of input tensor along given *axis*.
  38. :param inp: The input tensor
  39. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: ``None``
  40. :param keepdims: Whether the output tensor has *axis* retained or not. Default: ``False``
  41. :return: The output tensor
  42. Examples:
  43. .. testcode::
  44. import numpy as np
  45. from megengine import tensor
  46. import megengine.functional as F
  47. data = tensor(np.arange(1, 7, dtype=np.int32).reshape(2, 3))
  48. out = F.prod(data)
  49. print(out.numpy())
  50. Outputs:
  51. .. testoutput::
  52. [720]
  53. """
  54. return mgb.opr.reduce_(inp, "PRODUCT", axis, keepdims)
  55. @wrap_io_tensor
  56. def mean(inp: Tensor, axis: Optional[int] = None, keepdims: bool = False) -> Tensor:
  57. """Returns the mean value of each row of the ``inp`` tensor in
  58. the given ``axis``. If axis is a list of dimensions,
  59. reduce over all of them.
  60. :param inp: The input tensor
  61. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  62. :param keepdims: Whether the output tensor has ``axis`` retained or not. Default: False
  63. Examples:
  64. .. testcode::
  65. import numpy as np
  66. from megengine import tensor
  67. import megengine.functional as F
  68. data = tensor(np.arange(1, 7, dtype=np.int32).reshape(2, 3))
  69. out = F.mean(data)
  70. print(out.numpy())
  71. .. testoutput::
  72. [3.5]
  73. """
  74. return mgb.opr.mean(inp, axis, keepdims)
  75. @wrap_io_tensor
  76. def min(inp: Tensor, axis: Optional[int] = None, keepdims: bool = False) -> Tensor:
  77. r"""
  78. Returns the min value of input tensor along given *axis*.
  79. :param inp: The input tensor
  80. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  81. :param keepdims: Whether the output tensor has *axis* retained or not. Default: False
  82. :return: The output tensor
  83. Examples:
  84. .. testcode::
  85. import numpy as np
  86. from megengine import tensor
  87. import megengine.functional as F
  88. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  89. y = F.min(x)
  90. print(y.numpy())
  91. Outputs:
  92. .. testoutput::
  93. [1]
  94. """
  95. return mgb.opr.reduce_(inp, "MIN", axis, keepdims)
  96. @wrap_io_tensor
  97. def max(inp: Tensor, axis: Optional[int] = None, keepdims: bool = False) -> Tensor:
  98. r"""Returns the max value of the input tensor along given *axis*.
  99. :param inp: The input tensor
  100. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  101. :param keepdims: Whether the output tensor has *axis* retained or not. Default: False
  102. :return: The output tensor
  103. Examples:
  104. .. testcode::
  105. import numpy as np
  106. from megengine import tensor
  107. import megengine.functional as F
  108. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  109. y = F.max(x)
  110. print(y.numpy())
  111. .. testoutput::
  112. [6]
  113. """
  114. return mgb.opr.reduce_(inp, "MAX", axis, keepdims)
  115. @wrap_io_tensor
  116. def sqrt(inp: Tensor) -> Tensor:
  117. """
  118. Return a new tensor with the square-root of the elements of ``inp``
  119. :param inp: The input tensor
  120. :return: The computed tensor
  121. Examples:
  122. .. testcode::
  123. import numpy as np
  124. import megengine as mge
  125. import megengine.functional as F
  126. data = mge.tensor(np.arange(0, 6, dtype=np.float32).reshape(2, 3))
  127. out = F.sqrt(data)
  128. print(out.numpy())
  129. Outputs:
  130. .. testoutput::
  131. [[0. 1. 1.4142]
  132. [1.7321 2. 2.2361 ]]
  133. """
  134. return mgb.opr.sqrt(inp)
  135. def norm(inp: Tensor, p: int = 2, axis: Optional[int] = None, keepdims=False):
  136. """Calculate ``p``-norm of input tensor along certain axis.
  137. :param inp: The input tensor
  138. :param p: power of value ``p`` applied to ``inp``. Default: 2
  139. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  140. :param keepdims: Whether the output tensor has ``axis`` retained or not. Default: False
  141. :return: The output tensor
  142. """
  143. if axis is None:
  144. inp = inp.reshape(-1)
  145. return (inp ** p).sum(axis=axis, keepdims=keepdims) ** (1.0 / p)
  146. @wrap_io_tensor
  147. def argmin(inp: Tensor, axis: Optional[int] = None, keepdims: bool = False) -> Tensor:
  148. r"""Returns the indices of the minimum values along an axis
  149. :param inp: The input tensor
  150. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  151. :param keepdims: Whether the output tensor has *axis* retained or not. Default: False
  152. :return: The output tensor
  153. Examples:
  154. .. testcode::
  155. import numpy as np
  156. from megengine import tensor
  157. import megengine.functional as F
  158. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  159. y = F.argmin(x)
  160. print(y.numpy())
  161. .. testoutput::
  162. [0]
  163. """
  164. return mgb.opr.argmin(inp, axis, keepdims)
  165. @wrap_io_tensor
  166. def argmax(inp: Tensor, axis: Optional[int] = None, keepdims: bool = False) -> Tensor:
  167. r"""Returns the indices of the maximum values along an axis
  168. :param inp: The input tensor
  169. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  170. :param keepdims: Whether the output tensor has *axis* retained or not. Default: False
  171. :return: The output tensor
  172. Examples:
  173. .. testcode::
  174. import numpy as np
  175. from megengine import tensor
  176. import megengine.functional as F
  177. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  178. y = F.argmax(x)
  179. print(y.numpy())
  180. .. testoutput::
  181. [5]
  182. """
  183. return mgb.opr.argmax(inp, axis, keepdims)
  184. def normalize(
  185. inp: Tensor, p: int = 2, axis: Optional[int] = None, eps: float = 1e-12
  186. ) -> Tensor:
  187. r"""Perform :math:`L_p` normalization of input tensor along certain axis.
  188. For a tensor :attr:`inp` of shape :math:`(n_0, ..., n_{dim}, ..., n_k)`, each
  189. :math:`n_{dim}` -element vector :math:`v` along dimension :attr:`axis` is transformed as:
  190. .. math::
  191. v = \frac{v}{\max(\lVert v \rVert_p, \epsilon)}.
  192. :param inp: the input tensor
  193. :param p: power of value ``p`` applied to ``inp``. Default: 2
  194. :param axis: The dimension to reduce. If None, all the dimensions will be reduced
  195. to calculate the norm. Default: None
  196. :param eps: a small value to avoid division by zero. Default: 1e-12
  197. :return: the normalized output tensor
  198. """
  199. if axis is None:
  200. return inp / clamp(norm(inp, p), lower=eps)
  201. else:
  202. return inp / clamp(norm(inp, p, axis, keepdims=True), lower=eps)

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