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_ops.py 94 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425
  1. # Copyright 2020-2021 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """math operations, the function docs are adapted from Numpy API."""
  16. import operator
  17. import functools
  18. from ..ops import operations as P
  19. from ..ops import functional as F
  20. from ..ops import composite as C
  21. from ..ops.primitive import constexpr
  22. from ..common import dtype as mstype
  23. from ..common import Tensor
  24. from .dtypes import nan, pi
  25. from .array_creations import asarray_const, ones, zeros, empty, full, full_like
  26. from .array_ops import where as where_
  27. from .array_ops import ravel, expand_dims
  28. from .utils_const import _infer_out_shape, _check_axis_valid, _get_device, \
  29. _check_shape_aligned, _raise_type_error, _check_same_type, _check_is_float, \
  30. _raise_value_error, _promote, _check_axis_type, _canonicalize_axis, \
  31. _is_shape_empty, _check_is_int, _expanded_shape, _check_axis_in_range
  32. from .utils import _is_scalar, _expand, _broadcast_to, _broadcast_to_shape, _get_size, \
  33. _check_input_tensor
  34. ZERO_TENSOR = asarray_const(0)
  35. _mean_default = P.ReduceMean()
  36. _mean_keepdims = P.ReduceMean(True)
  37. _matmul = P.MatMul(False, False)
  38. _matmul_T = P.MatMul(False, True)
  39. _reduce_sum_default = P.ReduceSum()
  40. _reduce_sum_keepdims = P.ReduceSum(True)
  41. _reduce_min_default = P.ReduceMin()
  42. _reduce_min_keepdims = P.ReduceMin(True)
  43. _reduce_max_default = P.ReduceMax()
  44. _reduce_max_keepdims = P.ReduceMax(True)
  45. _cumsum_default = P.CumSum()
  46. def absolute(x, out=None, where=True, dtype=None):
  47. """
  48. Calculates the absolute value element-wise.
  49. Note:
  50. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  51. not supported.
  52. When `where` is provided, `out` must have a tensor value. `out` is not supported
  53. for storing the result, however it can be used in combination with `where` to set
  54. the value at indices for which `where` is set to False.
  55. Currently the backend kernel only supports float calculation, if the input
  56. is not a `float`, then it will be casted to :class:`mstype.float32` and casted back.
  57. Args:
  58. x (Tensor): Tensor to be used for calculation.
  59. out (Tensor or None, optional): defaults to None.
  60. where (Tensor or None, optional): For any non-default value of type other
  61. than :class:`Tensor` or :class:`None`, the output retains its original value.
  62. This condition is broadcasted over the input. At locations where the
  63. condition is `True`, the out array will be set to the ufunc result.
  64. Elsewhere, the out array will retain its original value. Note that
  65. if an uninitialized out array is created via the default ``out=None``,
  66. locations within it where the condition is `False` will remain
  67. uninitialized.
  68. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  69. output Tensor.
  70. Returns:
  71. Tensor.
  72. Raises:
  73. TypeError: If input arguments have types not specified above.
  74. Supported Platforms:
  75. ``Ascend`` ``GPU`` ``CPU``
  76. Examples:
  77. >>> import mindspore.numpy as np
  78. >>> x = np.asarray([1, 2, 3, -4, -5], np.float32)
  79. >>> output = np.absolute(x)
  80. >>> print(output)
  81. [1. 2. 3. 4. 5.]
  82. """
  83. original_dtype = x.dtype
  84. if not _check_is_float(original_dtype) and dtype is None:
  85. x = x.astype(mstype.float32)
  86. return _apply_tensor_op(F.absolute, x, out=out, where=where, dtype=dtype).astype(original_dtype)
  87. return _apply_tensor_op(F.absolute, x, out=out, where=where, dtype=dtype)
  88. def count_nonzero(x, axis=None, keepdims=False):
  89. """
  90. Counts the number of non-zero values in the tensor `x`.
  91. Args:
  92. x (Tensor): The tensor for which to count non-zeros.
  93. axis (Union[int,tuple], optional): Axis or tuple of axes along which to
  94. count non-zeros. Default is None, meaning that non-zeros will be counted
  95. along a flattened version of `x`.
  96. keepdims (bool, optional): If this is set to True, the axes that are counted
  97. are left in the result as dimensions with size one. With this option,
  98. the result will broadcast correctly against `x`.
  99. Returns:
  100. Tensor, indicating number of non-zero values in the `x` along a given axis.
  101. Otherwise, the total number of non-zero values in `x` is returned.
  102. Raises:
  103. TypeError: if the input is not a tensor.
  104. Supported Platforms:
  105. ``Ascend`` ``GPU`` ``CPU``
  106. Examples:
  107. >>> import mindspore.numpy as np
  108. >>> x = np.asarray([1, 2, 3, -4, 0, 3, 2, 0])
  109. >>> output = np.count_nonzero(x)
  110. >>> print(output)
  111. 6
  112. """
  113. if _is_shape_empty(x.shape):
  114. return ZERO_TENSOR
  115. if axis is None:
  116. axis = ()
  117. return C.count_nonzero(x=x, axis=axis, keep_dims=keepdims)
  118. def clip(x, xmin, xmax, out=None, where=True, dtype=None):
  119. """
  120. Clips (limits) the values in an array.
  121. Given an interval, values outside the interval are clipped to the interval edges.
  122. For example, if an interval of :math:`[0, 1]` is specified, values smaller than 0 become 0,
  123. and values larger than 1 become 1.
  124. Args:
  125. x (Tensor): Tensor containing elements to clip.
  126. xmin (Tensor, scalar, None): Minimum value. If None, clipping is not performed
  127. on lower interval edge. Not more than one of `xmin` and `xmax` may be None.
  128. xmax (Tensor, scalar, None): Maximum value. If None, clipping is not performed
  129. on upper interval edge. Not more than one of `xmin` and `xmax` may be None.
  130. If `xmin` or `xmax` are tensors, then the three tensors will be broadcasted
  131. to match their shapes.
  132. out (Tensor or None): optional, default to None.
  133. where (Tensor or None, optional): For any non-default value of type other
  134. than :class:`Tensor` or :class:`None`, the output retains its original value.
  135. This condition is broadcasted over the input. At locations where the
  136. condition is `True`, the out array will be set to the ufunc result.
  137. Elsewhere, the out array will retain its original value. Note that
  138. if an uninitialized out array is created via the default ``out=None``,
  139. locations within it where the condition is `False` will remain
  140. uninitialized.
  141. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  142. output Tensor.
  143. Returns:
  144. Tensor, a tensor with the elements of `x`, but where values
  145. < `xmin` are replaced with `xmin`, and those > `xmax` with `xmax`.
  146. Supported Platforms:
  147. ``Ascend`` ``GPU`` ``CPU``
  148. Examples:
  149. >>> import mindspore.numpy as np
  150. >>> x = np.asarray([1, 2, 3, -4, 0, 3, 2, 0])
  151. >>> output = np.clip(x, 0, 2)
  152. >>> print(output)
  153. [1 2 2 0 0 2 2 0]
  154. """
  155. if xmin is None and xmax is None:
  156. _raise_value_error("One of max or min must be given.")
  157. if xmin is not None:
  158. x = maximum(x, xmin, out=out, where=where, dtype=dtype)
  159. if xmax is not None:
  160. x = minimum(x, xmax, out=out, where=where, dtype=dtype)
  161. return x
  162. def deg2rad(x, out=None, where=True, dtype=None):
  163. """
  164. Converts angles from degrees to radians.
  165. Args:
  166. x (Tensor): Angles in degrees.
  167. out (Tensor or None, optional): defaults to None.
  168. where (Tensor or None, optional): For any non-default value of type other
  169. than :class:`Tensor` or :class:`None`, the output retains its original value.
  170. This condition is broadcasted over the input. At locations where the
  171. condition is `True`, the out array will be set to the ufunc result.
  172. Elsewhere, the out array will retain its original value. Note that
  173. if an uninitialized out array is created via the default ``out=None``,
  174. locations within it where the condition is `False` will remain
  175. uninitialized.
  176. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  177. output Tensor.
  178. Returns:
  179. Tensor, the corresponding angle in radians. This is a tensor scalar if `x`
  180. is a tensor scalar.
  181. Raises:
  182. TypeError: if `x` is not a tensor.
  183. Supported Platforms:
  184. ``Ascend`` ``GPU`` ``CPU``
  185. Examples:
  186. >>> import mindspore.numpy as np
  187. >>> x = np.asarray([1, 2, 3, -4, -5])
  188. >>> output = np.deg2rad(x)
  189. >>> print(output)
  190. [ 0.01745329 0.03490658 0.05235988 -0.06981317 -0.08726647]
  191. """
  192. _check_input_tensor(x)
  193. def convert(a):
  194. return a * pi / 180.0
  195. return _apply_tensor_op(convert, x, out=out, where=where, dtype=dtype)
  196. def rad2deg(x, out=None, where=True, dtype=None):
  197. """
  198. Converts angles from radians to degrees.
  199. Args:
  200. x (Tensor): Angles in radians.
  201. out (Tensor or None, optional): defaults to None.
  202. where (Tensor or None, optional): For any non-default value of type other
  203. than :class:`Tensor` or :class:`None`, the output retains its original value.
  204. This condition is broadcasted over the input. At locations where the
  205. condition is `True`, the out array will be set to the ufunc result.
  206. Elsewhere, the out array will retain its original value. Note that
  207. if an uninitialized out array is created via the default ``out=None``,
  208. locations within it where the condition is `False` will remain
  209. uninitialized.
  210. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  211. output Tensor.
  212. Returns:
  213. Tensor, the corresponding angle in degrees. This is a tensor scalar if `x`
  214. is a tensor scalar.
  215. Raises:
  216. TypeError: if the input is not a tensor.
  217. Supported Platforms:
  218. ``Ascend`` ``GPU`` ``CPU``
  219. Examples:
  220. >>> x = np.asarray([1, 2, 3, -4, -5])
  221. >>> output = np.rad2deg(x)
  222. >>> print(output)
  223. [ 57.295776 114.59155 171.88733 -229.1831 -286.47888 ]
  224. """
  225. _check_input_tensor(x)
  226. def convert(a):
  227. return a * 180.0 / pi
  228. return _apply_tensor_op(convert, x, out=out, where=where, dtype=dtype)
  229. def add(x1, x2, out=None, where=True, dtype=None):
  230. """
  231. Adds arguments element-wise.
  232. Note:
  233. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  234. not supported.
  235. When `where` is provided, `out` must have a tensor value. `out` is not supported
  236. for storing the result, however it can be used in combination with `where` to set
  237. the value at indices for which `where` is set to False.
  238. Args:
  239. x1 (Tensor): input to be added.
  240. x2 (Tensor): input to be added.
  241. out (Tensor or None, optional): defaults to None.
  242. where (Tensor or None, optional): For any non-default value of type other
  243. than :class:`Tensor` or :class:`None`, the output retains its original value.
  244. This condition is broadcasted over the input. At locations where the
  245. condition is `True`, the out array will be set to the ufunc result.
  246. Elsewhere, the out array will retain its original value. Note that
  247. if an uninitialized out array is created via the default ``out=None``,
  248. locations within it where the condition is `False` will remain
  249. uninitialized.
  250. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  251. output Tensor.
  252. Returns:
  253. Tensor or scalar, the sum of `x1` and `x2`, element-wise. This is a scalar
  254. if both `x1` and `x2` are scalars.
  255. Raises:
  256. TypeError: if the input is not a tensor.
  257. Supported Platforms:
  258. ``Ascend`` ``GPU`` ``CPU``
  259. Examples:
  260. >>> x1 = np.full((3, 2), [1, 2])
  261. >>> x2 = np.full((3, 2), [3, 4])
  262. >>> output = np.add(x1, x2)
  263. >>> print(output)
  264. [[4, 6],
  265. [4, 6],
  266. [4, 6]]
  267. """
  268. # broadcast is not fully supported in tensor_add on CPU,
  269. # so we use tensor_sub as a substitute solution
  270. if _get_device() == 'CPU':
  271. _check_input_tensor(x1, x2)
  272. return subtract(x1, F.neg_tensor(x2), out=out, where=where, dtype=dtype)
  273. return _apply_tensor_op(F.tensor_add, x1, x2, out=out, where=where, dtype=dtype)
  274. def subtract(x1, x2, out=None, where=True, dtype=None):
  275. """
  276. Subtracts arguments, element-wise.
  277. Note:
  278. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  279. not supported.
  280. When `where` is provided, `out` must have a tensor value. `out` is not supported
  281. for storing the result, however it can be used in combination with `where` to set
  282. the value at indices for which `where` is set to False.
  283. Args:
  284. x1 (Tensor): the input to be subtracted from.
  285. x2 (Tensor): the input to be subtracted by.
  286. out (Tensor or None, optional): defaults to None.
  287. where (Tensor or None, optional): For any non-default value of type other
  288. than :class:`Tensor` or :class:`None`, the output retains its original value.
  289. This condition is broadcasted over the input. At locations where the
  290. condition is `True`, the out array will be set to the ufunc result.
  291. Elsewhere, the out array will retain its original value. Note that
  292. if an uninitialized out array is created via the default ``out=None``,
  293. locations within it where the condition is `False` will remain
  294. uninitialized.
  295. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  296. output Tensor.
  297. Returns:
  298. Tensor or scalar, the difference of `x1` and `x2`, element-wise. This is a
  299. scalar if both `x1` and `x2` are scalars.
  300. Raises:
  301. TypeError: if the input is not a tensor.
  302. Supported Platforms:
  303. ``Ascend`` ``GPU`` ``CPU``
  304. Examples:
  305. >>> x1 = np.full((3, 2), [1, 2])
  306. >>> x2 = np.full((3, 2), [3, 4])
  307. >>> output = np.subtract(x1, x2)
  308. >>> print(output)
  309. [[-2, -2],
  310. [-2, -2],
  311. [-2, -2]]
  312. """
  313. return _apply_tensor_op(F.tensor_sub, x1, x2, out=out, where=where, dtype=dtype)
  314. def multiply(x1, x2, out=None, where=True, dtype=None):
  315. """
  316. Multiplies arguments element-wise.
  317. Note:
  318. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  319. not supported.
  320. When `where` is provided, `out` must have a tensor value. `out` is not supported
  321. for storing the result, however it can be used in combination with `where` to set
  322. the value at indices for which `where` is set to False.
  323. Args:
  324. x1 (Tensor): input tensor to be multiplied.
  325. x2 (Tensor): input tensor to be multiplied.
  326. out (Tensor or None, optional): defaults to None.
  327. where (Tensor or None, optional): For any non-default value of type other
  328. than :class:`Tensor` or :class:`None`, the output retains its original value.
  329. This condition is broadcasted over the input. At locations where the
  330. condition is `True`, the out array will be set to the ufunc result.
  331. Elsewhere, the out array will retain its original value. Note that
  332. if an uninitialized out array is created via the default ``out=None``,
  333. locations within it where the condition is `False` will remain
  334. uninitialized.
  335. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  336. output Tensor.
  337. Returns:
  338. Tensor or scalar, the product of `x1` and `x2`, element-wise. This is a scalar
  339. if both `x1` and `x2` are scalars.
  340. Raises:
  341. TypeError: if the input is not a tensor.
  342. Supported Platforms:
  343. ``Ascend`` ``GPU`` ``CPU``
  344. Examples:
  345. >>> x1 = np.full((3, 2), [1, 2])
  346. >>> x2 = np.full((3, 2), [3, 4])
  347. >>> output = np.multiply(x1, x2)
  348. >>> print(output)
  349. [[3, 8],
  350. [3, 8],
  351. [3, 8]]
  352. """
  353. if _get_device() == 'CPU':
  354. _check_input_tensor(x1, x2)
  355. # broadcast is not fully supported on CPU backend,
  356. # and explicit broadcasting is performed
  357. shape_out = _infer_out_shape(F.shape(x1), F.shape(x2))
  358. x1 = _broadcast_to_shape(x1, shape_out)
  359. x2 = _broadcast_to_shape(x2, shape_out)
  360. return _apply_tensor_op(F.tensor_mul, x1, x2, out=out, where=where, dtype=dtype)
  361. def divide(x1, x2, out=None, where=True, dtype=None):
  362. """
  363. Returns a true division of the inputs, element-wise.
  364. Instead of the Python traditional ‘floor division’, this returns a true
  365. division.
  366. Note:
  367. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  368. not supported.
  369. When `where` is provided, `out` must have a tensor value. `out` is not supported
  370. for storing the result, however it can be used in combination with `where` to set
  371. the value at indices for which `where` is set to False.
  372. Args:
  373. x1 (Tensor): the divident.
  374. x2 (Tensor): the divisor.
  375. out (Tensor or None, optional): defaults to None.
  376. where (Tensor or None, optional): For any non-default value of type other
  377. than :class:`Tensor` or :class:`None`, the output retains its original value.
  378. This condition is broadcasted over the input. At locations where the
  379. condition is `True`, the out array will be set to the ufunc result.
  380. Elsewhere, the out array will retain its original value. Note that
  381. if an uninitialized out array is created via the default ``out=None``,
  382. locations within it where the condition is `False` will remain
  383. uninitialized.
  384. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  385. output Tensor.
  386. Returns:
  387. Tensor or scalar, this is a scalar if both `x1` and `x2` are scalars.
  388. Raises:
  389. TypeError: if the input is not a tensor.
  390. Supported Platforms:
  391. ``Ascend`` ``GPU`` ``CPU``
  392. Examples:
  393. >>> x1 = np.full((3, 2), [1, 2])
  394. >>> x2 = np.full((3, 2), [3, 4])
  395. >>> output = np.divide(x1, x2)
  396. >>> print(output)
  397. [[0.33333333, 0.5],
  398. [0.33333333, 0.5],
  399. [0.33333333, 0.5]]
  400. """
  401. if not _check_is_float(F.dtype(x1)) and not _check_is_float(F.dtype(x2)):
  402. x1 = F.cast(x1, mstype.float32)
  403. x2 = F.cast(x2, mstype.float32)
  404. return _apply_tensor_op(F.tensor_div, x1, x2, out=out, where=where, dtype=dtype)
  405. def true_divide(x1, x2, out=None, where=True, dtype=None):
  406. """
  407. Returns a true division of the inputs, element-wise.
  408. Instead of the Python traditional ‘floor division’, this returns a true
  409. division.
  410. Note:
  411. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  412. not supported.
  413. When `where` is provided, `out` must have a tensor value. `out` is not supported
  414. for storing the result, however it can be used in combination with `where` to set
  415. the value at indices for which `where` is set to False.
  416. Args:
  417. x1 (Tensor): the divident.
  418. x2 (Tensor): the divisor.
  419. out (Tensor or None, optional)
  420. where (Tensor, optional):
  421. This condition is broadcast over the input. At locations where the
  422. condition is True, the out array will be set to the ufunc result.
  423. Elsewhere, the out array will retain its original value. Note that
  424. if an uninitialized out array is created via the default out=None,
  425. locations within it where the condition is False will remain
  426. uninitialized.
  427. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  428. output Tensor.
  429. Returns:
  430. Tensor or scalar, this is a scalar if both `x1` and `x2` are scalars.
  431. Raises:
  432. TypeError: if the input is not a tensor.
  433. Supported Platforms:
  434. ``Ascend`` ``GPU`` ``CPU``
  435. Examples:
  436. >>> x1 = np.full((3, 2), [1, 2])
  437. >>> x2 = np.full((3, 2), [3, 4])
  438. >>> output = np.true_divide(x1, x2)
  439. >>> print(output)
  440. [[0.33333333, 0.5],
  441. [0.33333333, 0.5],
  442. [0.33333333, 0.5]]
  443. """
  444. return divide(x1, x2, out=out, where=where, dtype=dtype)
  445. def power(x1, x2, out=None, where=True, dtype=None):
  446. """
  447. First array elements raised to powers from second array, element-wise.
  448. Raises each base in `x1` to the positionally-corresponding power in `x2`.
  449. Note:
  450. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  451. not supported.
  452. When `where` is provided, `out` must have a tensor value. `out` is not supported
  453. for storing the result, however it can be used in combination with `where` to set
  454. the value at indices for which `where` is set to False.
  455. On GPU, the supported dtypes are np.float16, and np.float32.
  456. Args:
  457. x1 (Tensor): the bases.
  458. x2 (Tensor): the exponents.
  459. out (Tensor or None, optional): defaults to None.
  460. where (Tensor or None, optional): For any non-default value of type other
  461. than :class:`Tensor` or :class:`None`, the output retains its original value.
  462. This condition is broadcasted over the input. At locations where the
  463. condition is `True`, the out array will be set to the ufunc result.
  464. Elsewhere, the out array will retain its original value. Note that
  465. if an uninitialized out array is created via the default ``out=None``,
  466. locations within it where the condition is `False` will remain
  467. uninitialized.
  468. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  469. output Tensor.
  470. Returns:
  471. Tensor or scalar, the bases in `x1` raised to the exponents in `x2`. This
  472. is a scalar if both `x1` and `x2` are scalars.
  473. Raises:
  474. TypeError: if the input is not a tensor.
  475. Supported Platforms:
  476. ``Ascend`` ``GPU`` ``CPU``
  477. Examples:
  478. >>> x1 = np.full((3, 2), [1, 2]).astype('float32')
  479. >>> x2 = np.full((3, 2), [3, 4]).astype('float32')
  480. >>> output = np.power(x1, x2)
  481. >>> print(output)
  482. [[ 1, 16],
  483. [ 1, 16],
  484. [ 1, 16]]
  485. """
  486. return _apply_tensor_op(F.tensor_pow, x1, x2, out=out, where=where, dtype=dtype)
  487. def float_power(x1, x2, out=None, where=True, dtype=None):
  488. """
  489. First array elements raised to powers from second array, element-wise.
  490. Raise each base in `x1` to the positionally-corresponding power in `x2`. `x1` and
  491. `x2` must be broadcastable to the same shape. This differs from the power
  492. function in that integers, float16, and float64 are promoted to floats with
  493. a minimum precision of float32 so that the result is always inexact. The
  494. intent is that the function will return a usable result for negative powers
  495. and seldom overflow for positive powers.
  496. Note:
  497. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  498. not supported.
  499. When `where` is provided, `out` must have a tensor value. `out` is not supported
  500. for storing the result, however it can be used in combination with `where` to set
  501. the value at indices for which `where` is set to False.
  502. Integers and floats are promoted to float32 instead of float64.
  503. Args:
  504. x1 (Tensor): the bases.
  505. x2 (Tensor): the exponenets.
  506. out (Tensor or None, optional): defaults to None.
  507. where (Tensor or None, optional): For any non-default value of type other
  508. than :class:`Tensor` or :class:`None`, the output retains its original value.
  509. This condition is broadcasted over the input. At locations where the
  510. condition is `True`, the out array will be set to the ufunc result.
  511. Elsewhere, the out array will retain its original value. Note that
  512. if an uninitialized out array is created via the default ``out=None``,
  513. locations within it where the condition is `False` will remain
  514. uninitialized.
  515. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  516. output Tensor.
  517. Returns:
  518. Tensor or scalar, the bases in `x1` raised to the exponents in `x2`. This
  519. is a scalar if both `x1` and `x2` are scalars.
  520. Raises:
  521. TypeError: if the input is not a tensor.
  522. Supported Platforms:
  523. ``Ascend`` ``GPU`` ``CPU``
  524. Examples:
  525. >>> x1 = np.arange(6)
  526. >>> x2 = np.array(3)
  527. >>> output = np.float_power(x1, x2)
  528. >>> print(output)
  529. [ 0. 1. 8. 27. 64. 125.]
  530. """
  531. if not _check_same_type(F.dtype(x1), mstype.float32):
  532. x1 = F.cast(x1, mstype.float32)
  533. if not _check_same_type(F.dtype(x2), mstype.float32):
  534. x2 = F.cast(x2, mstype.float32)
  535. return _apply_tensor_op(F.tensor_pow, x1, x2, out=out, where=where, dtype=dtype)
  536. def minimum(x1, x2, out=None, where=True, dtype=None):
  537. """
  538. Element-wise minimum of tensor elements.
  539. Compares two tensors and returns a new tensor containing the element-wise minima.
  540. Note:
  541. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  542. not supported.
  543. When `where` is provided, `out` must have a tensor value. `out` is not supported
  544. for storing the result, however it can be used in combination with `where` to set
  545. the value at indices for which `where` is set to False.
  546. Unlike numpy, when one of the elements is a NaN, the second element is
  547. always returned regardless of whether the second element is a NaN, instead
  548. of returning NaN.
  549. Args:
  550. x1 (Tensor): first input tensor to be compared.
  551. x2 (Tensor): second input tensor to be compared.
  552. out (Tensor or None, optional), default is None.
  553. where (Tensor or None, optional): For any non-default value of type other
  554. than :class:`Tensor` or :class:`None`, the output retains its original value.
  555. This condition is broadcasted over the input. At locations where the
  556. condition is `True`, the out array will be set to the ufunc result.
  557. Elsewhere, the out array will retain its original value. Note that
  558. if an uninitialized out array is created via the default ``out=None``,
  559. locations within it where the condition is `False` will remain
  560. uninitialized.
  561. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  562. output Tensor.
  563. Returns:
  564. Tensor, element-wise minimum of `x1` and `x2`.
  565. Raises:
  566. TypeError: If inputs have types not specified above.
  567. ValueError: If the shapes of `x1` and `x2` cannot be broadcast.
  568. Supported Platforms:
  569. ``Ascend`` ``GPU`` ``CPU``
  570. Examples:
  571. >>> import mindspore.numpy as np
  572. >>> a = np.asarray([1, 2])
  573. >>> b = np.asarray([[1, 3],[1, 4]])
  574. >>> print(np.minimum(a, b))
  575. [[1 2]
  576. [1 2]]
  577. """
  578. if isinstance(x1, (int, float, bool, list, tuple)):
  579. x1 = asarray_const(x1)
  580. elif not isinstance(x1, Tensor):
  581. _raise_type_error("Input x1 is expected to be array_like")
  582. if isinstance(x2, (int, float, bool, list, tuple)):
  583. x2 = asarray_const(x2)
  584. elif not isinstance(x2, Tensor):
  585. _raise_type_error("Input x2 is expected to be array_like")
  586. # if both are scalars, expand x1 to 1d tensor, since cpu kernel doesn't support
  587. # comparisons with 2 scalars
  588. if x1.ndim == 0 and x2.ndim == 0:
  589. x1 = expand_dims(x1, 0)
  590. return _apply_tensor_op(F.minimum, x1, x2, out=out, where=where, dtype=dtype).squeeze()
  591. if x1.ndim == 0:
  592. dtype = x2.dtype
  593. elif x2.ndim == 0:
  594. dtype = x1.dtype
  595. return _apply_tensor_op(F.minimum, x1, x2, out=out, where=where, dtype=dtype)
  596. def mean(a, axis=None, keepdims=False, dtype=None):
  597. """
  598. Computes the arithmetic mean along the specified axis.
  599. Returns the average of the array elements. The average is taken
  600. over the flattened array by default, otherwise over the specified
  601. axis.
  602. Note:
  603. Numpy arguments `out` is not supported.
  604. On GPU, the supported dtypes are np.float16, and np.float32.
  605. Args:
  606. a (Tensor): input tensor containing numbers whose mean is desired.
  607. If a is not an array, a conversion is attempted.
  608. axis (None or int or tuple of ints, optional): Axis or axes along
  609. which the means are computed. The default is to compute
  610. the mean of the flattened array. If this is a tuple of
  611. ints, a mean is performed over multiple axes.
  612. keepdims (bool, optional): If this is set to True, the axes which
  613. are reduced are left in the result as dimensions with
  614. size one. With this option, the result will broadcast
  615. correctly against the input tensor.
  616. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  617. output Tensor.
  618. Returns:
  619. Tensor or scalar, an array containing the mean values.
  620. Raises:
  621. ValueError: if axes are out of the range of ``[-a.ndim, a.ndim)``, or
  622. if the axes contain duplicates.
  623. Supported Platforms:
  624. ``Ascend`` ``GPU`` ``CPU``
  625. Examples:
  626. >>> import mindspore.numpy as np
  627. >>> a = np.arange(6, dtype='float32')
  628. >>> output = np.mean(a, 0)
  629. >>> print(output)
  630. 2.5
  631. """
  632. axis = _check_axis_valid(axis, F.rank(a))
  633. shape_a = F.shape(a)
  634. if dtype is None:
  635. dtype = F.dtype(a)
  636. if _is_shape_empty(shape_a):
  637. if keepdims:
  638. shape_out = _shape_reduced_keepdims(shape_a, axis)
  639. else:
  640. shape_out = _shape_reduced(shape_a, axis)
  641. if _is_shape_empty(shape_out):
  642. return empty(F.dtype(a), shape_out)
  643. return full(shape_out, nan, dtype)
  644. if _is_scalar(shape_a):
  645. if keepdims:
  646. return a
  647. shape_out = _shape_reduced(shape_a, axis)
  648. return F.reshape(a, shape_out)
  649. if keepdims:
  650. res = _mean_keepdims(a, axis)
  651. else:
  652. res = _mean_default(a, axis)
  653. if not _check_same_type(dtype, F.dtype(res)):
  654. res = F.cast(res, dtype)
  655. return res
  656. def inner(a, b):
  657. """
  658. Returns the inner product of two tensors.
  659. Ordinary inner product of vectors for 1-D tensors (without complex
  660. conjugation), in higher dimensions a sum product over the last
  661. axes.
  662. Note:
  663. Numpy argument `out` is not supported.
  664. On GPU, the supported dtypes are np.float16, and np.float32.
  665. On CPU, the supported dtypes are np.float16, np.float32, and
  666. np.float64.
  667. Args:
  668. a (Tensor): input tensor. If `a` and `b` are nonscalar, their last
  669. dimensions must match.
  670. b (Tensor): input tensor. If `a` and `b` are nonscalar, their last
  671. dimensions must match.
  672. Returns:
  673. Tensor or scalar.
  674. Raises:
  675. ValueError: if ``x1.shape[-1] != x2.shape[-1]``.
  676. Supported Platforms:
  677. ``Ascend`` ``GPU`` ``CPU``
  678. Examples:
  679. >>> import mindspore.numpy as np
  680. >>> a = np.ones((5, 3))
  681. >>> b = np.ones((2, 7, 3))
  682. >>> output = np.inner(a, b)
  683. >>> print(output)
  684. [[[3. 3. 3. 3. 3. 3. 3.]
  685. [3. 3. 3. 3. 3. 3. 3.]]
  686. [[3. 3. 3. 3. 3. 3. 3.]
  687. [3. 3. 3. 3. 3. 3. 3.]]
  688. [[3. 3. 3. 3. 3. 3. 3.]
  689. [3. 3. 3. 3. 3. 3. 3.]]
  690. [[3. 3. 3. 3. 3. 3. 3.]
  691. [3. 3. 3. 3. 3. 3. 3.]]
  692. [[3. 3. 3. 3. 3. 3. 3.]
  693. [3. 3. 3. 3. 3. 3. 3.]]]
  694. """
  695. if F.rank(a) == 0 or F.rank(b) == 0:
  696. return F.tensor_mul(a, b)
  697. _check_shape_aligned(F.shape(a), F.shape(b))
  698. aligned_shape_a = (F.shape_mul(F.shape(a)[:-1]), F.shape(a)[-1])
  699. aligned_shape_b = (F.shape_mul(F.shape(b)[:-1]), F.shape(a)[-1])
  700. a_aligned = F.reshape(a, aligned_shape_a)
  701. b_aligned = F.reshape(b, aligned_shape_b)
  702. res = _matmul_T(a_aligned, b_aligned)
  703. res = F.reshape(res, F.shape(a)[:-1] + F.shape(b)[:-1])
  704. return res
  705. def dot(a, b):
  706. """
  707. Returns the dot product of two arrays.
  708. Specifically,
  709. If both `a` and `b` are 1-D arrays, it is inner product of vectors
  710. (without complex conjugation).
  711. If both `a` and `b` are 2-D arrays, it is matrix multiplication.
  712. If either `a` or `b` is 0-D (scalar), it is equivalent to multiply.
  713. If `a` is an `N-D` array and `b` is a 1-D array, it is a sum product
  714. over the last axis of `a` and `b`.
  715. If `a` is an `N-D` array and `b` is an `M-D` array (where ``M>=2``), it is a
  716. sum product over the last axis of `a` and the second-to-last axis of `b`:
  717. ``dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])``
  718. Note:
  719. Numpy argument `out` is not supported.
  720. On GPU, the supported dtypes are np.float16, and np.float32.
  721. On CPU, the supported dtypes are np.float16, np.float32, and
  722. np.float64.
  723. Args:
  724. a (Tensor): input tensor
  725. b (Tensor): input tensor
  726. Returns:
  727. Tensor or scalar, the dot product of `a` and `b`. If `a` and `b` are
  728. both scalars or both 1-D arrays then a scalar is returned;
  729. otherwise an array is returned
  730. Raises:
  731. ValueError: If the last dimension of `a` is not the same size
  732. as the second-to-last dimension of `b`.
  733. Supported Platforms:
  734. ``Ascend`` ``GPU`` ``CPU``
  735. Examples:
  736. >>> import mindspore.numpy as np
  737. >>> a = np.full((1, 3), 7).astype('float32')
  738. >>> b = np.full((2, 3, 4), 5).astype('float32')
  739. >>> output = np.dot(a, b)
  740. >>> print(output)
  741. [[[105, 105, 105, 105],
  742. [105, 105, 105, 105]]]
  743. """
  744. ndim_a, ndim_b = F.rank(a), F.rank(b)
  745. if ndim_a > 0 and ndim_b >= 2:
  746. perm = F.make_range(ndim_b)
  747. perm = perm[:-2] + (perm[-1],) + (perm[-2],)
  748. b = F.transpose(b, perm)
  749. return inner(a, b)
  750. def outer(a, b):
  751. """
  752. Computes the outer product of two vectors.
  753. Given two vectors, ``a = [a0, a1, ..., aM]`` and ``b = [b0, b1, ..., bN]``,
  754. the outer product is:
  755. ``[[a0*b0 a0*b1 ... a0*bN ]``
  756. ``[a1*b0 . ]``
  757. ``[ ... . ]``
  758. ``[aM*b0 aM*bN ]]``
  759. Note:
  760. Numpy argument ``out`` is not supported.
  761. On GPU, the supported dtypes are np.float16, and np.float32.
  762. On CPU, the supported dtypes are np.float16, np.float32, and
  763. np.float64.
  764. Args:
  765. a (Tensor): first input vector. Input is flattened if not
  766. already 1-dimensional.
  767. b (Tensor): second input vector. Input is flattened if not
  768. already 1-dimensional.
  769. Returns:
  770. Tensor or scalar, ``out[i, j] = a[i] * b[j]``.
  771. Raises:
  772. TypeError: if the input is not a tensor.
  773. Supported Platforms:
  774. ``Ascend`` ``GPU`` ``CPU``
  775. Examples:
  776. >>> import mindspore.numpy as np
  777. >>> a = np.full(7, 2).astype('float32')
  778. >>> b = np.full(4, 3).astype('float32')
  779. >>> output = np.outer(a, b)
  780. >>> print(output)
  781. [[6, 6, 6, 6],
  782. [6, 6, 6, 6],
  783. [6, 6, 6, 6],
  784. [6, 6, 6, 6],
  785. [6, 6, 6, 6],
  786. [6, 6, 6, 6],
  787. [6, 6, 6, 6]]
  788. """
  789. _check_input_tensor(a, b)
  790. if F.rank(a) != 1:
  791. a = ravel(a)
  792. if F.rank(b) != 1:
  793. b = ravel(b)
  794. a = F.reshape(a, (F.shape(a)[0], 1))
  795. b = _expand(b, 2)
  796. return _matmul(a, b)
  797. def tensordot(a, b, axes=2):
  798. """
  799. Computes tensor dot product along specified axes.
  800. Given two tensors, `a` and `b`, and an array_like object containing two array_like
  801. objects, `(a_axes, b_axes)`, sum the products of `a`’s and `b`’s elements (components)
  802. over the axes specified by `a_axes` and `b_axes`. The third argument can be a single
  803. non-negative integer_like scalar, `N`; if it is such, then the last `N` dimensions of
  804. `a` and the first `N` dimensions of `b` are summed over.
  805. Three common use cases are:
  806. ``axes = 0`` : tensor product
  807. ``axes = 1`` : tensor dot product
  808. ``axes = 2`` : (default) tensor double contraction
  809. When axes is integer_like, the sequence for evaluation will be: first the `-Nth`
  810. axis in `a` and 0th axis in `b`, and the -1th axis in `a` and `Nth` axis in `b` last.
  811. When there is more than one axis to sum over - and they are not the last (first)
  812. axes of `a` `(b)` - the argument axes should consist of two sequences of the same
  813. length, with the first axis to sum over given first in both sequences, the second
  814. axis second, and so forth.
  815. The shape of the result consists of the non-contracted axes of the first tensor,
  816. followed by the non-contracted axes of the second.
  817. Note:
  818. On CPU, the supported dypes are np.float16 and np.float32.
  819. On GPU, the supported dypes are np.float16 and np.float32.
  820. Args:
  821. a (Tensor): Tensor to "dot".
  822. b (Tensor): Tensor to “dot”.
  823. axes (int or sequence of ints):
  824. integer_like: If an int `N`, sum over the last `N` axes of `a` and the first `N`
  825. axes of `b` in order. The sizes of the corresponding axes must match.
  826. sequence of ints: Or, a list of axes to be summed over, first sequence
  827. applying to `a`, second to `b`. Both elements `array_like` must be of the same
  828. length.
  829. Returns:
  830. Tensor, or list of tensors, the tensor dot product of the input.
  831. Supported Platforms:
  832. ``Ascend`` ``GPU`` ``CPU``
  833. Examples:
  834. >>> a = np.ones((3, 4, 5))
  835. >>> b = np.ones((4, 3, 2))
  836. >>> output = np.tensordot(a, b, axes=([1,0],[0,1]))
  837. >>> print(output.shape)
  838. (5, 2)
  839. """
  840. if F.rank(a)*F.rank(b) == 0 and axes == 0:
  841. return F.tensor_mul(a, b)
  842. return C.tensor_dot(a, b, axes)
  843. def std(x, axis=None, ddof=0, keepdims=False):
  844. """
  845. Computes the standard deviation along the specified axis.
  846. The standard deviation is the square root of the average of the squared deviations
  847. from the mean, i.e., :math:`std = sqrt(mean(abs(x - x.mean())**2))`.
  848. Returns the standard deviation, which is computed for the flattened array by default,
  849. otherwise over the specified axis.
  850. Note:
  851. Numpy arguments `dtype` and `out` are not supported.
  852. Args:
  853. x (Tensor): A Tensor to be calculated.
  854. axis (Union[None, int, tuple(int)]): Axis or axes along which the standard
  855. deviation is computed. Default: `None`.
  856. If `None`, compute the standard deviation of the flattened array.
  857. ddof (int): Means Delta Degrees of Freedom. The divisor used in calculations is :math:`N - ddof`,
  858. where :math:`N` represents the number of elements. Default: 0.
  859. keepdims: Default: `False`.
  860. Returns:
  861. Standard deviation tensor.
  862. Supported Platforms:
  863. ``Ascend`` ``GPU`` ``CPU``
  864. Examples:
  865. >>> import mindspore.numpy as np
  866. >>> input_x = np.array([1., 2., 3., 4.])
  867. >>> output = np.std(input_x)
  868. >>> print(output)
  869. 1.118034
  870. """
  871. if _is_shape_empty(x.shape):
  872. return full((), nan, F.dtype(x))
  873. if not isinstance(ddof, int):
  874. _raise_type_error("integer argument expected, but got ", ddof)
  875. if not isinstance(keepdims, int):
  876. _raise_type_error("integer argument expected, but got ", keepdims)
  877. if axis is None:
  878. axis = ()
  879. else:
  880. _check_axis_type(axis, True, True, False)
  881. axis = _canonicalize_axis(axis, x.ndim)
  882. x_mean = _mean_keepdims(x, axis)
  883. x_sub = F.tensor_sub(x, x_mean)
  884. x_pow = F.tensor_pow(x_sub, 2)
  885. if keepdims:
  886. x_sum = _reduce_sum_keepdims(x_pow, axis)
  887. else:
  888. x_sum = _reduce_sum_default(x_pow, axis)
  889. if isinstance(axis, int):
  890. nums = x.shape[axis]
  891. else:
  892. nums = _get_size(x, axis)
  893. x_std = F.tensor_pow(F.tensor_div(x_sum, nums - ddof), 0.5)
  894. return x_std
  895. def var(x, axis=None, ddof=0, keepdims=False):
  896. """
  897. Computes the variance along the specified axis.
  898. The variance is the average of the squared deviations from the mean, i.e.,
  899. :math:`var = mean(abs(x - x.mean())**2)`.
  900. Returns the variance, which is computed for the flattened array by default,
  901. otherwise over the specified axis.
  902. Note:
  903. Numpy arguments `dtype` and `out` are not supported.
  904. Args:
  905. x (Tensor): A Tensor to be calculated.
  906. axis (Union[None, int, tuple(int)]): Axis or axes along which the variance is computed.
  907. The default is to compute the variance of the flattened array. Default: `None`.
  908. ddof (int): Means Delta Degrees of Freedom. Default: 0.
  909. The divisor used in calculations is :math:`N - ddof`, where :math:`N` represents the number of elements.
  910. keepdims (bool): Default: `False`.
  911. Supported Platforms:
  912. ``Ascend`` ``GPU`` ``CPU``
  913. Returns:
  914. Standard deviation tensor.
  915. Examples:
  916. >>> import mindspore.numpy as np
  917. >>> input_x = np.array([1., 2., 3., 4.])
  918. >>> output = np.var(input_x)
  919. >>> print(output)
  920. 1.25
  921. """
  922. if _is_shape_empty(x.shape):
  923. return full((), nan, F.dtype(x))
  924. x_std = std(x, axis, ddof, keepdims)
  925. return F.tensor_pow(x_std, 2)
  926. def ptp(x, axis=None, out=None, keepdims=False):
  927. """
  928. Range of values (maximum - minimum) along an axis.
  929. The name of the function comes from the acronym for ‘peak to peak’.
  930. Note:
  931. Numpy arguments `dtype` and `out` are not supported.
  932. Args:
  933. x (Tensor): Input tensor.
  934. axis (Union[None, int, tuple(int)]): Axis or axes along which the range is computed.
  935. The default is to compute the variance of the flattened array. Default: None.
  936. keepdims (bool): Default is False.
  937. Returns:
  938. Tensor.
  939. Raises:
  940. TypeError: if inputs have types not specified above.
  941. Supported Platforms:
  942. ``Ascend`` ``GPU`` ``CPU``
  943. Examples:
  944. >>> import mindspore.numpy as np
  945. >>> x = np.array([[4.0, 9.0, 2.0, 10.0], [6.0, 9.0, 7.0, 12.0]])
  946. >>> print(np.ptp(x, axis=1))
  947. [8. 6.]
  948. >>> print(np.ptp(x, axis=0))
  949. [2. 0. 5. 2.]
  950. """
  951. _check_input_tensor(x)
  952. if not isinstance(keepdims, bool):
  953. _raise_type_error('keepdims should be boolean')
  954. if axis is None:
  955. axis = ()
  956. else:
  957. _check_axis_type(axis, True, True, False)
  958. axis = _check_axis_valid(axis, x.ndim)
  959. if keepdims:
  960. x_min = _reduce_min_keepdims(x, axis)
  961. x_max = _reduce_max_keepdims(x, axis)
  962. else:
  963. x_min = _reduce_min_default(x, axis)
  964. x_max = _reduce_max_default(x, axis)
  965. return F.tensor_sub(x_max, x_min)
  966. def average(x, axis=None, weights=None, returned=False):
  967. """
  968. Computes the weighted average along the specified axis.
  969. Args:
  970. x (Tensor): A Tensor to be averaged.
  971. axis (Union[None, int, tuple(int)]): Axis along which to average `x`. Default: `None`.
  972. If the axis is `None`, it will average over all of the elements of the tensor `x`.
  973. If the axis is negative, it counts from the last to the first axis.
  974. weights (Union[None, Tensor]): Weights associated with the values in `x`. Default: `None`.
  975. If `weights` is `None`, all the data in `x` are assumed to have a weight equal to one.
  976. If `weights` is 1-D tensor, the length must be the same as the given axis.
  977. Otherwise, `weights` should have the same shape as `x`.
  978. returned (bool): Default: `False`.
  979. If `True`, the tuple (average, sum_of_weights) is returned.
  980. If `False`, only the average is returned.
  981. Returns:
  982. Averaged Tensor. If returned is `True`, return tuple.
  983. Supported Platforms:
  984. ``Ascend`` ``GPU`` ``CPU``
  985. Examples:
  986. >>> import mindspore.numpy as np
  987. >>> input_x = np.array([[1., 2.], [3., 4.]])
  988. >>> output = np.average(input_x, axis=0, weights=input_x, returned=True)
  989. >>> print(output)
  990. (Tensor(shape=[2], dtype=Float32, value= [ 2.50000000e+00, 3.33333325e+00]),
  991. Tensor(shape=[2], dtype=Float32, value= [ 4.00000000e+00, 6.00000000e+00]))
  992. """
  993. _check_input_tensor(x)
  994. if axis is None:
  995. axis = ()
  996. else:
  997. _check_axis_type(axis, True, True, False)
  998. axis = _canonicalize_axis(axis, x.ndim)
  999. x_avg = full((), nan, F.dtype(x))
  1000. sum_of_weights = None
  1001. if weights is None:
  1002. x_avg = mean(x, axis)
  1003. if axis is None:
  1004. sum_of_weights = full((), x.size, F.dtype(x))
  1005. else:
  1006. fill_value = 1
  1007. if isinstance(axis, int) or isinstance(axis, tuple) and F.tuple_len(axis) == 1:
  1008. fill_value = x.shape[axis]
  1009. elif axis is None or axis == ():
  1010. for sh in x.shape:
  1011. fill_value *= sh
  1012. else:
  1013. for ax in axis:
  1014. fill_value *= x.shape[ax]
  1015. sum_of_weights = full_like(x_avg, fill_value, F.dtype(x))
  1016. else:
  1017. _check_input_tensor(weights)
  1018. if x.shape == weights.shape:
  1019. x_avg, sum_of_weights = comput_avg(x, axis, weights)
  1020. elif F.rank(weights) == 1:
  1021. if not isinstance(axis, int):
  1022. _raise_type_error("Axis must be specified when shapes of x and weights differ.")
  1023. perm = _expanded_shape(x.ndim, weights.shape[0], axis)
  1024. weights = weights.reshape(perm)
  1025. x_avg, sum_of_weights = comput_avg(x, axis, weights)
  1026. else:
  1027. _raise_type_error("Weights should be None, 1-D or the same shape as input x.")
  1028. if returned:
  1029. if x_avg.shape != sum_of_weights.shape:
  1030. sum_of_weights = _broadcast_to(sum_of_weights, sum_of_weights.shape, x_avg.shape, x_avg.ndim)
  1031. return (x_avg, sum_of_weights)
  1032. return x_avg
  1033. def comput_avg(x, axis, weights):
  1034. """Computes average value of input x with given parameters."""
  1035. x_mul = F.tensor_mul(x, weights)
  1036. x_sum = _reduce_sum_default(x_mul, axis)
  1037. sum_of_weights = _reduce_sum_default(weights, axis)
  1038. x_avg = F.tensor_div(x_sum, sum_of_weights)
  1039. return x_avg, sum_of_weights
  1040. def matmul(x1, x2, dtype=None):
  1041. """
  1042. Returns the matrix product of two arrays.
  1043. Note:
  1044. Numpy arguments `out`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  1045. not supported.
  1046. On GPU, the supported dtypes are np.float16 and np.float32.
  1047. On CPU, the supported dtypes are np.float16 and np.float32.
  1048. Args:
  1049. x1 (Tensor): Input tensor, scalar not allowed.
  1050. x2 (Tensor): Input tensor, scalar not allowed.
  1051. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1052. output Tensor.
  1053. Returns:
  1054. Tensor or scalar, the matrix product of the inputs. This is a scalar only
  1055. when both `x1`, `x2` are 1-d vectors.
  1056. Raises:
  1057. ValueError: If the last dimension of `x1` is not the same size as the
  1058. second-to-last dimension of `x2`, or if a scalar value is passed in.
  1059. Supported Platforms:
  1060. ``Ascend`` ``GPU`` ``CPU``
  1061. Examples:
  1062. >>> x1 = np.arange(2*3*4).reshape(2, 3, 4).astype('float32')
  1063. >>> x2 = np.arange(4*5).reshape(4, 5).astype('float32')
  1064. >>> output = np.matmul(x1, x2)
  1065. >>> print(output)
  1066. [[[ 70. 76. 82. 88. 94.]
  1067. [ 190. 212. 234. 256. 278.]
  1068. [ 310. 348. 386. 424. 462.]]
  1069. [[ 430. 484. 538. 592. 646.]
  1070. [ 550. 620. 690. 760. 830.]
  1071. [ 670. 756. 842. 928. 1014.]]]
  1072. """
  1073. return C.matmul(x1, x2, dtype=dtype)
  1074. def square(x, out=None, where=True, dtype=None):
  1075. """
  1076. Returns the element-wise square of the input.
  1077. Note:
  1078. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  1079. not supported.
  1080. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1081. for storing the result, however it can be used in combination with `where` to set
  1082. the value at indices for which `where` is set to False.
  1083. On GPU, the supported dtypes are np.float16 and np.float32.
  1084. Args:
  1085. x (Tensor): Input data.
  1086. out (Tensor or None, optional): defaults to None.
  1087. where (Tensor or None, optional): For any non-default value of type other
  1088. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1089. This condition is broadcasted over the input. At locations where the
  1090. condition is `True`, the out array will be set to the ufunc result.
  1091. Elsewhere, the out array will retain its original value. Note that
  1092. if an uninitialized out array is created via the default ``out=None``,
  1093. locations within it where the condition is `False` will remain
  1094. uninitialized.
  1095. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1096. output Tensor.
  1097. Returns:
  1098. Tensor or scalar, element-wise ``x*x``, of the same shape and dtype as `x`.
  1099. This is a scalar if `x` is a scalar..
  1100. Raises:
  1101. TypeError: if the input is not a tensor.
  1102. Supported Platforms:
  1103. ``Ascend`` ``GPU`` ``CPU``
  1104. Examples:
  1105. >>> x = np.square(np.arange(6).reshape(2, 3).astype('float32'))
  1106. >>> print(x)
  1107. [[ 0. 1. 4.]
  1108. [ 9. 16. 25.]]
  1109. """
  1110. return _apply_tensor_op(F.square, x, out=out, where=where, dtype=dtype)
  1111. def sqrt(x, out=None, where=True, dtype=None):
  1112. """
  1113. Returns the non-negative square-root of an array, element-wise.
  1114. Note:
  1115. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  1116. not supported.
  1117. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1118. for storing the result, however it can be used in combination with `where` to set
  1119. the value at indices for which `where` is set to False.
  1120. On GPU, the supported dtypes are np.float16 and np.float32.
  1121. Args:
  1122. x (Tensor): The values whose square-roots are required.
  1123. out (Tensor or None, optional): defaults to None.
  1124. where (Tensor or None, optional): For any non-default value of type other
  1125. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1126. This condition is broadcasted over the input. At locations where the
  1127. condition is `True`, the out array will be set to the ufunc result.
  1128. Elsewhere, the out array will retain its original value. Note that
  1129. if an uninitialized out array is created via the default ``out=None``,
  1130. locations within it where the condition is `False` will remain
  1131. uninitialized.
  1132. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1133. output Tensor.
  1134. Returns:
  1135. Tensor or scalar, an array of the same shape as `x`, containing the positive
  1136. square-root of each element in `x`. For negative elements, nan is returned.
  1137. This is a scalar if `x` is a scalar.
  1138. Raises:
  1139. TypeError: if the input is not a tensor.
  1140. Supported Platforms:
  1141. ``Ascend`` ``GPU`` ``CPU``
  1142. Examples:
  1143. >>> x = np.arange(6).reshape(2, 3).astype('float32')
  1144. >>> x_squared = np.square(x)
  1145. >>> output = np.sqrt(x_squared)
  1146. >>> print(output)
  1147. [[ 0. 1. 2.]
  1148. [ 3. 4. 5.]]
  1149. """
  1150. return _apply_tensor_op(F.sqrt, x, out=out, where=where, dtype=dtype)
  1151. def reciprocal(x, out=None, where=True, dtype=None):
  1152. """
  1153. Returns the reciprocal of the argument, element-wise.
  1154. Calculates ``1/x``.
  1155. Note:
  1156. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  1157. not supported.
  1158. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1159. for storing the result, however it can be used in combination with `where` to set
  1160. the value at indices for which `where` is set to False.
  1161. Args:
  1162. x (Tensor): Input array. For integer arguments with absolute value larger
  1163. than 1 the result is always zero because of the way Python handles
  1164. integer division. For integer zero the result is an overflow.
  1165. out (Tensor or None, optional): defaults to None.
  1166. where (Tensor or None, optional): For any non-default value of type other
  1167. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1168. This condition is broadcasted over the input. At locations where the
  1169. condition is `True`, the out array will be set to the ufunc result.
  1170. Elsewhere, the out array will retain its original value. Note that
  1171. if an uninitialized out array is created via the default ``out=None``,
  1172. locations within it where the condition is `False` will remain
  1173. uninitialized.
  1174. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1175. output Tensor.
  1176. Returns:
  1177. Tensor or scalar, this is a scalar if `x` is a scalar.
  1178. Raises:
  1179. TypeError: if the input is not a tensor.
  1180. Supported Platforms:
  1181. ``Ascend`` ``GPU`` ``CPU``
  1182. Examples:
  1183. >>> x = np.arange(1, 7).reshape(2, 3).astype('float32')
  1184. >>> output = np.reciprocal(x)
  1185. >>> print(output)
  1186. [[1. 0.5 0.33333334]
  1187. [0.25 0.2 0.16666667]]
  1188. """
  1189. return _apply_tensor_op(lambda x: F.tensor_div(1, x), x, out=out, where=where, dtype=dtype)
  1190. def log(x, out=None, where=True, dtype=None):
  1191. """
  1192. Returns the natural logarithm, element-wise.
  1193. The natural logarithm log is the inverse of the exponential function, so that
  1194. ``log(exp(x)) = x``. The natural logarithm is logarithm in base e.
  1195. Note:
  1196. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  1197. not supported.
  1198. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1199. for storing the result, however it can be used in combination with `where` to set
  1200. the value at indices for which `where` is set to False.
  1201. On GPU, the supported dtypes are np.float16, and np.float32.
  1202. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.
  1203. Args:
  1204. x (Tensor): Input array. For integer arguments with absolute value larger
  1205. than 1 the result is always zero because of the way Python handles
  1206. integer division. For integer zero the result is an overflow.
  1207. out (Tensor or None, optional): defaults to None.
  1208. where (Tensor or None, optional): For any non-default value of type other
  1209. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1210. This condition is broadcasted over the input. At locations where the
  1211. condition is `True`, the out array will be set to the ufunc result.
  1212. Elsewhere, the out array will retain its original value. Note that
  1213. if an uninitialized out array is created via the default ``out=None``,
  1214. locations within it where the condition is `False` will remain
  1215. uninitialized.
  1216. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1217. output Tensor.
  1218. Returns:
  1219. Tensor or scalar, the natural logarithm of `x`, element-wise. This is a
  1220. scalar if `x` is a scalar.
  1221. Raises:
  1222. TypeError: if the input is not a tensor.
  1223. Supported Platforms:
  1224. ``Ascend`` ``GPU`` ``CPU``
  1225. Examples:
  1226. >>> x = np.array([2, 3, 4]).astype('float32')
  1227. >>> output = np.log(x)
  1228. >>> print(output)
  1229. [0.69314575 1.09861 1.3862929 ]
  1230. """
  1231. return _apply_tensor_op(F.log, x, out=out, where=where, dtype=dtype)
  1232. def maximum(x1, x2, out=None, where=True, dtype=None):
  1233. """
  1234. Returns the element-wise maximum of array elements.
  1235. Compares two arrays and returns a new array containing the element-wise maxima.
  1236. Note:
  1237. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  1238. not supported.
  1239. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1240. for storing the result, however it can be used in combination with `where` to set
  1241. the value at indices for which `where` is set to False.
  1242. Unlike numpy, when one of the elements is a NaN, the second element is
  1243. always returned regardless of whether the second element is a NaN, instead
  1244. of returning NaN.
  1245. Args:
  1246. x1 (Tensor): Input array
  1247. x2 (Tensor): The array holding the elements to be compared. If
  1248. ``x1.shape != x2.shape``, they must be broadcastable to a common shape
  1249. (which becomes the shape of the output).
  1250. out (Tensor or None, optional): defaults to None.
  1251. where (Tensor or None, optional): For any non-default value of type other
  1252. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1253. This condition is broadcasted over the input. At locations where the
  1254. condition is `True`, the out array will be set to the ufunc result.
  1255. Elsewhere, the out array will retain its original value. Note that
  1256. if an uninitialized out array is created via the default ``out=None``,
  1257. locations within it where the condition is `False` will remain
  1258. uninitialized.
  1259. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1260. output Tensor.
  1261. Returns:
  1262. Tensor or scalar, the maximum of `x1` and `x2`, element-wise. This is a scalar
  1263. if both `x1` and `x2` are scalars.
  1264. Raises:
  1265. TypeError: if the input is not a tensor.
  1266. Supported Platforms:
  1267. ``Ascend`` ``GPU`` ``CPU``
  1268. Examples:
  1269. >>> output = np.maximum(np.array([2, 3, 4]), np.array([1, 5, 2]))
  1270. >>> print(output)
  1271. [2 5 4]
  1272. """
  1273. if isinstance(x1, (int, float, bool, list, tuple)):
  1274. x1 = asarray_const(x1)
  1275. elif not isinstance(x1, Tensor):
  1276. _raise_type_error("Input x1 is expected to be array_like")
  1277. if isinstance(x2, (int, float, bool, list, tuple)):
  1278. x2 = asarray_const(x2)
  1279. elif not isinstance(x2, Tensor):
  1280. _raise_type_error("Input x2 is expected to be array_like")
  1281. # F.maximum does not support when both operands are scalar
  1282. if x1.ndim == 0 and x2.ndim == 0:
  1283. x1 = expand_dims(x1, 0)
  1284. return _apply_tensor_op(F.maximum, x1, x2, out=out, where=where, dtype=dtype).squeeze()
  1285. if x1.ndim == 0:
  1286. dtype = x2.dtype
  1287. elif x2.ndim == 0:
  1288. dtype = x1.dtype
  1289. return _apply_tensor_op(F.maximum, x1, x2, out=out, where=where, dtype=dtype)
  1290. def heaviside(x1, x2, out=None, where=True, dtype=None):
  1291. """
  1292. Computes the Heaviside step function.
  1293. Note:
  1294. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  1295. not supported.
  1296. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1297. for storing the result, however it can be used in combination with `where` to set
  1298. the value at indices for which `where` is set to False.
  1299. Args:
  1300. x1 (Tensor): Input values.
  1301. x2 (Tensor): The value of the function when `x1` is 0. If
  1302. ``x1.shape != x2.shape``, they must be broadcastable to a common shape
  1303. (which becomes the shape of the output).
  1304. out (Tensor or None, optional): defaults to None.
  1305. where (Tensor or None, optional): For any non-default value of type other
  1306. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1307. This condition is broadcasted over the input. At locations where the
  1308. condition is `True`, the out array will be set to the ufunc result.
  1309. Elsewhere, the out array will retain its original value. Note that
  1310. if an uninitialized out array is created via the default ``out=None``,
  1311. locations within it where the condition is `False` will remain
  1312. uninitialized.
  1313. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1314. output Tensor.
  1315. Returns:
  1316. Tensor or scalar, the output array, element-wise Heaviside step function
  1317. of `x1`. This is a scalar if both `x1` and `x2` are scalars.
  1318. Raises:
  1319. TypeError: if the input is not a tensor.
  1320. Supported Platforms:
  1321. ``Ascend`` ``GPU`` ``CPU``
  1322. Examples:
  1323. >>> output = np.heaviside(np.array([-1.5, 0, 2.0]), np.array(0.5))
  1324. >>> print(output)
  1325. [0. 0.5 1. ]
  1326. >>> output = np.heaviside(np.array([-1.5, 0, 2.0]), np.array(1))
  1327. >>> print(output)
  1328. [0. 1. 1.]
  1329. """
  1330. def _heaviside(x1, x2):
  1331. """Computes heaviside without passing keyword arguments"""
  1332. # performs type promotion
  1333. dtype1 = F.dtype(x1)
  1334. dtype2 = F.dtype(x2)
  1335. dtype_out = _promote(dtype1, dtype2)
  1336. if not _check_same_type(dtype1, dtype_out):
  1337. x1 = F.cast(x1, dtype_out)
  1338. if not _check_same_type(dtype2, dtype_out):
  1339. x2 = F.cast(x2, dtype_out)
  1340. # performs broadcast
  1341. shape_out = _infer_out_shape(F.shape(x1), F.shape(x2))
  1342. x1 = _broadcast_to_shape(x1, shape_out)
  1343. x2 = _broadcast_to_shape(x2, shape_out)
  1344. x2 = F.select(x1 < 0, zeros(shape_out, dtype_out), x2)
  1345. x2 = F.select(x1 > 0, ones(shape_out, dtype_out), x2)
  1346. return x2
  1347. return _apply_tensor_op(_heaviside, x1, x2, out=out, where=where, dtype=dtype)
  1348. def amax(a, axis=None, keepdims=False, initial=None, where=True):
  1349. """
  1350. Returns the maximum of an array or maximum along an axis.
  1351. Note:
  1352. Numpy argument `out` is not supported.
  1353. On GPU, the supported dtypes are np.float16, and np.float32.
  1354. Args:
  1355. a (Tensor): Input data.
  1356. axis (None or int or tuple of ints, optional): defaults to None. Axis or
  1357. axes along which to operate. By default, flattened input is used. If
  1358. this is a tuple of ints, the maximum is selected over multiple axes,
  1359. instead of a single axis or all the axes as before.
  1360. keepdims (boolean, optional): defaults to False.
  1361. If this is set to True, the axes which are reduced are left in the
  1362. result as dimensions with size one. With this option, the result will
  1363. broadcast correctly against the input array.
  1364. initial (scalar, optional):
  1365. The minimum value of an output element. Must be present to allow
  1366. computation on empty slice.
  1367. where (boolean Tensor, optional): defaults to True.
  1368. A boolean array which is broadcasted to match the dimensions of array,
  1369. and selects elements to include in the reduction. If non-default value
  1370. is passed, initial must also be provided.
  1371. Returns:
  1372. Tensor or scalar, maximum of `a`. If `axis` is None, the result is a scalar
  1373. value. If `axis` is given, the result is an array of dimension ``a.ndim - 1``.
  1374. Raises:
  1375. TypeError: if the input is not a tensor.
  1376. Supported Platforms:
  1377. ``Ascend`` ``GPU`` ``CPU``
  1378. Examples:
  1379. >>> a = np.arange(4).reshape((2,2)).astype('float32')
  1380. >>> output = np.amax(a)
  1381. >>> print(output)
  1382. 3.0
  1383. >>> output = np.amax(a, axis=0)
  1384. >>> print(output)
  1385. [2. 3.]
  1386. >>> output = np.amax(a, axis=1)
  1387. >>> print(output)
  1388. [1. 3.]
  1389. >>> output = np.amax(a, where=np.array([False, True]), initial=-1, axis=0)
  1390. >>> print(output)
  1391. [-1. 3.]
  1392. """
  1393. return _reduce(a, P.ReduceMax(keepdims), F.maximum, axis=axis, keepdims=keepdims,
  1394. initial=initial, where=where)
  1395. def amin(a, axis=None, keepdims=False, initial=None, where=True):
  1396. """
  1397. Returns the minimum of an array or minimum along an axis.
  1398. Note:
  1399. Numpy argument `out` is not supported.
  1400. On GPU, the supported dtypes are np.float16, and np.float32.
  1401. Args:
  1402. a (Tensor): Input data.
  1403. axis (None or int or tuple of ints, optional): defaults to None. Axis or
  1404. axes along which to operate. By default, flattened input is used. If
  1405. this is a tuple of ints, the minimum is selected over multiple axes,
  1406. instead of a single axis or all the axes as before.
  1407. keepdims (boolean, optional): defaults to False.
  1408. If this is set to True, the axes which are reduced are left in the
  1409. result as dimensions with size one. With this option, the result will
  1410. broadcast correctly against the input array.
  1411. initial (scalar, optional):
  1412. The maximum value of an output element. Must be present to allow
  1413. computation on empty slice.
  1414. where (boolean Tensor, optional): defaults to True.
  1415. A boolean array which is broadcasted to match the dimensions of array,
  1416. and selects elements to include in the reduction. If non-default value
  1417. is passed, initial must also be provided.
  1418. Returns:
  1419. Tensor or scalar, minimum of `a`. If axis is None, the result is a scalar
  1420. value. If `axis` is given, the result is an array of dimension ``a.ndim - 1``.
  1421. Raises:
  1422. TypeError: if the input is not a tensor.
  1423. Supported Platforms:
  1424. ``Ascend`` ``GPU`` ``CPU``
  1425. Examples:
  1426. >>> a = np.arange(4).reshape((2,2)).astype('float32')
  1427. >>> output = np.amin(a)
  1428. >>> print(output)
  1429. 0.0
  1430. >>> output = np.amin(a, axis=0)
  1431. >>> print(output)
  1432. [0. 1.]
  1433. >>> output = np.amin(a, axis=1)
  1434. >>> print(output)
  1435. [0, 2]
  1436. >>> output = np.amin(a, where=np.array([False, True]), initial=10, axis=0)
  1437. >>> print(output)
  1438. [10. 1.]
  1439. """
  1440. return _reduce(a, P.ReduceMin(keepdims), F.minimum, axis=axis, keepdims=keepdims,
  1441. initial=initial, where=where)
  1442. def hypot(x1, x2, out=None, where=True, dtype=None):
  1443. """
  1444. Given the “legs” of a right triangle, returns its hypotenuse.
  1445. Equivalent to ``sqrt(x1**2 + x2**2)``, element-wise. If `x1` or `x2` is scalar_like
  1446. (i.e., unambiguously cast-able to a scalar type), it is broadcast for use
  1447. with each element of the other argument. (See Examples)
  1448. Note:
  1449. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  1450. not supported.
  1451. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1452. for storing the result, however it can be used in combination with `where` to set
  1453. the value at indices for which `where` is set to False.
  1454. On GPU, the supported dtypes are np.float16 and np.float32.
  1455. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.
  1456. Args:
  1457. x1 (Tensor): Leg of the traingle(s).
  1458. x2 (Tensor): Leg of the triangle(s). If ``x1.shape != x2.shape``, they
  1459. must be broadcastable to a common shape (which becomes the shape of
  1460. the output).
  1461. out (Tensor or None, optional): defaults to None.
  1462. where (Tensor or None, optional): For any non-default value of type other
  1463. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1464. This condition is broadcasted over the input. At locations where the
  1465. condition is `True`, the out array will be set to the ufunc result.
  1466. Elsewhere, the out array will retain its original value. Note that
  1467. if an uninitialized out array is created via the default ``out=None``,
  1468. locations within it where the condition is `False` will remain
  1469. uninitialized.
  1470. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1471. output Tensor.
  1472. Returns:
  1473. Tensor or scalar, the hypotenuse of the triangle(s). This is a scalar if
  1474. both `x1` and `x2` are scalars.
  1475. Raises:
  1476. TypeError: if the input is not a tensor.
  1477. Supported Platforms:
  1478. ``Ascend`` ``GPU`` ``CPU``
  1479. Examples:
  1480. >>> output = np.hypot(3*np.ones((3, 3)), 4*np.ones((3, 3)))
  1481. >>> print(output)
  1482. [[5. 5. 5.]
  1483. [5. 5. 5.]
  1484. [5. 5. 5.]]
  1485. >>> output = np.hypot(3*np.ones((3, 3)), np.array([4]))
  1486. >>> print(output)
  1487. [[5. 5. 5.]
  1488. [5. 5. 5.]
  1489. [5. 5. 5.]]
  1490. """
  1491. def _hypot(x1, x2):
  1492. """Computes hypotenuse without passing keyword arguments"""
  1493. if _get_device() == 'CPU':
  1494. # broadcast is not fully supported in tensor_add on CPU,
  1495. # so we use tensor_sub as a substitute solution
  1496. return F.sqrt(F.tensor_sub(F.square(x1), F.neg_tensor(F.square(x2))))
  1497. return F.sqrt(F.tensor_add(F.square(x1), F.square(x2)))
  1498. return _apply_tensor_op(_hypot, x1, x2, out=out, where=where, dtype=dtype)
  1499. def floor(x, out=None, where=True, dtype=None):
  1500. """
  1501. Returns the floor of the input, element-wise.
  1502. The floor of the scalar `x` is the largest integer `i`, such that ``i <= x``.
  1503. Note:
  1504. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  1505. not supported.
  1506. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1507. for storing the result, however it can be used in combination with `where` to set
  1508. the value at indices for which `where` is set to False.
  1509. On GPU, the supported dtypes are np.float16 and np.float32.
  1510. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.
  1511. Args:
  1512. x (Tensor): input data.
  1513. out (Tensor or None, optional): defaults to None.
  1514. where (Tensor or None, optional): For any non-default value of type other
  1515. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1516. This condition is broadcasted over the input. At locations where the
  1517. condition is `True`, the out array will be set to the ufunc result.
  1518. Elsewhere, the out array will retain its original value. Note that
  1519. if an uninitialized out array is created via the default ``out=None``,
  1520. locations within it where the condition is `False` will remain
  1521. uninitialized.
  1522. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1523. output Tensor.
  1524. Returns:
  1525. Tensor or scalar, the floor of each element in `x`. This is a scalar if `x`
  1526. is a scalar.
  1527. Raises:
  1528. TypeError: if the input is not a tensor.
  1529. Supported Platforms:
  1530. ``Ascend`` ``GPU`` ``CPU``
  1531. Examples:
  1532. >>> output = np.floor(np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]))
  1533. >>> print(output)
  1534. [-2. -2. -1. 0. 1. 1. 2.]
  1535. """
  1536. return _apply_tensor_op(F.floor, x, out=out, where=where, dtype=dtype)
  1537. def floor_divide(x1, x2, out=None, where=True, dtype=None):
  1538. """
  1539. Returns the largest integer smaller or equal to the division of the inputs.
  1540. It is equivalent to the Python // operator and pairs with the
  1541. Python % (remainder), function so that ``a = a % b + b * (a // b)`` up to roundoff.
  1542. Note:
  1543. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  1544. not supported.
  1545. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1546. for storing the result, however it can be used in combination with `where` to set
  1547. the value at indices for which `where` is set to False.
  1548. Args:
  1549. x1 (Tensor): Input array.
  1550. x2 (Tensor): Input array.
  1551. out (Tensor or None, optional): defaults to None.
  1552. where (Tensor or None, optional): For any non-default value of type other
  1553. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1554. This condition is broadcasted over the input. At locations where the
  1555. condition is `True`, the out array will be set to the ufunc result.
  1556. Elsewhere, the out array will retain its original value. Note that
  1557. if an uninitialized out array is created via the default ``out=None``,
  1558. locations within it where the condition is `False` will remain
  1559. uninitialized.
  1560. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1561. output Tensor.
  1562. Returns:
  1563. Tensor or scalar.
  1564. Raises:
  1565. TypeError: if the input is not a tensor.
  1566. Supported Platforms:
  1567. ``Ascend`` ``GPU`` ``CPU``
  1568. Examples:
  1569. >>> output = np.floor_divide(np.array([1., 2., 3., 4.]), np.array(2.5))
  1570. >>> print(output)
  1571. [0. 0. 1. 1.]
  1572. """
  1573. return _apply_tensor_op(F.tensor_floordiv, x1, x2, out=out, where=where, dtype=dtype)
  1574. def _remainder(x1, x2, C_style=False):
  1575. """Computes remainder without applying keyword arguments."""
  1576. dtype = _promote(F.dtype(x1), F.dtype(x2))
  1577. if not _check_is_float(dtype):
  1578. x1 = F.cast(x1, mstype.float32)
  1579. x2 = F.cast(x2, mstype.float32)
  1580. quotient = F.tensor_div(x1, x2)
  1581. if C_style:
  1582. quotient = fix(quotient)
  1583. else:
  1584. quotient = F.floor(quotient)
  1585. prod = F.tensor_mul(x2, quotient)
  1586. res = F.tensor_sub(x1, prod)
  1587. if _check_is_int(dtype):
  1588. zeros_tensor = zeros(F.shape(quotient), F.dtype(quotient))
  1589. x2_zeros = F.equal(x2, zeros_tensor)
  1590. res = F.select(x2_zeros, zeros_tensor, res)
  1591. if not _check_same_type(F.dtype(res), dtype):
  1592. res = F.cast(res, dtype)
  1593. return res
  1594. def remainder(x1, x2, out=None, where=True, dtype=None):
  1595. """
  1596. Returns element-wise remainder of division.
  1597. Computes the remainder complementary to the floor_divide function. It is
  1598. equivalent to the Python modulus operator ``x1 % x2`` and has the same sign
  1599. as the divisor `x2`. The MATLAB function equivalent to np.remainder is mod.
  1600. Note:
  1601. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  1602. not supported.
  1603. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1604. for storing the result, however it can be used in combination with `where` to set
  1605. the value at indices for which `where` is set to False.
  1606. Args:
  1607. x1 (Tensor): input array.
  1608. x2 (Tensor): input array.
  1609. out (Tensor or None, optional): defaults to None.
  1610. where (Tensor or None, optional): For any non-default value of type other
  1611. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1612. This condition is broadcasted over the input. At locations where the
  1613. condition is `True`, the out array will be set to the ufunc result.
  1614. Elsewhere, the out array will retain its original value. Note that
  1615. if an uninitialized out array is created via the default ``out=None``,
  1616. locations within it where the condition is `False` will remain
  1617. uninitialized.
  1618. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1619. output Tensor.
  1620. Returns:
  1621. Tensor or scalar, the element-wise remainder of the quotient
  1622. ``floor_divide(x1, x2)``. This is a scalar if both `x1` and `x2` are scalars.
  1623. Raises:
  1624. TypeError: if the input is not a tensor.
  1625. Supported Platforms:
  1626. ``Ascend`` ``GPU`` ``CPU``
  1627. Examples:
  1628. >>> output = np.remainder(np.array([4, 7]), np.array([2, 3]))
  1629. >>> print(output)
  1630. [0 1]
  1631. >>> output = np.remainder(np.arange(7), np.array(5))
  1632. >>> print(output)
  1633. [0 1 2 3 4 0 1]
  1634. """
  1635. return _apply_tensor_op(_remainder, x1, x2, out=out, where=where, dtype=dtype)
  1636. def fix(x):
  1637. """
  1638. Rounds to nearest integer towards zero.
  1639. Rounds an array of floats element-wise to nearest integer towards zero. The
  1640. rounded values are returned as floats.
  1641. Note:
  1642. Numpy argument `out` is not supported.
  1643. Args:
  1644. x (Tensor): An array of floats to be rounded.
  1645. Returns:
  1646. Tensor.
  1647. Raises:
  1648. TypeError: if the input is not a tensor.
  1649. Supported Platforms:
  1650. ``Ascend`` ``GPU`` ``CPU``
  1651. Examples:
  1652. >>> output = np.fix(np.array([2.1, 2.9, -2.1, -2.9]))
  1653. >>> print(output)
  1654. [ 2. 2. -2. -2.]
  1655. """
  1656. _check_input_tensor(x)
  1657. if not _check_is_float(F.dtype(x)):
  1658. x = F.cast(x, mstype.float32)
  1659. floored = F.floor(x)
  1660. # TODO change to F.ceil once supported on CPU.
  1661. ceiled = F.neg_tensor(F.floor(F.neg_tensor(x)))
  1662. is_neg = F.tensor_lt(x, zeros(F.shape(x), F.dtype(x)))
  1663. return F.select(is_neg, ceiled, floored)
  1664. def fmod(x1, x2, out=None, where=True, dtype=None):
  1665. """
  1666. Returns the element-wise remainder of division.
  1667. This is the NumPy implementation of the C library function fmod, the remainder
  1668. has the same sign as the dividend `x1`. It is equivalent to the Matlab(TM) rem
  1669. function and should not be confused with the Python modulus operator ``x1 % x2``.
  1670. Note:
  1671. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  1672. not supported.
  1673. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1674. for storing the result, however it can be used in combination with `where` to set
  1675. the value at indices for which `where` is set to False.
  1676. Args:
  1677. x1 (Tensor)
  1678. x2 (Tensor): input arrays.
  1679. out (Tensor or None, optional): defaults to None.
  1680. where (Tensor or None, optional): For any non-default value of type other
  1681. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1682. This condition is broadcasted over the input. At locations where the
  1683. condition is `True`, the out array will be set to the ufunc result.
  1684. Elsewhere, the out array will retain its original value. Note that
  1685. if an uninitialized out array is created via the default ``out=None``,
  1686. locations within it where the condition is `False` will remain
  1687. uninitialized.
  1688. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1689. output Tensor.
  1690. Returns:
  1691. Tensor or scalar, the remainder of the division of `x1` by `x2`. This is a
  1692. scalar if both `x1` and `x2` are scalars.
  1693. Raises:
  1694. TypeError: if the input is not a tensor.
  1695. Supported Platforms:
  1696. ``Ascend`` ``GPU`` ``CPU``
  1697. Examples:
  1698. >>> output = np.fmod(np.array([-3, -2, -1, 1, 2, 3]), np.array(2))
  1699. >>> print(output)
  1700. [-1 0 -1 1 0 1]
  1701. """
  1702. return _apply_tensor_op(lambda x1, x2: _remainder(x1, x2, C_style=True), x1, x2,
  1703. out=out, where=where, dtype=dtype)
  1704. def trunc(x, out=None, where=True, dtype=None):
  1705. """
  1706. Returns the truncated value of the input, element-wise.
  1707. The truncated value of the scalar `x` is the nearest integer `i` which is closer to zero
  1708. than `x` is. In short, the fractional part of the signed number `x` is discarded.
  1709. Note:
  1710. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  1711. not supported.
  1712. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1713. for storing the result, however it can be used in combination with `where` to set
  1714. the value at indices for which `where` is set to False.
  1715. Args:
  1716. x (Tensor): input data.
  1717. out (Tensor or None, optional): defaults to None.
  1718. where (Tensor or None, optional): For any non-default value of type other
  1719. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1720. This condition is broadcasted over the input. At locations where the
  1721. condition is `True`, the out array will be set to the ufunc result.
  1722. Elsewhere, the out array will retain its original value. Note that
  1723. if an uninitialized out array is created via the default ``out=None``,
  1724. locations within it where the condition is `False` will remain
  1725. uninitialized.
  1726. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1727. output Tensor.
  1728. Returns:
  1729. Tensor or scalar, the truncated value of each element in `x`. This is a scalar if `x` is
  1730. a scalar.
  1731. Raises:
  1732. TypeError: if the input is not a tensor.
  1733. Supported Platforms:
  1734. ``Ascend`` ``GPU`` ``CPU``
  1735. Examples:
  1736. >>> output = np.trunc(np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]))
  1737. >>> print(output)
  1738. [-1. -1. -0. 0. 1. 1. 2.]
  1739. """
  1740. return _apply_tensor_op(fix, x, out=out, where=where, dtype=dtype)
  1741. def exp(x, out=None, where=True, dtype=None):
  1742. """
  1743. Calculates the exponential of all elements in the input array.
  1744. Note:
  1745. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  1746. not supported.
  1747. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1748. for storing the result, however it can be used in combination with `where` to set
  1749. the value at indices for which `where` is set to False.
  1750. On GPU, the supported dtypes are np.float16, and np.float32.
  1751. On CPU, the supported dtypes are np.float16, np.float32, np.float64.
  1752. Args:
  1753. x (Tensor): input data.
  1754. out (Tensor or None, optional): defaults to None.
  1755. where (Tensor or None, optional): For any non-default value of type other
  1756. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1757. This condition is broadcasted over the input. At locations where the
  1758. condition is `True`, the out array will be set to the ufunc result.
  1759. Elsewhere, the out array will retain its original value. Note that
  1760. if an uninitialized out array is created via the default ``out=None``,
  1761. locations within it where the condition is `False` will remain
  1762. uninitialized.
  1763. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1764. output Tensor.
  1765. Returns:
  1766. Tensor or scalar, element-wise exponential of `x`. This is a scalar if both
  1767. `x1` and `x2` are scalars.
  1768. Raises:
  1769. TypeError: if the input is not a tensor.
  1770. Supported Platforms:
  1771. ``Ascend`` ``GPU`` ``CPU``
  1772. Examples:
  1773. >>> output = np.exp(np.arange(5).astype(np.float32))
  1774. >>> print(output)
  1775. [ 1. 2.718282 7.3890557 20.085537 54.598145 ]
  1776. """
  1777. return _apply_tensor_op(F.tensor_exp, x, out=out, where=where, dtype=dtype)
  1778. def expm1(x, out=None, where=True, dtype=None):
  1779. """
  1780. Calculates ``exp(x) - 1`` for all elements in the array.
  1781. Note:
  1782. Numpy arguments `casting`, `order`, `dtype`, `subok`, `signature`, and `extobj` are
  1783. not supported.
  1784. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1785. for storing the result, however it can be used in combination with `where` to set
  1786. the value at indices for which `where` is set to False.
  1787. On GPU, the supported dtypes are np.float16, and np.float32.
  1788. On CPU, the supported dtypes are np.float16, and np.float32.
  1789. Args:
  1790. x (Tensor): input data.
  1791. out (Tensor or None, optional): defaults to None.
  1792. where (Tensor or None, optional): For any non-default value of type other
  1793. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1794. This condition is broadcasted over the input. At locations where the
  1795. condition is `True`, the out array will be set to the ufunc result.
  1796. Elsewhere, the out array will retain its original value. Note that
  1797. if an uninitialized out array is created via the default ``out=None``,
  1798. locations within it where the condition is `False` will remain
  1799. uninitialized.
  1800. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1801. output Tensor.
  1802. Returns:
  1803. Tensor or scalar, element-wise exponential minus one, ``out = exp(x) - 1``.
  1804. This is a scalar if both `x1` and `x2` are scalars.
  1805. Raises:
  1806. TypeError: if the input is not a tensor.
  1807. Supported Platforms:
  1808. ``Ascend`` ``GPU`` ``CPU``
  1809. Examples:
  1810. >>> output = np.expm1(np.arange(5).astype(np.float32))
  1811. >>> print(output)
  1812. [ 0. 1.7182819 6.389056 19.085537 53.59815 ]
  1813. """
  1814. return _apply_tensor_op(F.tensor_expm1, x, out=out, where=where, dtype=dtype)
  1815. @constexpr
  1816. def _real_axes(ndim_orig, ndim_out, axes_orig):
  1817. """Returns the real axes to be reduced after performing broadcast"""
  1818. diff = ndim_out - ndim_orig
  1819. axes = F.make_range(diff)
  1820. axes_orig = map(functools.partial(operator.add, diff), axes_orig)
  1821. return axes + tuple(axes_orig)
  1822. @constexpr
  1823. def _shape_reduced_keepdims(shape, axes):
  1824. """
  1825. Reduces dimensions corresponding to argument axes while
  1826. keeping the number of dimensions unchanged.
  1827. """
  1828. ndim_out = F.tuple_len(shape)
  1829. shape_out = [1]*ndim_out
  1830. for i in range(ndim_out):
  1831. if not i in axes:
  1832. shape_out[i] = shape[i]
  1833. return tuple(shape_out)
  1834. @constexpr
  1835. def _shape_reduced(shape, axes):
  1836. """Removes dimensions corresponding to argument axes"""
  1837. ndim_orig = F.tuple_len(shape)
  1838. ndim_out = ndim_orig - F.tuple_len(axes)
  1839. shape_out = [0]*ndim_out
  1840. idx_out = 0
  1841. for i in range(ndim_orig):
  1842. if not i in axes:
  1843. shape_out[idx_out] = shape[i]
  1844. idx_out += 1
  1845. return tuple(shape_out)
  1846. def _reduce(a, reduce_fn, cmp_fn, axis=None, keepdims=False, initial=None, where=True):
  1847. """Applies comparison based on cmp_fn and reduction based on reduce_fn"""
  1848. _check_input_tensor(a)
  1849. shape = F.shape(a)
  1850. ndim = F.rank(a)
  1851. dtype = F.dtype(a)
  1852. axes = _check_axis_valid(axis, ndim)
  1853. if initial is not None:
  1854. if ((isinstance(initial, Tensor) and F.rank(initial) > 0) or
  1855. not isinstance(initial, (int, float, bool, Tensor))):
  1856. _raise_type_error('initial should be scalar')
  1857. if _is_shape_empty(shape):
  1858. if not axes:
  1859. return a
  1860. if keepdims:
  1861. shape_out = _shape_reduced_keepdims(shape, axes)
  1862. else:
  1863. shape_out = _shape_reduced(shape, axes)
  1864. if _is_shape_empty(shape_out):
  1865. return empty(F.dtype(a), shape_out)
  1866. if initial is None:
  1867. return _raise_value_error('initial value must be provided for zero-size arrays')
  1868. return full(shape_out, initial, dtype)
  1869. if initial is not None:
  1870. initial = full(shape, initial, dtype)
  1871. a = cmp_fn(a, initial)
  1872. if not axes:
  1873. return a
  1874. if isinstance(where, Tensor):
  1875. if initial is None:
  1876. return _raise_value_error('initial value must be provided for where masks')
  1877. ndim_orig = F.rank(a)
  1878. a = where_(where, a, initial)
  1879. axes = _real_axes(ndim_orig, F.rank(a), axes)
  1880. return reduce_fn(a, axes)
  1881. def positive(a, out=None, where=True, dtype=None):
  1882. """
  1883. Numerical positive, element-wise.
  1884. Note:
  1885. Numpy arguments casting, order, subok, signature, and extobj are
  1886. not supported.
  1887. Args:
  1888. a (Tensor): Input tensor.
  1889. out (Tensor or None, optional): defaults to None.
  1890. where (Tensor or None, optional): For any non-default value of type other
  1891. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1892. This condition is broadcasted over the input. At locations where the
  1893. condition is `True`, the out array will be set to the ufunc result.
  1894. Elsewhere, the out array will retain its original value. Note that
  1895. if an uninitialized out array is created via the default ``out=None``,
  1896. locations within it where the condition is `False` will remain
  1897. uninitialized.
  1898. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1899. output Tensor.
  1900. Returns:
  1901. Tensor.
  1902. Supported Platforms:
  1903. ``Ascend`` ``GPU`` ``CPU``
  1904. Examples:
  1905. >>> import mindspore.numpy as np
  1906. >>> a = np.asarray([1, -1]).astype('float32')
  1907. >>> output = np.positive(a)
  1908. >>> print(output)
  1909. [1. -1.]
  1910. """
  1911. _check_input_tensor(a)
  1912. neg_tensor = F.neg_tensor(a)
  1913. return _apply_tensor_op(F.neg_tensor, neg_tensor, out=out, where=where, dtype=dtype)
  1914. def negative(a, out=None, where=True, dtype=None):
  1915. """
  1916. Numerical negative, element-wise.
  1917. Note:
  1918. Numpy arguments `casting`, `order`, `subok`, `signature`, and `extobj` are
  1919. not supported.
  1920. Args:
  1921. a (Tensor): Input tensor.
  1922. out (Tensor or None, optional): defaults to None.
  1923. where (Tensor or None, optional): For any non-default value of type other
  1924. than :class:`Tensor` or :class:`None`, the output retains its original value.
  1925. This condition is broadcasted over the input. At locations where the
  1926. condition is `True`, the out array will be set to the ufunc result.
  1927. Elsewhere, the out array will retain its original value. Note that
  1928. if an uninitialized out array is created via the default ``out=None``,
  1929. locations within it where the condition is `False` will remain
  1930. uninitialized.
  1931. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1932. output Tensor.
  1933. Returns:
  1934. Tensor.
  1935. Supported Platforms:
  1936. ``Ascend`` ``GPU`` ``CPU``
  1937. Examples:
  1938. >>> import mindspore.numpy as np
  1939. >>> a = np.asarray([1, -1]).astype('float32')
  1940. >>> output = np.negative(a)
  1941. >>> print(output)
  1942. [-1. 1.]
  1943. """
  1944. _check_input_tensor(a)
  1945. return _apply_tensor_op(F.neg_tensor, a, out=out, where=where, dtype=dtype)
  1946. def cumsum(a, axis=None, dtype=None):
  1947. """
  1948. Returns the cumulative sum of the elements along a given axis.
  1949. Args:
  1950. a (Tensor): Input tensor.
  1951. axis (int, optional): Axis along which the cumulative sum is computed. The
  1952. default (None) is to compute the cumsum over the flattened array.
  1953. dtype (:class:`mindspore.dtype`, optional): If not specified, stay the same as `a`,
  1954. unless `a` has an integer dtype with a precision less than that of the
  1955. default platform integer. In that case, the default platform integer
  1956. is used.
  1957. Returns:
  1958. Tensor.
  1959. Raises:
  1960. TypeError: If input arguments have types not specified above.
  1961. ValueError: If axis is out of range.
  1962. Supported Platforms:
  1963. ``Ascend`` ``GPU`` ``CPU``
  1964. Examples:
  1965. >>> output = np.cumsum(np.ones((3,3)), axis=0)
  1966. >>> print(output)
  1967. [[1. 1. 1.]
  1968. [2. 2. 2.]
  1969. [3. 3. 3.]]
  1970. """
  1971. _check_input_tensor(a)
  1972. original_dtype = F.dtype(a)
  1973. # If original array is int, and has precision less then int32, convert to int32
  1974. if _check_same_type(original_dtype, mstype.bool_) or \
  1975. _check_same_type(original_dtype, mstype.int8) or \
  1976. _check_same_type(original_dtype, mstype.int16):
  1977. original_dtype = mstype.int32
  1978. a = a.astype(mstype.float32)
  1979. if axis is None:
  1980. a = a.ravel()
  1981. axis = 0
  1982. _check_axis_in_range(axis, a.ndim)
  1983. if dtype is not None and not _check_same_type(original_dtype, dtype):
  1984. return _cumsum_default(a, axis).astype(dtype, copy=False)
  1985. return _cumsum_default(a, axis).astype(original_dtype, copy=False)
  1986. def _apply_tensor_op(fn, *args, out=None, where=True, dtype=None):
  1987. """Applies tensor operations based on fn"""
  1988. _check_input_tensor(*args)
  1989. res = fn(*args)
  1990. # if out is set to a non-default value, return tensor will have the same
  1991. # dtype as out, which overrides the dtype passed into the keyword argument
  1992. if isinstance(out, Tensor):
  1993. dtype_out = F.dtype(out)
  1994. elif dtype is not None:
  1995. dtype_out = dtype
  1996. else:
  1997. dtype_out = F.dtype(res)
  1998. if isinstance(out, Tensor) and isinstance(where, Tensor):
  1999. out = where_(where, res, out)
  2000. elif out is None or where is not None:
  2001. out = res
  2002. if not _check_same_type(F.dtype(out), dtype_out):
  2003. out = F.cast(out, dtype_out)
  2004. return out