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

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