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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. import collections
  10. import functools
  11. import math
  12. import numbers
  13. from typing import Optional, Sequence, Tuple, Union
  14. from ..core.ops import builtin
  15. from ..core.ops._internal import param_defs as P
  16. from ..core.tensor import utils
  17. from ..core.tensor.core import apply
  18. from ..tensor import Tensor
  19. from .elemwise import clamp, exp, log, log1p
  20. from .tensor import remove_axis, reshape
  21. __all__ = [
  22. "argmax",
  23. "argmin",
  24. "argsort",
  25. "isinf",
  26. "isnan",
  27. "max",
  28. "mean",
  29. "min",
  30. "norm",
  31. "normalize",
  32. "prod",
  33. "sign",
  34. "sort",
  35. "std",
  36. "sum",
  37. "topk",
  38. "var",
  39. ]
  40. def isnan(inp: Tensor) -> Tensor:
  41. r"""Returns a new tensor representing if each element is NaN or not.
  42. :param: inp
  43. :return: a new tensor representing if each element in :attr:`inp` is NaN or not.
  44. Examples:
  45. .. testcode::
  46. from megengine import tensor
  47. import megengine.functional as F
  48. x = tensor([1, float("nan"), 0])
  49. print(F.isnan(x).numpy())
  50. .. testoutput::
  51. [False True False]
  52. """
  53. return inp != inp
  54. def isinf(inp: Tensor) -> Tensor:
  55. r"""Returns a new tensor representing if each element is Inf or not.
  56. :param: inp
  57. :return: a new tensor representing if each element in :attr:`inp` is Inf or not.
  58. Examples:
  59. .. testcode::
  60. from megengine import tensor
  61. import megengine.functional as F
  62. x = tensor([1, float("inf"), 0])
  63. print(F.isinf(x).numpy())
  64. .. testoutput::
  65. [False True False]
  66. """
  67. return abs(inp).astype("float32") == float("inf")
  68. def sign(inp: Tensor):
  69. r"""Returns sign of each element in the input tensor.
  70. :param: inp
  71. :return: a sign tensor.
  72. Examples:
  73. .. testcode::
  74. from megengine import tensor
  75. import megengine.functional as F
  76. x = tensor([1, -1, 0])
  77. print(F.sign(x).numpy())
  78. .. testoutput::
  79. [ 1 -1 0]
  80. """
  81. return (inp > 0).astype(inp.dtype) - (inp < 0).astype(inp.dtype)
  82. def sum(
  83. inp: Tensor,
  84. axis: Optional[Union[int, Sequence[int]]] = None,
  85. keepdims: bool = False,
  86. ) -> Tensor:
  87. r"""Returns the sum of each row of the ``inp`` tensor in the given ``axis``.
  88. :param inp: The input tensor.
  89. :param axis: The dimension to reduce. If None, all the dimensions will be reduced.
  90. Default: None
  91. :param keepdims: Whether the output tensor has ``axis`` retained or not.
  92. Default: False
  93. :return: The output tensor
  94. Examples:
  95. .. testcode::
  96. import numpy as np
  97. from megengine import tensor
  98. import megengine.functional as F
  99. data = tensor(np.arange(1, 7, dtype=np.int32).reshape(2, 3))
  100. out = F.sum(data)
  101. print(out.numpy())
  102. .. testoutput::
  103. [21]
  104. """
  105. return inp.sum(axis=axis, keepdims=keepdims)
  106. def prod(
  107. inp: Tensor, axis: Optional[Union[int, Sequence[int]]] = None, keepdims=False
  108. ) -> Tensor:
  109. r"""
  110. Returns the element product of input tensor along given *axis*.
  111. :param inp: The input tensor
  112. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: ``None``
  113. :param keepdims: Whether the output tensor has *axis* retained or not. Default: ``False``
  114. :return: The output tensor
  115. Examples:
  116. .. testcode::
  117. import numpy as np
  118. from megengine import tensor
  119. import megengine.functional as F
  120. data = tensor(np.arange(1, 7, dtype=np.int32).reshape(2, 3))
  121. out = F.prod(data)
  122. print(out.numpy())
  123. Outputs:
  124. .. testoutput::
  125. [720]
  126. """
  127. return inp.prod(axis=axis, keepdims=keepdims)
  128. def mean(
  129. inp: Tensor,
  130. axis: Optional[Union[int, Sequence[int]]] = None,
  131. keepdims: bool = False,
  132. ) -> Tensor:
  133. """Returns the mean value of each row of the ``inp`` tensor in
  134. the given ``axis``. If axis is a list of dimensions,
  135. reduce over all of them.
  136. :param inp: The input tensor
  137. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  138. :param keepdims: Whether the output tensor has ``axis`` retained or not. Default: False
  139. Examples:
  140. .. testcode::
  141. import numpy as np
  142. from megengine import tensor
  143. import megengine.functional as F
  144. data = tensor(np.arange(1, 7, dtype=np.int32).reshape(2, 3))
  145. out = F.mean(data)
  146. print(out.numpy())
  147. .. testoutput::
  148. [3.5]
  149. """
  150. return inp.astype("float32").mean(axis=axis, keepdims=keepdims)
  151. def median(
  152. inp: Tensor,
  153. axis: Optional[Union[int, Sequence[int]]] = None,
  154. keepdims: bool = False,
  155. ) -> Tensor:
  156. raise NotImplementedError
  157. def var(
  158. inp: Tensor,
  159. axis: Optional[Union[int, Sequence[int]]] = None,
  160. keepdims: bool = False,
  161. ) -> Tensor:
  162. """Returns the variance value of input tensor along
  163. given ``axis``. If axis is a list of dimensions,
  164. reduce over all of them.
  165. :param inp: The input tensor.
  166. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: ``None``.
  167. :param keepdims: Whether the output tensor has ``axis`` retained or not. Default: ``False``.
  168. :return: The output tensor.
  169. Examples:
  170. .. testcode::
  171. import numpy as np
  172. from megengine import tensor
  173. import megengine.functional as F
  174. data = tensor(np.arange(1, 7, dtype=np.float32).reshape(2, 3))
  175. out = F.var(data)
  176. print(out.numpy())
  177. .. testoutput::
  178. [2.9166667]
  179. """
  180. if axis is None:
  181. m = mean(inp, axis=axis, keepdims=False)
  182. else:
  183. m = mean(inp, axis=axis, keepdims=True)
  184. v = inp - m
  185. return mean(v ** 2, axis=axis, keepdims=keepdims)
  186. def std(
  187. inp: Tensor,
  188. axis: Optional[Union[int, Sequence[int]]] = None,
  189. keepdims: bool = False,
  190. ) -> Tensor:
  191. """Returns the standard deviation of input tensor along
  192. given ``axis``. If axis is a list of dimensions,
  193. reduce over all of them.
  194. :param inp: The input tensor.
  195. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: ``None``.
  196. :param keepdims: Whether the output tensor has ``axis`` retained or not. Default: ``False``.
  197. :return: The output tensor.
  198. Examples:
  199. .. testcode::
  200. import numpy as np
  201. from megengine import tensor
  202. import megengine.functional as F
  203. data = tensor(np.arange(1, 7, dtype=np.float32).reshape(2, 3))
  204. out = F.std(data, axis=1)
  205. print(out.numpy())
  206. .. testoutput::
  207. [0.8164966 0.8164966]
  208. """
  209. return var(inp, axis=axis, keepdims=keepdims) ** 0.5
  210. def min(
  211. inp: Tensor,
  212. axis: Optional[Union[int, Sequence[int]]] = None,
  213. keepdims: bool = False,
  214. ) -> Tensor:
  215. r"""
  216. Returns the min value of input tensor along given *axis*.
  217. :param inp: The input tensor
  218. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  219. :param keepdims: Whether the output tensor has *axis* retained or not. Default: False
  220. :return: The output tensor
  221. Examples:
  222. .. testcode::
  223. import numpy as np
  224. from megengine import tensor
  225. import megengine.functional as F
  226. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  227. y = F.min(x)
  228. print(y.numpy())
  229. Outputs:
  230. .. testoutput::
  231. [1]
  232. """
  233. return inp.min(axis=axis, keepdims=keepdims)
  234. def max(
  235. inp: Tensor,
  236. axis: Optional[Union[int, Sequence[int]]] = None,
  237. keepdims: bool = False,
  238. ) -> Tensor:
  239. r"""Returns the max value of the input tensor along given *axis*.
  240. :param inp: The input tensor
  241. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  242. :param keepdims: Whether the output tensor has *axis* retained or not. Default: False
  243. :return: The output tensor
  244. Examples:
  245. .. testcode::
  246. import numpy as np
  247. from megengine import tensor
  248. import megengine.functional as F
  249. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  250. y = F.max(x)
  251. print(y.numpy())
  252. .. testoutput::
  253. [6]
  254. """
  255. return inp.max(axis=axis, keepdims=keepdims)
  256. def norm(
  257. inp: Tensor,
  258. p: int = 2,
  259. axis: Optional[Union[int, Sequence[int]]] = None,
  260. keepdims=False,
  261. ):
  262. """Calculate ``p``-norm of input tensor along certain axis.
  263. :param inp: The input tensor
  264. :param p: power of value ``p`` applied to ``inp``. Default: 2
  265. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  266. :param keepdims: Whether the output tensor has ``axis`` retained or not. Default: False
  267. :return: The output tensor
  268. Examples:
  269. .. testcode::
  270. import numpy as np
  271. from megengine import tensor
  272. import megengine.functional as F
  273. x = tensor(np.arange(-3, 3, dtype=np.float32).reshape(2,3))
  274. y = F.norm(x)
  275. print(y.numpy())
  276. .. testoutput::
  277. [4.358899]
  278. """
  279. if p == 0:
  280. return sum(inp != 0, axis=axis, keepdims=keepdims)
  281. if p == math.inf:
  282. return max(abs(inp))
  283. if p == -math.inf:
  284. return min(abs(inp))
  285. return sum(abs(inp) ** p, axis=axis, keepdims=keepdims) ** (1.0 / p)
  286. def argmin(
  287. inp: Tensor,
  288. axis: Optional[Union[int, Sequence[int]]] = None,
  289. keepdims: bool = False,
  290. ) -> Tensor:
  291. r"""Returns the indices of the minimum values along an axis
  292. :param inp: The input tensor
  293. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  294. :param keepdims: Whether the output tensor has *axis* retained or not. Default: False
  295. :return: The output tensor
  296. Examples:
  297. .. testcode::
  298. import numpy as np
  299. from megengine import tensor
  300. import megengine.functional as F
  301. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  302. y = F.argmin(x)
  303. print(y.numpy())
  304. .. testoutput::
  305. [0]
  306. """
  307. if isinstance(axis, collections.abc.Iterable):
  308. axis = list(axis)
  309. axis.sort(reverse=True)
  310. for ai in axis:
  311. op = builtin.Argmin(axis=ai)
  312. (inp,) = apply(op, inp)
  313. if not keepdims:
  314. inp = remove_axis(inp, ai)
  315. return inp
  316. if axis is None:
  317. assert not keepdims, "can not set axis=None and keepdims=True"
  318. inp = inp.flatten()
  319. axis = 0
  320. op = builtin.Argmin(axis=axis)
  321. (result,) = apply(op, inp)
  322. if not keepdims:
  323. result = remove_axis(result, axis)
  324. return result
  325. def argmax(
  326. inp: Tensor,
  327. axis: Optional[Union[int, Sequence[int]]] = None,
  328. keepdims: bool = False,
  329. ) -> Tensor:
  330. r"""Returns the indices of the maximum values along an axis
  331. :param inp: The input tensor
  332. :param axis: The dimension to reduce. If None, all the dimensions will be reduced. Default: None
  333. :param keepdims: Whether the output tensor has *axis* retained or not. Default: False
  334. :return: The output tensor
  335. Examples:
  336. .. testcode::
  337. import numpy as np
  338. from megengine import tensor
  339. import megengine.functional as F
  340. x = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3))
  341. y = F.argmax(x)
  342. print(y.numpy())
  343. .. testoutput::
  344. [5]
  345. """
  346. if isinstance(axis, collections.abc.Iterable):
  347. axis = list(axis)
  348. axis.sort(reverse=True)
  349. for ai in axis:
  350. op = builtin.Argmax(axis=ai)
  351. (inp,) = apply(op, inp)
  352. if not keepdims:
  353. inp = remove_axis(inp, ai)
  354. return inp
  355. if axis is None:
  356. assert not keepdims, "can not set axis=None and keepdims=True"
  357. inp = inp.flatten()
  358. axis = 0
  359. op = builtin.Argmax(axis=axis)
  360. (result,) = apply(op, inp)
  361. if not keepdims:
  362. result = remove_axis(result, axis)
  363. return result
  364. def normalize(
  365. inp: Tensor,
  366. p: int = 2,
  367. axis: Optional[Union[int, Sequence[int]]] = None,
  368. eps: float = 1e-12,
  369. ) -> Tensor:
  370. r"""Perform :math:`L_p` normalization of input tensor along certain axis.
  371. For a tensor :attr:`inp` of shape :math:`(n_0, ..., n_{dim}, ..., n_k)`, each
  372. :math:`n_{dim}` -element vector :math:`v` along dimension :attr:`axis` is transformed as:
  373. .. math::
  374. v = \frac{v}{\max(\lVert v \rVert_p, \epsilon)}.
  375. :param inp: the input tensor
  376. :param p: power of value ``p`` applied to ``inp``. Default: 2
  377. :param axis: The dimension to reduce. If None, all the dimensions will be reduced
  378. to calculate the norm. Default: None
  379. :param eps: a small value to avoid division by zero. Default: 1e-12
  380. :return: the normalized output tensor
  381. """
  382. if axis is None:
  383. return inp / clamp(norm(inp, p, axis), lower=eps)
  384. else:
  385. return inp / clamp(norm(inp, p, axis, keepdims=True), lower=eps)
  386. def argsort(inp: Tensor, descending: bool = False) -> Tensor:
  387. r"""
  388. Sort the target 2d matrix by row, return both the sorted tensor and indices.
  389. :param inp: The input tensor, if 2d, each row will be sorted
  390. :param descending: Sort in descending order, where the largest comes first. Default: ``False``
  391. :return: Tuple of two tensors (sorted_tensor, indices_of_int32)
  392. Examples:
  393. .. testcode::
  394. import numpy as np
  395. from megengine import tensor
  396. import megengine.functional as F
  397. data = tensor(np.array([1,2], dtype=np.float32))
  398. indices = F.argsort(data)
  399. print(indices.numpy())
  400. Outputs:
  401. .. testoutput::
  402. [0 1]
  403. """
  404. assert len(inp.shape) <= 2, "Input should be 1d or 2d"
  405. if descending:
  406. order = P.Argsort.Order.DESCENDING
  407. else:
  408. order = P.Argsort.Order.ASCENDING
  409. op = builtin.Argsort(order=order)
  410. if len(inp.shape) == 1:
  411. inp = inp.reshape(1, -1)
  412. _, result = apply(op, inp)
  413. return result[0]
  414. _, result = apply(op, inp)
  415. return result
  416. def sort(inp: Tensor, descending: bool = False) -> Tuple[Tensor, Tensor]:
  417. assert len(inp.shape) <= 2, "Input should be 1d or 2d"
  418. if descending:
  419. order = P.Argsort.Order.DESCENDING
  420. else:
  421. order = P.Argsort.Order.ASCENDING
  422. op = builtin.Argsort(order=order)
  423. if len(inp.shape) == 1:
  424. inp = inp.reshape(1, -1)
  425. tns, ind = apply(op, inp)
  426. return tns[0], ind[0]
  427. tns, ind = apply(op, inp)
  428. return tns, ind
  429. def topk(
  430. inp: Tensor,
  431. k: int,
  432. descending: bool = False,
  433. kth_only: bool = False,
  434. no_sort: bool = False,
  435. ) -> Tuple[Tensor, Tensor]:
  436. r"""
  437. Selected the Top-K (by default) smallest elements of 2d matrix by row.
  438. :param inp: The input tensor, if 2d, each row will be sorted
  439. :param k: The number of elements needed
  440. :param descending: If true, return the largest elements instead. Default: ``False``
  441. :param kth_only: If true, only the k-th element will be returned. Default: ``False``
  442. :param no_sort: If true, the returned elements can be unordered. Default: ``False``
  443. :return: Tuple of two tensors (topk_tensor, indices_of_int32)
  444. Examples:
  445. .. testcode::
  446. import numpy as np
  447. from megengine import tensor
  448. import megengine.functional as F
  449. data = tensor(np.array([2, 4, 6, 8, 7, 5, 3, 1], dtype=np.float32))
  450. top, indices = F.topk(data, 5)
  451. print(top.numpy(), indices.numpy())
  452. Outputs:
  453. .. testoutput::
  454. [1. 2. 3. 4. 5.] [7 0 6 1 5]
  455. """
  456. if descending:
  457. inp = -inp
  458. Mode = P.TopK.Mode
  459. if kth_only:
  460. mode = Mode.KTH_ONLY
  461. elif no_sort:
  462. mode = Mode.VALUE_IDX_NOSORT
  463. else:
  464. mode = Mode.VALUE_IDX_SORTED
  465. op = builtin.TopK(mode=mode)
  466. if len(inp.shape) == 1:
  467. inp = inp.reshape(1, -1)
  468. res = apply(op, inp, Tensor(k, dtype="int32"))
  469. if kth_only:
  470. tns = res[0]
  471. else:
  472. tns, ind = res[0][0], res[1][0]
  473. else:
  474. res = apply(op, inp, Tensor(k, dtype="int32"))
  475. if kth_only:
  476. tns = res
  477. else:
  478. tns, ind = res[0], res[1]
  479. if descending:
  480. tns = -tns
  481. return tns, ind

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