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.

array_ops.py 86 kB

5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515
  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. """array operations, the function docs are adapted from Numpy API."""
  16. import operator
  17. from ..common import dtype as mstype
  18. from ..common import Tensor
  19. from ..ops import operations as P
  20. from ..ops import functional as F
  21. from ..ops.primitive import constexpr
  22. from ..nn import Cell
  23. from .utils import _convert_list_tensor_to_tuple_tensor, _expand, _broadcast_to_shape, \
  24. _check_input_tensor, _broadcast_to, _to_tensor, _callable
  25. from .utils_const import _check_axes_range, _check_start_normalize, \
  26. _raise_type_error, _raise_value_error, _infer_out_shape, _empty, _promote, \
  27. _check_same_type, _check_axis_valid, _add_unit_axes, _broadcast_tuples, \
  28. _check_is_float, _check_axis_in_range, _check_axis_type, _canonicalize_axis, \
  29. _list_comprehensions, _check_element_int, _is_shape_empty, _type_convert, \
  30. _tuple_slice, _expanded_shape, _seq_prod, _tuple_setitem, _iota, \
  31. _raise_unimplemented_error, _cumprod, _get_device, _check_is_int
  32. # According to official numpy reference, the dimension of a numpy array must be less
  33. # than 32
  34. MAX_NUMPY_DIMS = 32
  35. def expand_dims(a, axis):
  36. """
  37. Expands the shape of a tensor.
  38. Inserts a new axis that will appear at the axis position in the expanded tensor shape.
  39. Args:
  40. a (Tensor): Input tensor array.
  41. axis (Union[int, list(int), tuple(int)]): Position in the expanded axes where
  42. the new axis is placed,
  43. Returns:
  44. Tensor, with the number of dimensions increased at specified axis.
  45. Raises:
  46. TypeError: If input arguments have types not specified above.
  47. ValueError: If axis exceeds a.ndim.
  48. Supported Platforms:
  49. ``Ascend`` ``GPU`` ``CPU``
  50. Examples:
  51. >>> import mindspore.numpy as np
  52. >>> x = np.ones((2,2))
  53. >>> x = np.expand_dims(x,0)
  54. >>> print(x.shape)
  55. (1, 2, 2)
  56. """
  57. _check_input_tensor(a)
  58. if not isinstance(axis, (int, tuple, list)):
  59. _raise_type_error("axis must be tuple, list or int, but got ", axis)
  60. if isinstance(axis, int):
  61. return F.expand_dims(a, axis)
  62. ndim = a.ndim + len(axis)
  63. axis = _canonicalize_axis(axis, ndim)
  64. for ax in axis:
  65. a = F.expand_dims(a, ax)
  66. return a
  67. def squeeze(a, axis=None):
  68. """
  69. Removes single-dimensional entries from the shape of an tensor.
  70. Args:
  71. a (Tensor): Input tensor array.
  72. axis (Union[None, int, list(int), tuple(list)]): Default is None.
  73. Returns:
  74. Tensor, with all or a subset of the dimensions of length :math:`1` removed.
  75. Raises:
  76. TypeError: If input arguments have types not specified above.
  77. ValueError: If specified axis has shape entry :math:`> 1`.
  78. Supported Platforms:
  79. ``Ascend`` ``GPU`` ``CPU``
  80. Examples:
  81. >>> import mindspore.numpy as np
  82. >>> x = np.ones((1,2,2,1))
  83. >>> x = np.squeeze(x)
  84. >>> print(x.shape)
  85. (2, 2)
  86. """
  87. _check_input_tensor(a)
  88. return a.squeeze(axis)
  89. def transpose(a, axes=None):
  90. """
  91. Reverses or permutes the axes of a tensor; returns the modified tensor.
  92. Args:
  93. a (Tensor): a tensor to be transposed
  94. axes (Union[None, tuple, list]): the axes order, if `axes` is `None`, transpose
  95. the entire tensor. Default is `None`.
  96. Returns:
  97. Tensor, the transposed tensor array.
  98. Raises:
  99. TypeError: If input arguments have types not specified above.
  100. ValueError: If the number of `axes` is not euqal to a.ndim.
  101. Supported Platforms:
  102. ``Ascend`` ``GPU`` ``CPU``
  103. Examples:
  104. >>> import mindspore.numpy as np
  105. >>> x = np.ones((1,2,3))
  106. >>> x = np.transpose(x)
  107. >>> print(x.shape)
  108. (3, 2, 1)
  109. """
  110. _check_input_tensor(a)
  111. return a.transpose(axes)
  112. def rollaxis(x, axis, start=0):
  113. """
  114. Rolls the specified axis backwards, until it lies in the given position.
  115. The positions of the other axes do not change relative to one another.
  116. Args:
  117. x (Tensor): A Tensor to be transposed.
  118. axis (int): The axis to be rolled.
  119. start (int): Default: 0.
  120. If :math:`start <= axis`, the axis is rolled back until it lies in this position (`start`).
  121. If :math:`start > axis`: the axis is rolled until it lies before this position (`start`).
  122. If :math:`start < 0`, the start will be normalized as shown in the table.
  123. (Please refer to the source code.)
  124. .. table
  125. +===========+=================+
  126. |start |Normalized start |
  127. +===========+=================+
  128. |-(x.ndim+1)| raise ValueError|
  129. +-----------+-----------------+
  130. |-x.ndim |0 |
  131. +-----------+-----------------+
  132. |... |... |
  133. +-----------+-----------------+
  134. |-1 |x.ndim-1 |
  135. +-----------+-----------------+
  136. |... |... |
  137. +-----------+-----------------+
  138. |x.ndim |x.ndim |
  139. +-----------+-----------------+
  140. |x.ndim+1 |raise ValueError |
  141. +===========+=================+
  142. ..
  143. Returns:
  144. Transposed Tensor. Has the same data type as the original tensor `x`.
  145. Supported Platforms:
  146. ``Ascend`` ``GPU`` ``CPU``
  147. Raises:
  148. TypeError: If `axis` or `start` is not integer, or `x` is not tensor.
  149. ValueError: If `axis` is not in the range of :math:`[-ndim, ndim-1]` or
  150. `start` is not in the range of :math:`[-ndim, ndim]`.
  151. Examples:
  152. >>> import mindspore.numpy as np
  153. >>> x = np.ones((2,3,4))
  154. >>> output = np.rollaxis(x, 0, 2)
  155. >>> print(output.shape)
  156. (3, 2, 4)
  157. """
  158. _check_input_tensor(x)
  159. if not isinstance(axis, int):
  160. _raise_type_error("integer argument expected, but got ", axis)
  161. if not isinstance(start, int):
  162. _raise_type_error("integer argument expected, but got ", start)
  163. shape = F.shape(x)
  164. ndim = F.tuple_len(shape)
  165. axis = _check_axes_range(axis, ndim)
  166. start = _check_start_normalize(start, ndim)
  167. if start - axis >= 0 and start - axis <= 1:
  168. return x
  169. perm = F.make_range(0, ndim)
  170. new_perm = None
  171. if start < axis:
  172. if axis + 1 < ndim:
  173. new_perm = perm[0:start] + perm[axis:axis+1] + \
  174. perm[start:axis] + perm[axis+1:]
  175. else:
  176. new_perm = perm[0:start] + perm[axis:axis+1] + perm[start:axis]
  177. if start > axis:
  178. if start < ndim:
  179. new_perm = perm[0:axis] + perm[axis+1:start] + \
  180. perm[axis:axis+1] + perm[start:]
  181. else:
  182. new_perm = perm[0:axis] + perm[axis+1:start] + \
  183. perm[axis:axis+1]
  184. return F.transpose(x, new_perm)
  185. def swapaxes(x, axis1, axis2):
  186. """
  187. Interchanges two axes of a tensor.
  188. Args:
  189. x (Tensor): A tensor to be transposed.
  190. axis1 (int): First axis.
  191. axis2 (int): Second axis.
  192. Returns:
  193. Transposed tensor, has the same data type as the original tensor `x`.
  194. Raises:
  195. TypeError: If `axis1` or `axis2` is not integer, or `x` is not tensor.
  196. ValueError: If `axis1` or `axis2` is not in the range of :math:`[-ndim, ndim-1]`.
  197. Supported Platforms:
  198. ``Ascend`` ``GPU`` ``CPU``
  199. Examples:
  200. >>> import mindspore.numpy as np
  201. >>> x = np.ones((2,3,4))
  202. >>> output = np.swapaxes(x, 0, 2)
  203. >>> print(output.shape)
  204. (4,3,2)
  205. """
  206. _check_input_tensor(x)
  207. return x.swapaxes(axis1, axis2)
  208. def reshape(x, new_shape):
  209. """
  210. Reshapes a tensor without changing its data.
  211. Args:
  212. x (Tensor): A tensor to be reshaped.
  213. new_shape (Union[int, list(int), tuple(int)]): The new shape should be
  214. compatible with the original shape. If the tuple has only one element,
  215. the result will be a 1-D tensor of that length. One shape dimension
  216. can be :math:`-1`. In this case, the value is inferred from the length of
  217. the tensor and remaining dimensions.
  218. Returns:
  219. Reshaped Tensor. Has the same data type as the original tensor `x`.
  220. Raises:
  221. TypeError: If new_shape is not integer, list or tuple, or `x` is not tensor.
  222. ValueError: If new_shape is not compatible with the original shape.
  223. Supported Platforms:
  224. ``Ascend`` ``GPU`` ``CPU``
  225. Examples:
  226. >>> import mindspore.numpy as np
  227. >>> x = np.asarray([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]])
  228. >>> output = np.reshape(x, (3, 2))
  229. >>> print(output)
  230. [[-0.1 0.3]
  231. [ 3.6 0.4]
  232. [ 0.5 -3.2]]
  233. >>> output = np.reshape(x, (3, -1))
  234. >>> print(output)
  235. [[-0.1 0.3]
  236. [ 3.6 0.4]
  237. [ 0.5 -3.2]]
  238. >>> output = np.reshape(x, (6, ))
  239. >>> print(output)
  240. [-0.1 0.3 3.6 0.4 0.5 -3.2]
  241. """
  242. _check_input_tensor(x)
  243. return x.reshape(new_shape)
  244. def ravel(x):
  245. """
  246. Returns a contiguous flattened tensor.
  247. A 1-D tensor, containing the elements of the input, is returned.
  248. Args:
  249. x (Tensor): A tensor to be flattened.
  250. Returns:
  251. Flattened tensor, has the same data type as the original tensor `x`.
  252. Raises:
  253. TypeError: If `x` is not tensor.
  254. Supported Platforms:
  255. ``Ascend`` ``GPU`` ``CPU``
  256. Examples:
  257. >>> import mindspore.numpy as np
  258. >>> x = np.ones((2,3,4))
  259. >>> output = np.ravel(x)
  260. >>> print(output.shape)
  261. (24,)
  262. """
  263. _check_input_tensor(x)
  264. return x.ravel()
  265. @constexpr
  266. def _move_axes_for_concatenate(arr_shape, axis):
  267. """
  268. Moves axis 0 to the desiganated position, while keeps other axes' relative
  269. positions unchanged, only used if a single tensor is concatenated.
  270. """
  271. original_axes = tuple(range(len(arr_shape)))
  272. new_axes = original_axes[1:axis+1] + (0,) + original_axes[axis+1:]
  273. new_shape = arr_shape[1:axis+1] + (arr_shape[0] * arr_shape[axis+1],) + \
  274. arr_shape[axis+2:]
  275. return new_axes, new_shape
  276. def _promote_type_for_concatenate(tuple_of_tensors):
  277. """
  278. Checks dtype for all tensors in the tuple. If dtypes are not the same, promote
  279. them to the `highest` dtype in the tuple, so that they are ready for the concat
  280. operator.
  281. Args:
  282. tuple_of_tensors(tuple(tensor)): A tuple of tensors
  283. Returns:
  284. tuple of tensors, with each tensor promoted to ths same dtype.
  285. """
  286. need_cast = False
  287. final_type = tuple_of_tensors[0].dtype
  288. for tensor in tuple_of_tensors:
  289. if not _check_same_type(final_type, tensor.dtype):
  290. need_cast = True
  291. final_type = _promote(final_type, tensor.dtype)
  292. if not need_cast:
  293. return tuple_of_tensors
  294. tuple_of_casted_tensors = ()
  295. for tensor in tuple_of_tensors:
  296. tuple_of_casted_tensors += (tensor.astype(final_type, copy=False),)
  297. return tuple_of_casted_tensors
  298. def concatenate(arrays, axis=0):
  299. """
  300. Joins a sequence of tensors along an existing axis.
  301. Note:
  302. To match Numpy behaviour, :math:`axis >= 32` will not cause value error, the
  303. `axis` will be treated as :class:`None` instead.
  304. Args:
  305. arrays (Union[Tensor, tuple(Tensor), list(Tensor)]): a tensor or a list
  306. of tensors to be concatenated.
  307. axis (Union[None, int], optional): The axis along which the tensors will be joined,
  308. if `axis` is :class:`None`, tensors are flattened before use. Default is 0.
  309. Returns:
  310. A tensor concatenated from a tensor or a list of tensors.
  311. Raises:
  312. TypeError: If input arguments have types not specified above.
  313. ValueError: If `axis` is not in the range of :math:`[-ndim, ndim-1]`, and less than 32.
  314. Supported Platforms:
  315. ``Ascend`` ``GPU`` ``CPU``
  316. Examples:
  317. >>> import mindspore.numpy as np
  318. >>> x1 = np.ones((1,2,3))
  319. >>> x2 = np.ones((1,2,1))
  320. >>> x = np.concatenate((x1, x2), axis=-1)
  321. >>> print(x.shape)
  322. (1, 2, 4)
  323. """
  324. if isinstance(arrays, Tensor):
  325. # if only one tensor is provided, it is treated as a tuple along the
  326. # first dimension. For example, a tensor of shape (3,4,5) will be treated
  327. # as: tuple(tensor_1(4,5), tensor_2(4,5), tensor_3(4,5))
  328. if axis is None or axis >= MAX_NUMPY_DIMS:
  329. return ravel(arrays)
  330. arr_shape = F.shape(arrays)
  331. _check_axes_range((axis,), len(arr_shape))
  332. # move axis 0 to the disiganated position, while keep other axes' relative
  333. # positions unchanged
  334. new_axes, new_shape = _move_axes_for_concatenate(arr_shape, axis)
  335. arrays = transpose(arrays, new_axes)
  336. arrays = reshape(arrays, new_shape)
  337. return arrays
  338. flattened_arrays = ()
  339. if axis is None or axis >= MAX_NUMPY_DIMS:
  340. for arr in arrays:
  341. flattened_arrays += (ravel(arr),)
  342. axis = -1
  343. flattened_arrays = _promote_type_for_concatenate(flattened_arrays)
  344. return P.Concat(axis)(flattened_arrays)
  345. # convert a list of tensor to a tuple of tensor
  346. arrays = _convert_list_tensor_to_tuple_tensor(arrays)
  347. arr_shape = F.shape(arrays[0])
  348. _check_axes_range((axis,), len(arr_shape))
  349. # if only one tensor in the tuple/list, return the tensor itself
  350. if len(arrays) == 1:
  351. return arrays[0]
  352. arrays = _promote_type_for_concatenate(arrays)
  353. return P.Concat(axis)(arrays)
  354. def append(arr, values, axis=None):
  355. """
  356. Appends values to the end of a tensor.
  357. Args:
  358. arr (Tensor): Values are appended to a copy of this tensor.
  359. values (Tensor): These values are appended to a copy of `arr`. It must be of
  360. the correct shape (the same shape as `arr`, excluding `axis`). If `axis` is
  361. not specified, `values` can be any shape and will be flattened before use.
  362. axis (None, int, optional): The `axis` along which values are appended. If `axis` is not
  363. given, both `arr` and `values` are flattened before use, default is :class:`None`.
  364. Returns:
  365. Tensor, a copy of tensor with values appended to axis.
  366. Raises:
  367. TypeError: If input arguments have types not specified above.
  368. ValueError: If specified axis exceeds `arr.ndim`.
  369. Supported Platforms:
  370. ``Ascend`` ``GPU`` ``CPU``
  371. Examples:
  372. >>> import mindspore.numpy as np
  373. >>> a = np.ones((2, 3))
  374. >>> b = np.ones((2, 1))
  375. >>> print(np.append(a, b, axis=1).shape)
  376. (2, 4)
  377. """
  378. _check_input_tensor(arr)
  379. _check_input_tensor(values)
  380. if axis is None:
  381. arr = arr.ravel()
  382. values = values.ravel()
  383. else:
  384. _check_axis_in_range(axis, arr.ndim)
  385. if F.rank(arr) != F.rank(values):
  386. _raise_value_error("all tensors must have same number of dimensions")
  387. return concatenate((arr, values), axis)
  388. def column_stack(tup):
  389. """
  390. Stacks 1-D tensors as columns into a 2-D tensor. 2-D tensors are stacked as-is,
  391. like np.hstack.
  392. Args:
  393. tup (Union[Tensor, tuple, list]): A sequence of 1-D or 2-D tensors. All
  394. of them must have the same shape except the axis to be concatenated.
  395. Returns:
  396. 2-D Tensor, formed by stacking the given tensors.
  397. Supported Platforms:
  398. ``Ascend`` ``GPU`` ``CPU``
  399. Raises:
  400. TypeError: If `tup` is not Tensor, list or tuple.
  401. ValueError: If `tup` is empty.
  402. Examples:
  403. >>> import mindspore.numpy as np
  404. >>> x1 = np.array([1, 2, 3]).astype('int32')
  405. >>> x2 = np.array([4, 5, 6]).astype('int32')
  406. >>> output = np.column_stack((x1, x2))
  407. >>> print(output)
  408. [[1 4]
  409. [2 5]
  410. [3 6]]
  411. """
  412. if isinstance(tup, Tensor):
  413. return tup
  414. if not isinstance(tup, (list, tuple)):
  415. _raise_type_error("Tensor or, list or tuple of tensors are required, but got ", tup)
  416. trans_tup = ()
  417. for tensor in tup:
  418. if tensor.ndim < 1:
  419. tensor = F.expand_dims(tensor, 0)
  420. if tensor.ndim == 1:
  421. tensor = F.expand_dims(tensor, 1)
  422. trans_tup += (tensor,)
  423. if not trans_tup:
  424. _raise_value_error("Need at least one tensor to concatenate.")
  425. return P.Concat(1)(trans_tup)
  426. def vstack(tup):
  427. """
  428. Stacks tensors in sequence vertically.
  429. This is equivalent to concatenation along the first axis. 1-D tensors should firstly be reshaped to `(1, N)`,
  430. and then be concatenated along the first axis.
  431. Args:
  432. tup (Union[Tensor, tuple, list]): A sequence of 1-D or 2-D tensors. The tensors must have the same shape
  433. along all but the first axis. 1-D tensors must have the same shape.
  434. Returns:
  435. Stacked Tensor, formed by stacking the given tensors.
  436. Supported Platforms:
  437. ``Ascend`` ``GPU`` ``CPU``
  438. Raises:
  439. TypeError: If `tup` is not Tensor, list or tuple.
  440. ValueError: If `tup` is empty.
  441. Examples:
  442. >>> import mindspore.numpy as np
  443. >>> x1 = np.array([1, 2, 3]).astype('int32')
  444. >>> x2 = np.array([4, 5, 6]).astype('int32')
  445. >>> output = np.vstack((x1, x2))
  446. >>> print(output)
  447. [[1 2 3]
  448. [4 5 6]]
  449. """
  450. if isinstance(tup, Tensor):
  451. return tup
  452. if not isinstance(tup, (list, tuple)):
  453. _raise_type_error("Tensor or, list or tuple of tensors are required, but got", tup)
  454. trans_tup = ()
  455. for tensor in tup:
  456. if tensor.ndim <= 1:
  457. tensor = _expand(tensor, 2, 0)
  458. trans_tup += (tensor,)
  459. if not trans_tup:
  460. _raise_value_error("Need at least one tensor to concatenate.")
  461. return P.Concat(0)(trans_tup)
  462. def hstack(tup):
  463. """
  464. Stacks tensors in sequence horizontally.
  465. This is equivalent to concatenation along the second axis, except for 1-D tensors
  466. where it concatenates along the first axis.
  467. Args:
  468. tup (Union[Tensor, tuple, list]): A sequence of 1-D or 2-D tensors. The
  469. tensors must have the same shape along all but the second axis, except
  470. 1-D tensors which can be any length.
  471. Returns:
  472. Stacked Tensor, formed by stacking the given tensors.
  473. Supported Platforms:
  474. ``Ascend`` ``GPU`` ``CPU``
  475. Raises:
  476. TypeError: If `tup` is not Tensor, list or tuple.
  477. ValueError: If `tup` is empty.
  478. Examples:
  479. >>> import mindspore.numpy as np
  480. >>> x1 = np.array([1, 2, 3]).astype('float32')
  481. >>> x2 = np.array([4, 5, 6]).astype('float32')
  482. >>> output = np.hstack((x1, x2))
  483. >>> print(output)
  484. [1. 2. 3. 4. 5. 6.]
  485. """
  486. if isinstance(tup, Tensor):
  487. return tup
  488. if not isinstance(tup, (list, tuple)):
  489. _raise_type_error("Tensor or, list or tuple of tensors are required, but got", tup)
  490. tuple_of_tensor = ()
  491. for tensor in tup:
  492. if tensor.ndim < 1:
  493. tensor = F.expand_dims(tensor, 0)
  494. tuple_of_tensor += (tensor,)
  495. if not tuple_of_tensor:
  496. _raise_value_error("Need at least one tensor to concatenate.")
  497. if tuple_of_tensor[0].ndim <= 1:
  498. return P.Concat(0)(tuple_of_tensor)
  499. return P.Concat(1)(tuple_of_tensor)
  500. def dstack(tup):
  501. """
  502. Stacks tensors in sequence depth wise (along the third axis).
  503. This is equivalent to concatenation along the third axis. 1-D tensors :math:`(N,)` should be
  504. reshaped to :math:`(1,N,1)`.
  505. 2-D tensors :math:`(M,N)` should be reshaped to :math:`(M,N,1)` before concatenation.
  506. Args:
  507. tup (Union[Tensor, tuple, list]): A sequence of tensors. The tensors must have the same shape along all but
  508. the third axis. 1-D or 2-D tensors must have the same shape.
  509. Returns:
  510. Stacked Tensor, formed by stacking the given tensors.
  511. Supported Platforms:
  512. ``Ascend`` ``GPU`` ``CPU``
  513. Raises:
  514. TypeError: If `tup` is not Tensor, list or tuple.
  515. ValueError: If `tup` is empty.
  516. Examples:
  517. >>> import mindspore.numpy as np
  518. >>> x1 = np.array([1, 2, 3]).astype('float32')
  519. >>> x2 = np.array([4, 5, 6]).astype('float32')
  520. >>> output = np.dstack((x1, x2))
  521. >>> print(output)
  522. [[[1. 4.]
  523. [2. 5.]
  524. [3. 6.]]]
  525. """
  526. if isinstance(tup, Tensor):
  527. return tup
  528. if not isinstance(tup, (list, tuple)):
  529. _raise_type_error("Tensor or list or tuple of tensors are required, but got", tup)
  530. trans_tup = ()
  531. for tensor in tup:
  532. if tensor.ndim <= 1:
  533. tensor = _expand(tensor, 2, 0)
  534. if tensor.ndim == 2:
  535. tensor = F.expand_dims(tensor, 2)
  536. trans_tup += (tensor,)
  537. if not trans_tup:
  538. _raise_value_error("Need at least one tensor to concatenate.")
  539. return P.Concat(2)(trans_tup)
  540. def where(condition, x=None, y=None):
  541. """
  542. Returns elements chosen from `x` or `y` depending on `condition`.
  543. Note:
  544. As nonzero is not supported, neither `x` or `y` can be None.
  545. Args:
  546. condition (Tensor): where True, yield `x`, otherwise yield `y`.
  547. x (Tensor): Values from which to choose.
  548. y (Tensor): Values from which to choose. `x`, `y` and `condition` need
  549. to be broadcastable to some shape.
  550. Returns:
  551. Tensor or scalar, with elements from `x` where `condition` is True, and
  552. elements from `y` elsewhere.
  553. Raises:
  554. ValueError: if operands cannot be broadcast.
  555. Supported Platforms:
  556. ``Ascend`` ``GPU`` ``CPU``
  557. Examples:
  558. >>> import mindspore.numpy as np
  559. >>> condition = np.full((1, 1, 2), [False, True])
  560. >>> x = np.full((1, 3, 2), 5)
  561. >>> y = np.full((2, 1, 1), 7)
  562. >>> output = np.where(condition, x, y)
  563. >>> print(output)
  564. [[[7 5]
  565. [7 5]
  566. [7 5]]
  567. [[7 5]
  568. [7 5]
  569. [7 5]]]
  570. """
  571. condition, x, y = _to_tensor(condition, x, y)
  572. # type promotes input tensors
  573. dtype1 = F.dtype(x)
  574. dtype2 = F.dtype(y)
  575. dtype = _promote(dtype1, dtype2)
  576. if not _check_same_type(dtype1, dtype):
  577. x = F.cast(x, dtype)
  578. if not _check_same_type(dtype2, dtype):
  579. y = F.cast(y, dtype)
  580. is_bool = _check_same_type(dtype1, mstype.bool_) and _check_same_type(
  581. dtype2, mstype.bool_)
  582. if is_bool:
  583. # select does not support bool type for x or y
  584. x = F.cast(x, mstype.float32)
  585. y = F.cast(y, mstype.float32)
  586. # broadcasts input tensors
  587. shape_out = _infer_out_shape(F.shape(condition),
  588. F.shape(x), F.shape(y))
  589. if not _check_same_type(F.dtype(condition), mstype.float32):
  590. # tiling with bool is not supported on GPU
  591. condition = F.cast(condition, mstype.float32)
  592. condition = _broadcast_to_shape(condition, shape_out)
  593. x = _broadcast_to_shape(x, shape_out)
  594. y = _broadcast_to_shape(y, shape_out)
  595. if not _check_same_type(F.dtype(condition), mstype.bool_):
  596. condition = F.cast(condition, mstype.bool_)
  597. res = F.select(condition, x, y)
  598. if is_bool:
  599. res = F.cast(res, mstype.bool_)
  600. return res
  601. def _atleast_xd(ndim, arys):
  602. """Returns arys with at least ndim."""
  603. _check_input_tensor(*arys)
  604. res = []
  605. for arr in arys:
  606. arr = _expand(arr, ndim)
  607. res.append(arr)
  608. if len(res) == 1:
  609. return res[0]
  610. return res
  611. def atleast_1d(*arys):
  612. """
  613. Converts inputs to arrays with at least one dimension.
  614. Scalar inputs are converted to 1-dimensional arrays, whilst
  615. higher-dimensional inputs are preserved.
  616. Note:
  617. In graph mode, returns a tuple of tensor instead of a list of
  618. tensors.
  619. Args:
  620. *arys (Tensor): one or more input tensors.
  621. Returns:
  622. Tensor, or list of tensors, each with ``a.ndim >= 1``.
  623. Raises:
  624. TypeError: if the input is not a tensor.
  625. Supported Platforms:
  626. ``Ascend`` ``GPU`` ``CPU``
  627. Examples:
  628. >>> import mindspore.numpy as np
  629. >>> a = np.ones((2, 3))
  630. >>> b = np.ones(())
  631. >>> c = np.ones(5)
  632. >>> output = np.atleast_1d(a, b, c)
  633. >>> print(output)
  634. [Tensor(shape=[2, 3], dtype=Float32, value=
  635. [[1.00000000e+00, 1.00000000e+00, 1.00000000e+00],
  636. [1.00000000e+00, 1.00000000e+00, 1.00000000e+00]]),
  637. Tensor(shape=[1], dtype=Float32, value= [1.00000000e+00]),
  638. Tensor(shape=[5], dtype=Float32,
  639. value= [1.00000000e+00, 1.00000000e+00, 1.00000000e+00,
  640. 1.00000000e+00, 1.00000000e+00])]
  641. """
  642. return _atleast_xd(1, arys)
  643. def atleast_2d(*arys):
  644. """
  645. Reshapes inputs as arrays with at least two dimensions.
  646. Note:
  647. In graph mode, returns a tuple of tensor instead of a list of
  648. tensors.
  649. Args:
  650. *arys (Tensor): one or more input tensors.
  651. Returns:
  652. Tensor, or list of tensors, each with ``a.ndim >= 2``.
  653. Raises:
  654. TypeError: if the input is not a tensor.
  655. Supported Platforms:
  656. ``Ascend`` ``GPU`` ``CPU``
  657. Examples:
  658. >>> import mindspore.numpy as np
  659. >>> a = np.ones((2, 3))
  660. >>> b = np.ones(())
  661. >>> c = np.ones(5)
  662. >>> output = np.atleast_2d(a, b, c)
  663. >>> print(output)
  664. [Tensor(shape=[2, 3], dtype=Float32, value=
  665. [[1.00000000e+00, 1.00000000e+00, 1.00000000e+00],
  666. [1.00000000e+00, 1.00000000e+00, 1.00000000e+00]]),
  667. Tensor(shape=[1, 1], dtype=Float32, value= [[1.00000000e+00]]),
  668. Tensor(shape=[1, 5], dtype=Float32,
  669. value= [[1.00000000e+00, 1.00000000e+00, 1.00000000e+00,
  670. 1.00000000e+00, 1.00000000e+00]])]
  671. """
  672. return _atleast_xd(2, arys)
  673. def atleast_3d(*arys):
  674. """
  675. Reshapes inputs as arrays with at least three dimensions.
  676. Note:
  677. In graph mode, returns a tuple of tensor instead of a list of
  678. tensors.
  679. Args:
  680. *arys (Tensor): one or more input tensors.
  681. Returns:
  682. Tensor, or list of tensors, each with ``a.ndim >= 3``. For example,
  683. a 1-D array of shape `(N,)` becomes a tensor of shape `(1, N, 1)`, and
  684. a 2-D array of shape `(M, N)` becomes a tensor of shape `(M, N, 1)`.
  685. Raises:
  686. TypeError: if the input is not a tensor.
  687. Supported Platforms:
  688. ``Ascend`` ``GPU`` ``CPU``
  689. Examples:
  690. >>> import mindspore.numpy as np
  691. >>> a = np.ones((2, 3))
  692. >>> b = np.ones(())
  693. >>> c = np.ones(5)
  694. >>> output = np.atleast_3d(a, b, c)
  695. >>> print(output)
  696. [Tensor(shape=[2, 3, 1], dtype=Float32, value=
  697. [[[1.00000000e+00], [1.00000000e+00], [1.00000000e+00]],
  698. [[1.00000000e+00], [1.00000000e+00], [1.00000000e+00]]]),
  699. Tensor(shape=[1, 1, 1], dtype=Float32, value= [[[1.00000000e+00]]]),
  700. Tensor(shape=[1, 5, 1], dtype=Float32,
  701. value= [[[1.00000000e+00], [1.00000000e+00], [1.00000000e+00],
  702. [1.00000000e+00], [1.00000000e+00]]])]
  703. """
  704. res = []
  705. for arr in arys:
  706. ndim = F.rank(arr)
  707. if ndim == 0:
  708. arr = F.reshape(arr, (1, 1, 1))
  709. elif ndim == 1:
  710. arr = F.reshape(arr, (1, F.size(arr), 1))
  711. elif ndim == 2:
  712. arr = F.reshape(arr, F.shape(arr) + (1,))
  713. res.append(arr)
  714. if len(res) == 1:
  715. return res[0]
  716. return res
  717. def stack(arrays, axis=0):
  718. """
  719. Joins a sequence of arrays along a new axis.
  720. The `axis` parameter specifies the index of the new axis in the
  721. dimensions of the result. For example, if ``axis=0`` it will be the
  722. first dimension and if ``axis=-1`` it will be the last dimension.
  723. Note:
  724. Numpy argument out is not supported.
  725. Args:
  726. arrays (sequence of Tensor): Each array must have the same shape.
  727. axis (int, optional): The axis in the result array along which the
  728. input arrays are stacked.
  729. Returns:
  730. Tensor, The stacked array has one more dimension than the input
  731. arrays.
  732. Raises:
  733. ValueError: if input is not Tensor, tuple, or list.
  734. Supported Platforms:
  735. ``Ascend`` ``GPU`` ``CPU``
  736. Examples:
  737. >>> import mindspore.numpy as np
  738. >>> arrays = [np.ones((3, 4)) for _ in range(10)]
  739. >>> output = np.stack(arrays, axis=0)
  740. >>> print(output.shape)
  741. (10, 3, 4)
  742. >>> output = np.stack(arrays, axis=1)
  743. >>> print(output.shape)
  744. (3, 10, 4)
  745. >>> output = np.stack(arrays, axis=2)
  746. >>> print(output.shape)
  747. (3, 4, 10)
  748. """
  749. if isinstance(arrays, Tensor):
  750. shape = F.shape(arrays)
  751. ndim = F.rank(arrays)
  752. axis = axis % ndim
  753. axes = F.make_range(ndim)
  754. perm = axes[1:axis+1] + (0,) + axes[axis+1:]
  755. if _is_shape_empty(shape):
  756. return _empty(mstype.float32, shape[1:axis+1] + (shape[0],) + shape[axis+1:])
  757. return transpose(arrays, perm)
  758. if isinstance(arrays, (list, tuple)):
  759. shape = (len(arrays),) + F.shape(arrays[0])
  760. ndim = len(shape)
  761. axis = axis % ndim
  762. if _is_shape_empty(shape):
  763. return _empty(mstype.float32, shape[1:axis+1] + (shape[0],) + shape[axis+1:])
  764. seq = ()
  765. for arr in arrays:
  766. seq += (F.expand_dims(arr, axis),)
  767. return concatenate(seq, axis)
  768. return _raise_value_error('input arrays must be Tensor, tuple, or list')
  769. class UniqueNet(Cell):
  770. """The operation is wrapped inside a model. """
  771. def __init__(self):
  772. super(UniqueNet, self).__init__()
  773. self.unique = P.Unique()
  774. def construct(self, x):
  775. return self.unique(x)
  776. def unique(x, return_inverse=False):
  777. """
  778. Finds the unique elements of a tensor. The input tensor will be flattened first
  779. when it has more than one dimension.
  780. Note:
  781. Numpy arguments `axis`, `return_index` and `return_counts` are not supported.
  782. On CPU, this operator must be executed in graph mode.
  783. Args:
  784. x (Tensor): The input tensor to be processed.
  785. return_inverse (bool): If `True`, also return the indices of the unique tensor.
  786. Default: `False`.
  787. Returns:
  788. Tensor or tuple of Tensors.
  789. - If `return_inverse` is `False`, just return the unique tensor.
  790. - If `return_inverse` is `True`, return tuple of tensors.
  791. Supported Platforms:
  792. ``Ascend`` ``GPU`` ``CPU``
  793. Raises:
  794. TypeError: If `x` is not tensor.
  795. Examples:
  796. >>> import mindspore.numpy as np
  797. >>> from mindspore import context
  798. >>> context.set_context(mode=context.GRAPH_MODE)
  799. >>> input_x = np.asarray([1, 2, 2, 2, 3, 4, 5]).astype('int32')
  800. >>> output_x = np.unique(input_x)
  801. >>> print(output_x)
  802. [1 2 3 4 5]
  803. >>> output_x = np.unique(input_x, return_inverse=True)
  804. >>> print(output_x)
  805. (Tensor(shape=[5], dtype=Int32, value= [ 1, 2, 3, 4, 5]), Tensor(shape=[7], dtype=Int32,
  806. value= [0, 1, 1, 1, 2, 3, 4]))
  807. """
  808. _check_input_tensor(x)
  809. if F.tuple_len(F.shape(x)) > 1:
  810. x = ravel(x)
  811. uniq = UniqueNet()
  812. res = uniq(x)
  813. if not return_inverse:
  814. return res[0]
  815. return res
  816. def roll_along_axis(a, shift, axis):
  817. """
  818. Rolls a tensor along a given axis. This is a helper function of np.roll.
  819. Args:
  820. a (Tensor): Input tensor.
  821. shift (int): The number of places the tensor is shifted.
  822. axis (int): The designated axis for shifting.
  823. Returns:
  824. Shifted tensor.
  825. """
  826. _check_axis_in_range(axis, a.ndim)
  827. _check_element_int((shift, axis))
  828. if axis < 0:
  829. axis += a.ndim
  830. shift = -(shift % a.shape[axis])
  831. # if shift is 0, we do not need to roll at all
  832. if shift == 0:
  833. return a
  834. begin1 = ()
  835. begin2 = ()
  836. end1 = ()
  837. end2 = ()
  838. stride = _list_comprehensions(a.ndim, 1, True)
  839. for i in F.make_range(a.ndim):
  840. if i != axis:
  841. begin1 += (0,)
  842. end1 += (a.shape[i],)
  843. begin2 += (0,)
  844. end2 += (a.shape[i],)
  845. else:
  846. begin1 += (shift,)
  847. end1 += (a.shape[i],)
  848. begin2 += (0,)
  849. end2 += (shift,)
  850. return append(F.strided_slice(a, begin1, end1, stride),
  851. F.strided_slice(a, begin2, end2, stride), axis=axis)
  852. def roll(a, shift, axis=None):
  853. """
  854. Rolls a tensor along given axes.
  855. Elements that rolls beyond the last position are re-introduced at the first.
  856. Args:
  857. a (Tensor): Input tensor.
  858. shift (Union[int, tuple(int)]: The number of places by which elements are
  859. shifted. If a tuple, then axis must be a tuple of the same size, and
  860. each of the given axes is shifted by the corresponding number. If shift
  861. is an int while axis is a tuple of ints, then the same value is used
  862. for all given axes.
  863. axis (Union[int, tuple(int)], optional): Axis or axes along which elements
  864. are shifted. By default, the array is flattened before shifting, after
  865. which the original shape is restored.
  866. Returns:
  867. Tensor, with the same shape as a.
  868. Supported Platforms:
  869. ``Ascend`` ``GPU`` ``CPU``
  870. Raises:
  871. TypeError: If input arguments have types not specified above.
  872. ValueError: If axis exceeds `a.ndim`, or `shift` and `axis` cannot broadcast.
  873. Examples:
  874. >>> import mindspore.numpy as np
  875. >>> a = np.reshape(np.arange(12), (3, 4))
  876. >>> print(np.roll(a, [2,-3], [0,-1]))
  877. [[ 7 4 5 6]
  878. [11 8 9 10]
  879. [ 3 0 1 2]]
  880. """
  881. _check_input_tensor(a)
  882. original_shape = a.shape
  883. original_dtype = a.dtype
  884. restore_shape = False
  885. # F.strided_slice only supports float on cpu, this will change once more supports
  886. # are added.
  887. if not _check_is_float(original_dtype):
  888. a = a.astype(mstype.float32)
  889. if axis is None:
  890. restore_shape = True
  891. axis = 0
  892. a = a.ravel()
  893. # Broadcast shift and axis to the same length
  894. shift, axis = _broadcast_tuples(shift, axis)
  895. for shift_each, axis_each in zip(shift, axis):
  896. a = roll_along_axis(a, shift_each, axis_each)
  897. if restore_shape:
  898. a = a.reshape(original_shape)
  899. if not _check_is_float(original_dtype):
  900. a = a.astype(original_dtype)
  901. return a
  902. @constexpr
  903. def _get_moved_perm(ndim, source, destination):
  904. """
  905. Helper function for moveaxis, returns permutation after moving axes
  906. from source to destination.
  907. """
  908. dest_sorted_idx = [i for i, _ in sorted(enumerate(destination),
  909. key=operator.itemgetter(1))]
  910. axes_orig = [i for i in range(ndim) if i not in source]
  911. k = 0
  912. m = 0
  913. perm = []
  914. for i in dest_sorted_idx:
  915. # inserts an axis that has been moved, denoted by n, and axes that remain
  916. # in their original position, indexed from k to k + n - m, into index m in
  917. # the list of permuted axes
  918. n = destination[i]
  919. j = k + n - m
  920. perm += axes_orig[k:j]
  921. perm.append(source[i])
  922. k += n - m
  923. m = n + 1
  924. perm += axes_orig[k:]
  925. return tuple(perm)
  926. @constexpr
  927. def _get_moved_shape(shape, perm):
  928. """
  929. Helper function for moveaxis, returns the permuated shape after
  930. applying perm.
  931. """
  932. return tuple([shape[i] for i in perm])
  933. def moveaxis(a, source, destination):
  934. """
  935. Moves axes of an array to new positions.
  936. Other axes remain in their original order.
  937. Args:
  938. a (Tensor): The array whose axes should be reordered.
  939. source (int or sequence of ints): Original positions of the
  940. axes to move. These must be unique.
  941. destination (int or sequence of ints): Destination positions
  942. for each of the original axes. These must also be unique.
  943. Returns:
  944. Tensor, array with moved axes.
  945. Raises:
  946. ValueError: if axes are out of the range of ``[-a.ndim, a.ndim)``, or
  947. if the axes contain duplicates.
  948. Supported Platforms:
  949. ``Ascend`` ``GPU`` ``CPU``
  950. Examples:
  951. >>> import mindspore.numpy as np
  952. >>> x = np.zeros((3, 4, 5))
  953. >>> output = np.moveaxis(x, 0, -1)
  954. >>> print(output.shape)
  955. (4, 5, 3)
  956. >>> output = np.moveaxis(x, -1, 0)
  957. >>> print(output.shape)
  958. (5, 3, 4)
  959. >>> output = np.moveaxis(x, [0, 1, 2], [-1, -2, -3])
  960. >>> print(output.shape)
  961. (5, 4, 3)
  962. """
  963. ndim = F.rank(a)
  964. source = _check_axis_valid(source, ndim)
  965. destination = _check_axis_valid(destination, ndim)
  966. if len(source) != len(destination):
  967. _raise_value_error('`source` and `destination` arguments must have the same number of elements')
  968. perm = _get_moved_perm(ndim, source, destination)
  969. shape = F.shape(a)
  970. if _is_shape_empty(shape):
  971. return _empty(F.dtype(a), _get_moved_shape(shape, perm))
  972. return F.transpose(a, perm)
  973. def tile(a, reps):
  974. """
  975. Constructs an array by repeating `a` the number of times given by `reps`.
  976. If `reps` has length `d`, the result will have dimension of ``max(d, a.ndim)``.
  977. If ``a.ndim < d``, `a` is promoted to be d-dimensional by prepending new axes.
  978. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or
  979. shape (1, 1, 3) for 3-D replication. If this is not the desired behavior,
  980. promote `a` to d-dimensions manually before calling this function.
  981. If ``a.ndim > d``, `reps` is promoted to ``a.ndim`` by pre-pending 1’s to it. Thus
  982. for an `a` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as (1, 1, 2, 2).
  983. Args:
  984. a (Tensor): The input array.
  985. reps (int or sequence of ints): The number of repetitions of `a` along
  986. each axis.
  987. Returns:
  988. Tensor, the tiled output array.
  989. Raises:
  990. TypeError: if the input is not a tensor.
  991. Supported Platforms:
  992. ``Ascend`` ``GPU`` ``CPU``
  993. Examples:
  994. >>> import mindspore.numpy as np
  995. >>> a = np.array([0, 1, 2])
  996. >>> output = np.tile(a, 2)
  997. >>> print(output)
  998. [0 1 2 0 1 2]
  999. >>> output = np.tile(a, (2, 2))
  1000. >>> print(output)
  1001. [[0 1 2 0 1 2]
  1002. [0 1 2 0 1 2]]
  1003. >>> output = np.tile(a, (2, 1, 2))
  1004. >>> print(output)
  1005. [[[0 1 2 0 1 2]]
  1006. [[0 1 2 0 1 2]]]
  1007. """
  1008. _check_input_tensor(a)
  1009. ndim = F.rank(a)
  1010. shape = F.shape(a)
  1011. reps = _add_unit_axes(reps, ndim)
  1012. if _is_shape_empty(shape) or _is_shape_empty(reps):
  1013. shape = _add_unit_axes(shape, len(reps))
  1014. return _empty(F.dtype(a), _seq_prod(shape, reps))
  1015. return F.tile(a, reps)
  1016. @constexpr
  1017. def _check_can_broadcast_to(shape, target_shape):
  1018. """Determines if shape can be broadcast to target_shape."""
  1019. ndim = len(shape)
  1020. ndim_target = len(target_shape)
  1021. if ndim > ndim_target:
  1022. return False
  1023. for i, j in zip(reversed(shape), reversed(target_shape)):
  1024. if i not in (1, j):
  1025. return False
  1026. return True
  1027. def broadcast_to(array, shape):
  1028. """
  1029. Broadcasts an array to a new shape.
  1030. Args:
  1031. array (Tensor): The array to broadcast.
  1032. shape (tuple): The shape of the desired array.
  1033. Returns:
  1034. Tensor, original array broadcast to the given shape.
  1035. Raises:
  1036. ValueError: if array cannot be broadcast to shape.
  1037. Supported Platforms:
  1038. ``Ascend`` ``GPU`` ``CPU``
  1039. Example:
  1040. >>> import mindspore.numpy as np
  1041. >>> x = np.array([1, 2, 3])
  1042. >>> output = np.broadcast_to(x, (3, 3))
  1043. >>> print(output)
  1044. [[1 2 3]
  1045. [1 2 3]
  1046. [1 2 3]]
  1047. """
  1048. shape_a = F.shape(array)
  1049. if not _check_can_broadcast_to(shape_a, shape):
  1050. return _raise_value_error('cannot broadcast with ', shape)
  1051. return _broadcast_to_shape(array, shape)
  1052. def broadcast_arrays(*args):
  1053. """
  1054. Broadcasts any number of arrays against each other.
  1055. Note:
  1056. Numpy argument `subok` is not supported.
  1057. In graph mode, returns a tuple of Tensor instead of a list
  1058. of Tensor.
  1059. Args:
  1060. *args (Tensor): The arrays to broadcast.
  1061. Returns:
  1062. List of Tensor.
  1063. Raises:
  1064. ValueError: if arrays cannot be broadcast.
  1065. Supported Platforms:
  1066. ``Ascend`` ``GPU`` ``CPU``
  1067. Example:
  1068. >>> import mindspore.numpy as np
  1069. >>> x = np.array([[1,2,3]])
  1070. >>> y = np.array([[4],[5]])
  1071. >>> output = np.broadcast_arrays(x, y)
  1072. >>> print(output)
  1073. [Tensor(shape=[2, 3], dtype=Int32, value=
  1074. [[1, 2, 3],
  1075. [1, 2, 3]]), Tensor(shape=[2, 3], dtype=Int32, value=
  1076. [[4, 4, 4],
  1077. [5, 5, 5]])]
  1078. """
  1079. shapes = map(F.shape, args)
  1080. out_shape = _infer_out_shape(*shapes)
  1081. res = []
  1082. for arr in args:
  1083. res.append(broadcast_to(arr, out_shape))
  1084. return res
  1085. def array_split(x, indices_or_sections, axis=0):
  1086. """
  1087. Splits a tensor into multiple sub-tensors.
  1088. Note:
  1089. Currently, array_split only supports :class:`mindspore.float32` on ``CPU``.
  1090. The only difference between ``np.split`` and ``np.array_split`` is that
  1091. ``np.array_split`` allows indices_or_sections to be an integer that does not
  1092. equally divide the axis. For a tensor of length l that should be split into
  1093. n sections, it returns :math:`l % n` sub-arrays of size :math:`l//n + 1` and
  1094. the rest of size :math:`l//n`.
  1095. Args:
  1096. x (Tensor): A Tensor to be divided.
  1097. indices_or_sections (Union[int, tuple(int), list(int)]):
  1098. If integer, :math:`N`, the tensor will be divided into
  1099. :math:`N` tensors along axis.
  1100. If tuple(int), list(int) or of sorted integers,
  1101. the entries indicate where along axis the array is split.
  1102. For example, :math:`[2, 3]` would, for :math:`axis=0`, result in
  1103. three sub-tensors :math:`x[:2]`, :math:`x[2:3]`and :math:`x[3:]`.
  1104. If an index exceeds the dimension of the array along axis,
  1105. an empty sub-array is returned correspondingly.
  1106. axis (int): The axis along which to split. Default: 0.
  1107. Returns:
  1108. A list of sub-tensors.
  1109. Raises:
  1110. TypeError: If argument `indices_or_sections` is not integer,
  1111. tuple(int) or list(int) or argument `axis` is not integer.
  1112. ValueError: If argument `axis` is out of range of :math:`[-x.ndim, x.ndim)`.
  1113. Supported Platforms:
  1114. ``Ascend`` ``GPU`` ``CPU``
  1115. Examples:
  1116. >>> import mindspore.numpy as np
  1117. >>> input_x = np.arange(9).astype("float32")
  1118. >>> output = np.array_split(input_x, 4)
  1119. >>> print(output)
  1120. (Tensor(shape=[3], dtype=Float32,
  1121. value= [ 0.00000000e+00, 1.00000000e+00, 2.00000000e+00]),
  1122. Tensor(shape=[2], dtype=Float32,
  1123. value= [ 3.00000000e+00, 4.00000000e+00]),
  1124. Tensor(shape=[2], dtype=Float32,
  1125. value= [ 5.00000000e+00, 6.00000000e+00]),
  1126. Tensor(shape=[2], dtype=Float32,
  1127. value= [ 7.00000000e+00, 8.00000000e+00]))
  1128. """
  1129. return _split(x, indices_or_sections, opname="array_split", axis=axis)
  1130. def split(x, indices_or_sections, axis=0):
  1131. """
  1132. Splits a tensor into multiple sub-tensors along the given axis.
  1133. Args:
  1134. x (Tensor): A Tensor to be divided.
  1135. indices_or_sections (Union[int, tuple(int), list(int)]):
  1136. If integer, :math:`N`, the tensor will be divided into
  1137. :math:`N` equal tensors along axis.
  1138. If tuple(int), list(int) or of sorted integers,
  1139. the entries indicate where along axis the array is split.
  1140. For example, :math:`[2, 3]` would, for :math:`axis=0`, result in
  1141. three sub-tensors :math:`x[:2]`, :math:`x[2:3]`and :math:`x[3:]`.
  1142. If an index exceeds the dimension of the array along axis,
  1143. an empty sub-array is returned correspondingly.
  1144. axis (int): The axis along which to split. Default: 0.
  1145. Returns:
  1146. A list of sub-tensors.
  1147. Raises:
  1148. TypeError: If argument `indices_or_sections` is not integer,
  1149. tuple(int) or list(int) or argument `axis` is not integer.
  1150. ValueError: If argument `axis` is out of range of :math:`[-x.ndim, x.ndim)`.
  1151. Supported Platforms:
  1152. ``Ascend`` ``GPU`` ``CPU``
  1153. Examples:
  1154. >>> import mindspore.numpy as np
  1155. >>> input_x = np.arange(9).astype("float32")
  1156. >>> output = np.split(input_x, 3)
  1157. >>> print(output)
  1158. (Tensor(shape=[3], dtype=Float32,
  1159. value= [ 0.00000000e+00, 1.00000000e+00, 2.00000000e+00]),
  1160. Tensor(shape=[3], dtype=Float32,
  1161. value= [ 3.00000000e+00, 4.00000000e+00, 5.00000000e+00]),
  1162. Tensor(shape=[3], dtype=Float32,
  1163. value= [ 6.00000000e+00, 7.00000000e+00, 8.00000000e+00]))
  1164. """
  1165. return _split(x, indices_or_sections, opname="split", axis=axis)
  1166. def _split(x, indices_or_sections, opname, axis=0):
  1167. """Splits a tensor based on ``np.split`` or ``np.array_split``."""
  1168. _check_input_tensor(x)
  1169. _ = _check_axis_type(axis, True, False, False)
  1170. axis = _canonicalize_axis(axis, x.ndim)
  1171. res = None
  1172. arr_shape = x.shape
  1173. length_along_dim = arr_shape[axis]
  1174. if isinstance(indices_or_sections, int):
  1175. if indices_or_sections > length_along_dim:
  1176. _raise_value_error("empty tensor encountered.")
  1177. if opname == "split" or length_along_dim % indices_or_sections == 0:
  1178. res = P.Split(axis, indices_or_sections)(x)
  1179. else:
  1180. num_long_tensor = length_along_dim % indices_or_sections
  1181. num_short_tensor = indices_or_sections - num_long_tensor
  1182. length1 = num_long_tensor * (length_along_dim // indices_or_sections + 1)
  1183. length2 = length_along_dim - length1
  1184. start1 = _list_comprehensions(F.rank(x), 0, True)
  1185. size1 = _tuple_setitem(arr_shape, axis, length1)
  1186. start2 = _tuple_setitem(start1, axis, length1)
  1187. size2 = _tuple_setitem(arr_shape, axis, length2)
  1188. res = P.Split(axis, num_long_tensor)(F.tensor_slice(x, start1, size1)) + \
  1189. P.Split(axis, num_short_tensor)(F.tensor_slice(x, start2, size2))
  1190. elif isinstance(indices_or_sections, (list, tuple)) and _check_element_int(indices_or_sections):
  1191. res = _split_sub_tensors(x, indices_or_sections, axis)
  1192. else:
  1193. _raise_type_error("Argument `indices_or_sections` in `mindspore.numpy.split`\
  1194. should be integer, tuple(int) or list(int), but got", indices_or_sections)
  1195. return res
  1196. @constexpr
  1197. def convert_neg_indices(indices, ndim):
  1198. """converts negative values in tuple/list indices"""
  1199. def canonicalizer(ax):
  1200. return ax + ndim if ax < 0 else ax
  1201. indices = tuple([canonicalizer(axis) for axis in indices])
  1202. return indices
  1203. def _split_sub_tensors(x, indices, axis):
  1204. """
  1205. Splits the input tensor `x` into multiple sub-tensors
  1206. along the axis according to the given indices.
  1207. """
  1208. length_along_dim = x.shape[axis]
  1209. indices = convert_neg_indices(indices, length_along_dim)
  1210. indices += (length_along_dim,)
  1211. sub_tensors = []
  1212. strides = _list_comprehensions(x.ndim, 1, True)
  1213. begin = _list_comprehensions(x.ndim, 0)
  1214. end = _list_comprehensions(x.shape)
  1215. for i, idx in enumerate(indices):
  1216. begin[axis] = 0 if i == 0 else indices[i-1]
  1217. end[axis] = idx
  1218. if end[axis] <= begin[axis]:
  1219. _raise_value_error("empty sub-tensor encountered.")
  1220. sliced_tensor = F.strided_slice(x, _type_convert(tuple, begin), _type_convert(tuple, end), strides)
  1221. sub_tensors.append(sliced_tensor)
  1222. return sub_tensors
  1223. def vsplit(x, indices_or_sections):
  1224. """
  1225. Splits a tensor into multiple sub-tensors vertically (row-wise).
  1226. It is equivalent to split with :math:`axis=0` (default), the array is always
  1227. split along the first axis regardless of the array dimension.
  1228. Args:
  1229. x (Tensor): A Tensor to be divided.
  1230. indices_or_sections (Union[int, tuple(int), list(int)]):
  1231. If integer, :math:`N`, the tensor will be divided into
  1232. :math:`N` equal tensors along axis.
  1233. If tuple(int), list(int) or of sorted integers,
  1234. the entries indicate where along axis the array is split.
  1235. For example, :math:`[2, 3]` would, for :math:`axis=0`, result in
  1236. three sub-tensors :math:`x[:2]`, :math:`x[2:3]`and :math:`x[3:]`.
  1237. If an index exceeds the dimension of the array along axis,
  1238. an empty sub-array is returned correspondingly.
  1239. Returns:
  1240. A list of sub-tensors.
  1241. Raises:
  1242. TypeError: If argument `indices_or_sections` is not integer.
  1243. Supported Platforms:
  1244. ``Ascend`` ``GPU`` ``CPU``
  1245. Examples:
  1246. >>> import mindspore.numpy as np
  1247. >>> input_x = np.arange(9).reshape((3, 3)).astype('float32')
  1248. >>> output = np.vsplit(input_x, 3)
  1249. >>> print(output)
  1250. (Tensor(shape=[1, 3], dtype=Float32,
  1251. value=[[ 0.00000000e+00, 1.00000000e+00, 2.00000000e+00]]),
  1252. Tensor(shape=[1, 3], dtype=Float32,
  1253. value=[[ 3.00000000e+00, 4.00000000e+00, 5.00000000e+00]]),
  1254. Tensor(shape=[1, 3], dtype=Float32,
  1255. value=[[ 6.00000000e+00, 7.00000000e+00, 8.00000000e+00]]))
  1256. """
  1257. return split(x, indices_or_sections, 0)
  1258. def hsplit(x, indices_or_sections):
  1259. """
  1260. Splits a tensor into multiple sub-tensors horizontally (column-wise).
  1261. It is equivalent to split with :math:`axis=1` (default), the array is always
  1262. split along the second axis regardless of the array dimension.
  1263. Args:
  1264. x (Tensor): A Tensor to be divided.
  1265. indices_or_sections (Union[int, tuple(int), list(int)]):
  1266. If integer, :math:`N`, the tensor will be divided into
  1267. :math:`N` equal tensors along axis.
  1268. If tuple(int), list(int) or of sorted integers,
  1269. the entries indicate where along axis the array is split.
  1270. For example, :math:`[2, 3]` would, for :math:`axis=0`, result in
  1271. three sub-tensors :math:`x[:2]`, :math:`x[2:3]`and :math:`x[3:]`.
  1272. If an index exceeds the dimension of the array along axis,
  1273. an empty sub-array is returned correspondingly.
  1274. Returns:
  1275. A list of sub-tensors.
  1276. Raises:
  1277. TypeError: If argument `indices_or_sections` is not integer.
  1278. Supported Platforms:
  1279. ``Ascend`` ``GPU`` ``CPU``
  1280. Examples:
  1281. >>> import mindspore.numpy as np
  1282. >>> input_x = np.arange(6).reshape((2, 3)).astype('float32')
  1283. >>> output = np.hsplit(input_x, 3)
  1284. >>> print(output)
  1285. (Tensor(shape=[2, 1], dtype=Float32,
  1286. value=[[ 0.00000000e+00],
  1287. [ 3.00000000e+00]]),
  1288. Tensor(shape=[2, 1], dtype=Float32,
  1289. value=[[ 1.00000000e+00],
  1290. [ 4.00000000e+00]]),
  1291. Tensor(shape=[2, 1], dtype=Float32,
  1292. value=[[ 2.00000000e+00],
  1293. [ 5.00000000e+00]]))
  1294. """
  1295. return split(x, indices_or_sections, 1)
  1296. def dsplit(x, indices_or_sections):
  1297. """
  1298. Splits a tensor into multiple sub-tensors along the 3rd axis (depth).
  1299. It is equivalent to split with :math:`axis=2` (default), the array is always
  1300. split along the third axis regardless of the array dimension.
  1301. Args:
  1302. x (Tensor): A Tensor to be divided.
  1303. indices_or_sections (Union[int, tuple(int), list(int)]):
  1304. If integer, :math:`N`, the tensor will be divided into
  1305. :math:`N` equal tensors along axis.
  1306. If tuple(int), list(int) or of sorted integers,
  1307. the entries indicate where along axis the array is split.
  1308. For example, :math:`[2, 3]` would, for :math:`axis=0`, result in
  1309. three sub-tensors :math:`x[:2]`, :math:`x[2:3]`and :math:`x[3:]`.
  1310. If an index exceeds the dimension of the array along axis,
  1311. an empty sub-array is returned correspondingly.
  1312. Returns:
  1313. A list of sub-tensors.
  1314. Raises:
  1315. TypeError: If argument `indices_or_sections` is not integer.
  1316. Supported Platforms:
  1317. ``Ascend`` ``GPU`` ``CPU``
  1318. Examples:
  1319. >>> import mindspore.numpy as np
  1320. >>> input_x = np.arange(6).reshape((1, 2, 3)).astype('float32')
  1321. >>> output = np.dsplit(input_x, 3)
  1322. >>> print(output)
  1323. (Tensor(shape=[1, 2, 1], dtype=Float32,
  1324. value=[[[ 0.00000000e+00],
  1325. [ 3.00000000e+00]]]),
  1326. Tensor(shape=[1, 2, 1], dtype=Float32,
  1327. value=[[[ 1.00000000e+00],
  1328. [ 4.00000000e+00]]]),
  1329. Tensor(shape=[1, 2, 1], dtype=Float32,
  1330. value=[[[ 2.00000000e+00],
  1331. [ 5.00000000e+00]]]))
  1332. """
  1333. return split(x, indices_or_sections, 2)
  1334. @constexpr
  1335. def _get_flip_start(ndim, shape, axes):
  1336. return tuple([shape[i] - 1 if i in axes else 0 for i in range(ndim)])
  1337. @constexpr
  1338. def _get_flip_end(ndim, shape, axes):
  1339. return tuple([-shape[i] - 1 if i in axes else shape[i] + 1 for i in range(ndim)])
  1340. @constexpr
  1341. def _get_flip_strides(ndim, axes):
  1342. return tuple([-1 if i in axes else 1 for i in range(ndim)])
  1343. def flip(m, axis=None):
  1344. """
  1345. Reverses the order of elements in an array along the given axis.
  1346. The shape of the array is preserved, but the elements are reordered.
  1347. Note:
  1348. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.
  1349. Args:
  1350. m (Tensor): Input array.
  1351. axis (None or int or tuple of ints, optional): Axis or axes along which
  1352. to flip over. The default, ``axis=None``, will flip over all of the axes
  1353. of the input array. If `axis` is negative it counts from the last to
  1354. the first axis. If `axis` is a tuple of ints, flipping is performed on
  1355. all of the axes specified in the tuple.
  1356. Returns:
  1357. Tensor, with the entries of `axis` reversed.
  1358. Raises:
  1359. TypeError: if the input is not a tensor.
  1360. Supported Platforms:
  1361. ``GPU``
  1362. Example:
  1363. >>> import mindspore.numpy as np
  1364. >>> A = np.arange(8.0).reshape((2,2,2))
  1365. >>> output = np.flip(A)
  1366. >>> print(output)
  1367. [[[7. 6]
  1368. [5. 4]]
  1369. [[3. 2]
  1370. [1. 0]]]
  1371. >>> output = np.flip(A, (0, 2))
  1372. >>> print(output)
  1373. [[[5. 4]
  1374. [7. 6]]
  1375. [[1. 0]
  1376. [3. 2]]]
  1377. """
  1378. _check_input_tensor(m)
  1379. ndim = F.rank(m)
  1380. axes = _check_axis_valid(axis, ndim)
  1381. shape = F.shape(m)
  1382. dtype = F.dtype(m)
  1383. if _is_shape_empty(shape):
  1384. return m
  1385. if not _check_is_float(dtype):
  1386. m = m.astype(mstype.float32)
  1387. start = _get_flip_start(ndim, shape, axes)
  1388. end = _get_flip_end(ndim, shape, axes)
  1389. strides = _get_flip_strides(ndim, axes)
  1390. res = F.strided_slice(m, start, end, strides)
  1391. if not _check_same_type(F.dtype(res), dtype):
  1392. res = F.cast(res, dtype)
  1393. return res
  1394. def flipud(m):
  1395. """
  1396. Flips the entries in each column in the up/down direction.
  1397. Rows are preserved, but appear in a different order than before.
  1398. Note:
  1399. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.
  1400. Args:
  1401. m (Tensor): Input array.
  1402. Returns:
  1403. Tensor.
  1404. Raises:
  1405. TypeError: if the input is not a tensor.
  1406. Supported Platforms:
  1407. ``GPU``
  1408. Example:
  1409. >>> import mindspore.numpy as np
  1410. >>> A = np.arange(8.0).reshape((2,2,2))
  1411. >>> output = np.flipud(A)
  1412. >>> print(output)
  1413. [[[4. 5.]
  1414. [6. 7.]]
  1415. [[0. 1.]
  1416. [2. 3.]]]
  1417. """
  1418. return flip(m, 0)
  1419. def fliplr(m):
  1420. """
  1421. Flips the entries in each row in the left/right direction.
  1422. Columns are preserved, but appear in a different order than before.
  1423. Note:
  1424. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.
  1425. Args:
  1426. m (Tensor): Input array.
  1427. Returns:
  1428. Tensor.
  1429. Raises:
  1430. TypeError: if the input is not a tensor.
  1431. Supported Platforms:
  1432. ``GPU``
  1433. Example:
  1434. >>> import mindspore.numpy as np
  1435. >>> A = np.arange(8.0).reshape((2,2,2))
  1436. >>> output = np.fliplr(A)
  1437. >>> print(output)
  1438. [[[2. 3.]
  1439. [0. 1.]]
  1440. [[6. 7.]
  1441. [4. 5.]]]
  1442. """
  1443. return flip(m, 1)
  1444. def take_along_axis(arr, indices, axis):
  1445. """
  1446. Takes values from the input array by matching 1d index and data slices.
  1447. This iterates over matching 1d slices oriented along the specified axis in the
  1448. index and data arrays, and uses the former to look up values in the latter.
  1449. These slices can be different lengths.
  1450. Args:
  1451. arr (Tensor): Source array with shape `(Ni…, M, Nk…)`.
  1452. indices (Tensor): Indices with shape `(Ni…, J, Nk…)` to take along each 1d
  1453. slice of `arr`. This must match the dimension of `arr`, but dimensions `Ni`
  1454. and `Nj` only need to broadcast against `arr`.
  1455. axis (int): The axis to take 1d slices along. If `axis` is None, the input
  1456. array is treated as if it had first been flattened to 1d.
  1457. Returns:
  1458. Tensor, the indexed result, with shape `(Ni…, J, Nk…)`.
  1459. Raises:
  1460. ValueError: if input array and indices have different number of dimensions.
  1461. TypeError: if the input is not a Tensor.
  1462. Supported Platforms:
  1463. ``Ascend`` ``GPU`` ``CPU``
  1464. Example:
  1465. >>> import mindspore.numpy as np
  1466. >>> x = np.arange(12).reshape(3, 4)
  1467. >>> indices = np.arange(3).reshape(1, 3)
  1468. >>> output = np.take_along_axis(x, indices, 1)
  1469. >>> print(output)
  1470. [[ 0 1 2]
  1471. [ 4 5 6]
  1472. [ 8 9 10]]
  1473. """
  1474. _check_input_tensor(arr, indices)
  1475. if axis is None:
  1476. arr = ravel(arr)
  1477. axis = 0
  1478. ndim = F.rank(arr)
  1479. if ndim != F.rank(indices):
  1480. _raise_value_error('`indices` and `arr` must have the same number of dimensions')
  1481. axis = _check_axis_in_range(axis, ndim)
  1482. shape_arr = F.shape(arr)
  1483. shape_indices = F.shape(indices)
  1484. # broadcasts indices against the shape of arr except at axis
  1485. indices = _broadcast_to(indices, _tuple_slice(shape_indices, None, axis),
  1486. _tuple_slice(shape_arr, None, axis), ndim)
  1487. indices = _broadcast_to(indices, _tuple_slice(shape_arr, None, axis + 1) +
  1488. _tuple_slice(shape_indices, axis + 1, None), shape_arr, ndim)
  1489. return F.gather_d(arr, axis, indices)
  1490. def _mod(x, y):
  1491. """Computes x mod y."""
  1492. quotient = F.tensor_floordiv(x, y)
  1493. prod = F.tensor_mul(y, quotient)
  1494. return F.tensor_sub(x, prod)
  1495. def _check_indices(dims, indices, mode, allow_negative_index=True):
  1496. """Checks whether indices are out of bounds."""
  1497. shape = F.shape(indices)
  1498. dtype = F.dtype(indices)
  1499. if not allow_negative_index:
  1500. lowerbounds = F.fill(dtype, shape, 0)
  1501. else:
  1502. lowerbounds = F.fill(dtype, shape, -dims)
  1503. upperbounds = F.fill(dtype, shape, dims - 1)
  1504. out_of_lowerbounds = F.tensor_lt(indices, lowerbounds)
  1505. out_of_upperbounds = F.tensor_gt(indices, upperbounds)
  1506. if mode == 'raise':
  1507. _raise_unimplemented_error('"raise" mode is not implemented')
  1508. if mode == 'wrap':
  1509. return _mod(indices, F.fill(mstype.float32, shape, dims)).astype(dtype)
  1510. if mode != 'clip':
  1511. _raise_value_error('invalid mode. Expected "raise", "wrap", or "clip"')
  1512. zeros = F.fill(dtype, shape, 0)
  1513. clipped = F.select(out_of_lowerbounds, zeros, indices)
  1514. clipped = F.select(out_of_upperbounds, upperbounds, clipped)
  1515. return clipped
  1516. def take(a, indices, axis=None, mode='clip'):
  1517. """
  1518. Takes elements from an array along an axis.
  1519. When axis is not None, this function does the same thing as “fancy” indexing
  1520. (indexing arrays using arrays); however, it can be easier to use if you need
  1521. elements along a given axis. A call such as ``np.take(arr, indices, axis=3)`` is
  1522. equivalent to ``arr[:,:,:,indices,...]``.
  1523. Note:
  1524. Numpy argument out is not supported.
  1525. ``mode = 'raise'`` is not supported, and the default mode is 'clip' instead.
  1526. Args:
  1527. a (Tensor): Source array with shape `(Ni…, M, Nk…)`.
  1528. indices (Tensor): The indices with shape `(Nj...)` of the values to extract.
  1529. axis (int, optional): The axis over which to select values. By default,
  1530. the flattened input array is used.
  1531. mode (‘raise’, ‘wrap’, ‘clip’, optional): Specifies how out-of-bounds
  1532. indices will behave.
  1533. ‘raise’ – raise an error;
  1534. ‘wrap’ – wrap around;
  1535. ‘clip’ – clip to the range. ‘clip’ mode means that all indices that are
  1536. too large are replaced by the index that addresses the last element
  1537. along that axis. Note that this disables indexing with negative numbers.
  1538. Returns:
  1539. Tensor, the indexed result.
  1540. Raises:
  1541. ValueError: if axis is out of range.
  1542. TypeError: if the input is not a Tensor.
  1543. Supported Platforms:
  1544. ``Ascend`` ``GPU`` ``CPU``
  1545. Examples:
  1546. >>> import mindspore.numpy as np
  1547. >>> a = np.array([4, 3, 5, 7, 6, 8])
  1548. >>> indices = np.array([0, 1, 4])
  1549. >>> output = np.take(a, indices)
  1550. >>> print(output)
  1551. [4 3 6]
  1552. >>> indices = np.array([[0, 1], [2, 3]])
  1553. >>> output = np.take(a, indices)
  1554. >>> print(output)
  1555. [[4 3]
  1556. [5 7]]
  1557. """
  1558. _check_input_tensor(a, indices)
  1559. return a.take(indices, axis=axis, mode=mode)
  1560. def repeat(a, repeats, axis=None):
  1561. """
  1562. Repeats elements of an array.
  1563. Args:
  1564. a (Tensor): Input array.
  1565. repeats (int or sequence of ints): The number of repetitions for each element.
  1566. `repeats` is broadcasted to fit the shape of the given axis.
  1567. axis (int, optional): The axis along which to repeat values. By default,
  1568. use the flattened input array, and return a flat output array.
  1569. Returns:
  1570. Tensor, output array which has the same shape as `a`, except along the given
  1571. axis.
  1572. Raises:
  1573. ValueError: if axis is out of range.
  1574. TypeError: if input `a` is not a Tensor.
  1575. Supported Platforms:
  1576. ``Ascend`` ``GPU`` ``CPU``
  1577. Examples:
  1578. >>> import mindspore.numpy as np
  1579. >>> output = np.repeat(np.array(3), 4)
  1580. >>> print(output)
  1581. [3 3 3 3]
  1582. >>> x = np.array([[1,2],[3,4]])
  1583. >>> output = np.repeat(x, 2)
  1584. >>> print(output)
  1585. [1 1 2 2 3 3 4 4]
  1586. >>> output = np.repeat(x, 3, axis=1)
  1587. >>> print(output)
  1588. [[1 1 1 2 2 2]
  1589. [3 3 3 4 4 4]]
  1590. >>> output = np.repeat(x, [1, 2], axis=0)
  1591. >>> print(output)
  1592. [[1 2]
  1593. [3 4]
  1594. [3 4]]
  1595. """
  1596. a = _to_tensor(a)
  1597. return a.repeat(repeats, axis)
  1598. def rot90(a, k=1, axes=(0, 1)):
  1599. """
  1600. Rotates a tensor by 90 degrees in the plane specified by axes.
  1601. Rotation direction is from the first towards the second axis.
  1602. Args:
  1603. a (Tensor): Input tensor of two or more dimensions.
  1604. k (int): Number of times the tensor is rotated by 90 degrees. Default: 1.
  1605. axes (Union[tuple(int), list(int)]): The tensor is rotated in the plane
  1606. defined by the axes. Default: `(0, 1)`.
  1607. Axes must be different and with the shape of `(2,)`.
  1608. Returns:
  1609. Tensor.
  1610. Raises:
  1611. TypeError: if input `a` is not a Tensor or
  1612. the argument `k` is not integer or
  1613. the argument `axes` is not tuple of ints or list of ints.
  1614. ValueError: if any axis is out of range or
  1615. the length of `axes` is not `2`.
  1616. Supported Platforms:
  1617. ``GPU``
  1618. Examples:
  1619. >>> import mindspore.numpy as np
  1620. >>> a = np.arange(24).reshape((2, 3, 4))
  1621. >>> output = np.rot90(a)
  1622. >>> print(output)
  1623. [[[ 8 9 10 11]
  1624. [20 21 22 23]]
  1625. [[ 4 5 6 7]
  1626. [16 17 18 19]]
  1627. [[ 0 1 2 3]
  1628. [12 13 14 15]]]
  1629. >>> output = np.rot90(a, 3, (1, 2))
  1630. >>> print(output)
  1631. [[[ 8 4 0]
  1632. [ 9 5 1]
  1633. [10 6 2]
  1634. [11 7 3]]
  1635. [[20 16 12]
  1636. [21 17 13]
  1637. [22 18 14]
  1638. [23 19 15]]]
  1639. """
  1640. _check_input_tensor(a)
  1641. if not isinstance(k, int):
  1642. _raise_type_error("integer argument expected, but got ", k)
  1643. k = k % 4 if k >= 0 else 4 - (-k % 4)
  1644. if not isinstance(axes, (tuple, list)):
  1645. _raise_type_error("tuple(ints) or list(ints) expected, but got ", axes)
  1646. if len(axes) != 2:
  1647. _raise_value_error("len(axes) must be 2.")
  1648. axis1, axis2 = axes[0], axes[1]
  1649. axis1 = _canonicalize_axis(axis1, a.ndim)
  1650. axis2 = _canonicalize_axis(axis2, a.ndim)
  1651. if axis1 == axis2:
  1652. _raise_value_error('Axes must be different.')
  1653. if k == 0:
  1654. return a
  1655. if k == 2:
  1656. return flip(flip(a, axis1), axis2)
  1657. perm = _list_comprehensions(a.ndim)
  1658. perm[axis1], perm[axis2] = perm[axis2], perm[axis1]
  1659. if k == 1:
  1660. return flip(transpose(a, perm), axis1)
  1661. return flip(transpose(a, perm), axis2)
  1662. def select(condlist, choicelist, default=0):
  1663. """
  1664. Returns an array drawn from elements in `choicelist`, depending on conditions.
  1665. Args:
  1666. condlist (Union[int, float, bool, list, tuple, Tensor]): The list of conditions
  1667. which determine from which array in `choicelist` the output elements are
  1668. taken. When multiple conditions are satisfied, the first one encountered in
  1669. `condlist` is used.
  1670. choicelist (Union[int, float, bool, list, tuple, Tensor]): The list of arrays
  1671. from which the output elements are taken. It has to be of the same length as
  1672. `condlist`.
  1673. default (scalar, optional): The element inserted in output when all conditions
  1674. evaluate to `False`.
  1675. Returns:
  1676. Tensor, the output at position `m` is the `m-th` element of the array in
  1677. `choicelist` where the `m-th` element of the corresponding array in `condlist`
  1678. is `True`.
  1679. Raises:
  1680. ValueError: if ``len(condlist) != len(choicelist)``.
  1681. Supported Platforms:
  1682. ``Ascend`` ``GPU`` ``CPU``
  1683. Examples:
  1684. >>> import mindspore.numpy as np
  1685. >>> condlist = [[True, True, True, False, False], \
  1686. [False, False, True, False, True]]
  1687. >>> choicelist = [[0, 1, 2, 3, 4], [0, 1, 4, 9, 16]]
  1688. >>> output = np.select(condlist, choicelist)
  1689. >>> print(output)
  1690. [ 0 1 2 0 16]
  1691. """
  1692. condlist, choicelist = _to_tensor(condlist, choicelist)
  1693. shape_cond = F.shape(condlist)
  1694. shape_choice = F.shape(choicelist)
  1695. if F.rank(condlist) == 0 or F.rank(choicelist) == 0:
  1696. _raise_value_error('input cannot be scalars')
  1697. case_num = shape_cond[0]
  1698. if shape_choice[0] != case_num:
  1699. _raise_value_error('list of cases must be same length as list of conditions')
  1700. case_size_cond = _tuple_slice(shape_cond, 1, None)
  1701. case_size_choice = _tuple_slice(shape_choice, 1, None)
  1702. # performs broadcast over the cases in condlist and choicelist
  1703. case_size = _infer_out_shape(case_size_cond, case_size_choice)
  1704. shape_broadcasted = (case_num,) + case_size
  1705. ndim = len(shape_broadcasted)
  1706. shape_cond_expanded = ((case_num,) + _list_comprehensions(ndim - F.rank(condlist), 1, True) +
  1707. case_size_cond)
  1708. condlist = _broadcast_to_shape(F.reshape(condlist, shape_cond_expanded), shape_broadcasted)
  1709. shape_choice_expanded = ((case_num,) + _list_comprehensions(ndim - F.rank(choicelist), 1, True) +
  1710. case_size_choice)
  1711. choicelist = _broadcast_to_shape(F.reshape(choicelist, shape_choice_expanded), shape_broadcasted)
  1712. slice_start = _list_comprehensions(ndim - 1, 0, True)
  1713. slice_size = (1,) + case_size
  1714. dtype = F.dtype(choicelist)
  1715. if isinstance(default, Tensor):
  1716. default_slice = default.astype(F.dtype(choicelist)).reshape(slice_size)
  1717. else:
  1718. default_slice = F.fill(F.dtype(choicelist), slice_size, default)
  1719. for i in range(case_num - 1, -1, -1):
  1720. cond_slice = F.tensor_slice(condlist.astype(mstype.float32), (i,) + slice_start, slice_size)
  1721. choice_slice = F.tensor_slice(choicelist, (i,) + slice_start, slice_size)
  1722. default_slice = F.select(cond_slice.astype(mstype.bool_), choice_slice, default_slice)
  1723. return F.reshape(default_slice, (case_size)).astype(dtype)
  1724. @constexpr
  1725. def _get_grid(shape):
  1726. """Returns a grid representing all the indices for an array with the given shape."""
  1727. grids = []
  1728. ndim = len(shape)
  1729. for i in range(ndim):
  1730. dim_grid = _iota(mstype.int32, shape[i])
  1731. dim_shape = _expanded_shape(ndim, shape[i], i)
  1732. dim_grid = _broadcast_to_shape(dim_grid.reshape(dim_shape), shape)
  1733. grids.append(dim_grid)
  1734. return stack(grids, -1)
  1735. def choose(a, choices, mode='clip'):
  1736. """
  1737. Construct an array from an index array and a list of arrays to choose from.
  1738. Given an “index” array `a` of integers and a sequence of n arrays (choices),
  1739. `a` and each choice array are first broadcast, as necessary, to arrays of a
  1740. common shape; calling these `Ba` and `Bchoices[i], i = 0,…,n-1` we have that,
  1741. necessarily, ``Ba.shape == Bchoices[i].shape`` for each `i`. Then, a new array
  1742. with ``shape Ba.shape`` is created as follows:
  1743. - if ``mode='raise'`` (the default), then, first of all, each element of `a`
  1744. (and thus `Ba`) must be in the range `[0, n-1]`; now, suppose that `i`
  1745. (in that range) is the value at the `(j0, j1, ..., jm)` position in
  1746. `Ba` - then the value at the same position in the new array is the
  1747. value in ``Bchoices[i]`` at that same position;
  1748. - if ``mode='wrap'``, values in `a` (and thus `Ba`) may be any (signed)
  1749. integer; modular arithmetic is used to map integers outside the
  1750. range ``[0, n-1]`` back into that range; and then the new array is
  1751. constructed as above;
  1752. - if ``mode='clip'``, values in `a` (and thus `Ba`) may be any (signed) integer;
  1753. negative integers are mapped to 0; values greater than `n-1` are mapped to
  1754. `n-1`; and then the new array is constructed as above.
  1755. Note:
  1756. Numpy argument `out` is not supported.
  1757. ``mode = 'raise'`` is not supported, and the default mode is 'clip' instead.
  1758. Args:
  1759. a (int array): This array must contain integers in ``[0, n-1]``, where `n` is
  1760. the number of choices, unless ``mode=wrap`` or ``mode=clip``, in which
  1761. cases any integers are permissible.
  1762. choices (sequence of arrays): Choice arrays. `a` and all of the `choices` must
  1763. be broadcastable to the same shape. If `choices` is itself an array, then
  1764. its outermost dimension (i.e., the one corresponding to ``choices.shape[0]``)
  1765. is taken as defining the “sequence”.
  1766. mode (‘raise’, ‘wrap’, ‘clip’, optional): Specifies how indices outside
  1767. ``[0, n-1]`` will be treated:
  1768. ‘raise’ – raise an error;
  1769. ‘wrap’ – wrap around;
  1770. ‘clip’ – clip to the range. ‘clip’ mode means that all indices that are
  1771. too large are replaced by the index that addresses the last element
  1772. along that axis. Note that this disables indexing with negative numbers.
  1773. Returns:
  1774. Tensor, the merged result.
  1775. Raises:
  1776. ValueError: if `a` and any of the `choices` cannot be broadcast.
  1777. Supported Platforms:
  1778. ``Ascend`` ``GPU`` ``CPU``
  1779. Examples:
  1780. >>> import mindspore.numpy as np
  1781. >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]
  1782. >>> print(np.choose([2, 3, 1, 0], choices))
  1783. [20 31 12 3]
  1784. >>> print(np.choose([2, 4, 1, 0], choices, mode='clip'))
  1785. [20 31 12 3]
  1786. >>> print(np.choose([2, 4, 1, 0], choices, mode='wrap'))
  1787. [20 1 12 3]
  1788. >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
  1789. >>> choices = [-10, 10]
  1790. >>> print(np.choose(a, choices))
  1791. [[ 10 -10 10]
  1792. [-10 10 -10]
  1793. [ 10 -10 10]]
  1794. """
  1795. a = _to_tensor(a)
  1796. if not _check_is_int(F.dtype(a)):
  1797. _raise_value_error('`a` should be an int array')
  1798. if isinstance(choices, (tuple, list)):
  1799. # broadcasts choices to the same shape if choices is a sequence
  1800. choices = _to_tensor(*choices)
  1801. shapes = ()
  1802. for choice in choices:
  1803. shapes += (F.shape(choice),)
  1804. shape_choice = _infer_out_shape(F.shape(a), *shapes)
  1805. tmp = []
  1806. for choice in choices:
  1807. tmp.append(broadcast_to(choice, shape_choice))
  1808. choices = stack(tmp)
  1809. else:
  1810. choices = _to_tensor(choices)
  1811. shape_choice = _infer_out_shape(F.shape(a), F.shape(choices)[1:])
  1812. choices = F.reshape(choices, choices.shape[:1] + _add_unit_axes(choices.shape[1:], len(shape_choice)))
  1813. choices = broadcast_to(choices, (F.shape(choices)[0],) + shape_choice)
  1814. if F.rank(a) == 0 or F.rank(choices) == 0:
  1815. _raise_value_error('input cannot be scalars')
  1816. a = broadcast_to(a, shape_choice)
  1817. a = _check_indices(F.shape(choices)[0], a, mode, allow_negative_index=False)
  1818. grid = _get_grid(F.shape(a))
  1819. indices = concatenate((a.reshape(F.shape(a) + (1,)), grid), -1)
  1820. return F.gather_nd(choices, indices)
  1821. def size(a, axis=None):
  1822. """
  1823. Returns the number of elements along a given axis.
  1824. Args:
  1825. a (Union[int, float, bool, list, tuple, Tensor]): Input data.
  1826. axis (int): Axis along which the elements are counted. Default: None.
  1827. If None, give the total number of elements.
  1828. Returns:
  1829. Number of elements along the specified axis.
  1830. Supported Platforms:
  1831. ``Ascend`` ``GPU`` ``CPU``
  1832. Raises:
  1833. TypeError: If input is not array_like or `axis` is not int.
  1834. ValueError: If any axis is out of range or duplicate axes exist.
  1835. Examples:
  1836. >>> import mindspore.numpy as np
  1837. >>> x = np.arange(10).reshape(2, 5).astype('float32')
  1838. >>> print(np.size(x))
  1839. 10
  1840. >>> print(np.size(x, axis=1))
  1841. 5
  1842. """
  1843. a = _to_tensor(a)
  1844. if axis is None:
  1845. return a.size
  1846. if not isinstance(axis, int):
  1847. _raise_type_error("axis argument should be integer.")
  1848. axis = _canonicalize_axis(axis, a.ndim)
  1849. return a.shape[axis]
  1850. def array_str(a):
  1851. """
  1852. Returns a string representation of the data in an array.
  1853. The data in the array is returned as a single string.
  1854. This function is similar to array_repr, the difference being that array_repr also
  1855. returns information on the kind of array and its data type.
  1856. Note:
  1857. Numpy argument `max_line_width`, `precision` and `suppress_small` are not supported.
  1858. Graph mode dose not support the function.
  1859. Args:
  1860. a (Tensor): Input data.
  1861. Returns:
  1862. String.
  1863. Supported Platforms:
  1864. ``Ascend`` ``GPU`` ``CPU``
  1865. Raises:
  1866. TypeError: If input is not tensor.
  1867. Examples:
  1868. >>> import mindspore.numpy as np
  1869. >>> x = np.arange(5)
  1870. >>> np.array_str(x)
  1871. '[0 1 2 3 4]'
  1872. """
  1873. if not isinstance(a, Tensor):
  1874. _raise_type_error("Expect input to be tensor.")
  1875. return a.__str__()
  1876. def apply_along_axis(func1d, axis, arr, *args, **kwargs):
  1877. """
  1878. Applies a function to 1-D slices along the given axis.
  1879. Executes ``func1d(a, *args, **kwargs)`` where `func1d` operates on 1-D arrays and `a` is a
  1880. 1-D slice of arr along axis.
  1881. Args:
  1882. func1d (function): Maps `(M,) -> (Nj…)`. This function should accept 1-D arrays. It is
  1883. applied to 1-D slices of arr along the specified axis.
  1884. axis (int): Axis along which arr is sliced.
  1885. arr (Tensor): Input array with shape `(Ni…, M, Nk…)`.
  1886. args (any): Additional arguments to `func1d`.
  1887. kwargs (any): Additional named arguments to `func1d`.
  1888. Returns:
  1889. Tensor with shape `(Ni…, Nj…, Nk…)`, the output array. Its shape is identical to the
  1890. shape of `arr`, except along the `axis` dimension. This axis is removed, and replaced
  1891. with new dimensions equal to the shape of the return value of `func1d`. So if `func1d`
  1892. returns a scalar, the output will have one fewer dimensions than `arr`.
  1893. Supported Platforms:
  1894. ``Ascend`` ``GPU`` ``CPU``
  1895. Raises:
  1896. ValueError: if axis is out of the range.
  1897. Examples:
  1898. >>> import mindspore.numpy as np
  1899. >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
  1900. >>> print(np.apply_along_axis(np.diag, -1, b))
  1901. [[[1 0 0]
  1902. [0 2 0]
  1903. [0 0 3]]
  1904. [[4 0 0]
  1905. [0 5 0]
  1906. [0 0 6]]
  1907. [[7 0 0]
  1908. [0 8 0]
  1909. [0 0 9]]]
  1910. """
  1911. ndim = F.rank(arr)
  1912. shape = F.shape(arr)
  1913. axis = _check_axis_in_range(axis, ndim)
  1914. arr = moveaxis(arr, axis, -1)
  1915. arr = F.reshape(arr, (-1, F.shape(arr)[-1]))
  1916. slices = []
  1917. for i in range(F.shape(arr)[0]):
  1918. slices.append(func1d(arr[i], *args, **kwargs))
  1919. stacked_slices = stack(slices)
  1920. shape_stacked = (_tuple_slice(shape, None, axis) + _tuple_slice(shape, axis + 1, None) +
  1921. _tuple_slice(F.shape(stacked_slices), 1, None))
  1922. res = F.reshape(stacked_slices, shape_stacked)
  1923. # moves the dimensions returned by `func1d` back to `axis`
  1924. ndim_func = F.rank(res) - ndim + 1
  1925. if ndim_func >= 1:
  1926. res = moveaxis(res, F.make_range(ndim - 1, F.rank(res)),
  1927. F.make_range(axis, axis + ndim_func))
  1928. return res
  1929. def _stack_arrays(arrs):
  1930. """Stacks a sequence of Tensor"""
  1931. if isinstance(arrs, (tuple, list)):
  1932. tensor_list = []
  1933. for arr in arrs:
  1934. tensor_list.append(_to_tensor(arr))
  1935. return stack(tensor_list)
  1936. return atleast_1d(_to_tensor(arrs))
  1937. def piecewise(x, condlist, funclist, *args, **kw):
  1938. """
  1939. Evaluates a piecewise-defined function.
  1940. Given a set of conditions and corresponding functions, evaluate each function on the input
  1941. data wherever its condition is true.
  1942. Args:
  1943. x (Union[int, float, bool, list, tuple, Tensor]): The input domain.
  1944. condlist (Union[bool, list of bool Tensor]): Each boolean array corresponds to a
  1945. function in `funclist`. Wherever `condlist[i]` is True, `funclist[i](x)` is used as
  1946. the output value. Each boolean array in `condlist` selects a piece of `x`, and
  1947. should therefore be of the same shape as `x`. The length of `condlist` must
  1948. correspond to that of `funclist`. If one extra function is given, i.e. if
  1949. ``len(funclist) == len(condlist) + 1``, then that extra function is the default
  1950. value, used wherever all conditions are false.
  1951. funclist (Union[list of callables, list of scalars]): Each function is evaluated over
  1952. `x` wherever its corresponding condition is True. It should take a 1d array as input
  1953. and give an 1d array or a scalar value as output. If, instead of a callable, a scalar
  1954. is provided then a constant function ``(lambda x: scalar)`` is assumed.
  1955. args (any): Any further arguments given to `piecewise` are passed to the functions upon
  1956. execution, i.e., if called ``piecewise(..., ..., 1, 'a')``, then each function is
  1957. called as ``f(x, 1, 'a')``.
  1958. kw (any): Keyword arguments used in calling `piecewise` are passed to the functions upon
  1959. execution, i.e., if called ``piecewise(..., ..., alpha=1)``, then each function is
  1960. called as ``f(x, alpha=1)``.
  1961. Returns:
  1962. Tensor, the output is the same shape and type as `x` and is found by calling the
  1963. functions in `funclist` on the appropriate portions of `x`, as defined by the boolean
  1964. arrays in `condlist`. Portions not covered by any condition have a default value of 0.
  1965. Supported Platforms:
  1966. ``Ascend`` ``GPU`` ``CPU``
  1967. Raises:
  1968. ValueError: if length of `funclist` is not in ``(len(condlist), len(condlist) + 1)``
  1969. Examples:
  1970. >>> import mindspore.numpy as np
  1971. >>> x = np.linspace(-2.5, 2.5, 6)
  1972. >>> print(np.piecewise(x, [x < 0, x >= 0], [-1, 1]))
  1973. [-1 -1 -1 1 1 1]
  1974. """
  1975. x = _to_tensor(x)
  1976. choicelist = funclist
  1977. if isinstance(funclist, (tuple, list)):
  1978. if _callable(x, funclist[0]):
  1979. choicelist = []
  1980. for func in funclist:
  1981. choicelist.append(func(x, *args, **kw))
  1982. condlist = _stack_arrays(condlist)
  1983. choicelist = _stack_arrays(choicelist)
  1984. default = 0
  1985. n1 = len(condlist)
  1986. n2 = len(funclist)
  1987. if n1 + 1 == n2:
  1988. default = choicelist[-1]
  1989. choicelist = choicelist[:-1]
  1990. elif n1 != n2:
  1991. _raise_value_error('the number of choices should be either equal to conditions or ', n1 + 1)
  1992. return select(condlist, choicelist, default=default)
  1993. def unravel_index(indices, shape, order='C'):
  1994. """
  1995. Converts a flat index or array of flat indices into a tuple of coordinate arrays.
  1996. Note:
  1997. Out-of-bound indices are clipped by the boundaries of `shape` instead of raising
  1998. an error.
  1999. Args:
  2000. indices (Union[int, float, bool, list, tuple, Tensor]): An integer array whose elements
  2001. are indices into the flattened version of an array of dimensions shape.
  2002. shape (tuple of ints): The shape of the array to use for unraveling indices.
  2003. order (Union['C', 'F'], optional): Determines whether the indices should be viewed as
  2004. indexing in row-major (C-style) or column-major (Fortran-style) order.
  2005. Returns:
  2006. Tensor, each array in the tuple has the same shape as the indices array.
  2007. Supported Platforms:
  2008. ``Ascend`` ``GPU`` ``CPU``
  2009. Raises:
  2010. ValueError: if `order` is not 'C' or 'F'.
  2011. Examples:
  2012. >>> import mindspore.numpy as np
  2013. >>> print(np.unravel_index([22, 41, 37], (7,6)))
  2014. (Tensor(shape=[3], dtype=Int32, value= [3, 6, 6]),
  2015. Tensor(shape=[3], dtype=Int32, value= [4, 5, 1]))
  2016. >>> print(np.unravel_index([31, 41, 13], (7,6), order='F'))
  2017. (Tensor(shape=[3], dtype=Int32, value= [3, 6, 6]),
  2018. Tensor(shape=[3], dtype=Int32, value= [4, 5, 1]))
  2019. """
  2020. indices = _to_tensor(indices)
  2021. if order not in ('C', 'F'):
  2022. _raise_value_error('invalid order. Expected "C" or "F"')
  2023. if isinstance(shape, int):
  2024. shape = (shape,)
  2025. ndim = F.rank(indices)
  2026. if order == 'F':
  2027. sizes = _cumprod(shape)
  2028. else:
  2029. sizes = _cumprod(shape[::-1])
  2030. sizes = _to_tensor(sizes[::-1] + (1,))
  2031. sizes = F.reshape(sizes, (-1,) + _list_comprehensions(ndim, 1, True))
  2032. total_size = sizes[0]
  2033. indices = where(indices > total_size - 1, total_size - 1, indices)
  2034. if _get_device() == 'GPU':
  2035. dtype = F.dtype(total_size)
  2036. lowerbounds = (-(total_size.astype(mstype.float32))).astype(dtype)
  2037. else:
  2038. lowerbounds = -total_size
  2039. indices = where(indices < lowerbounds, lowerbounds, indices)
  2040. res = _mod(indices, sizes[:-1])//sizes[1:]
  2041. num = len(res)
  2042. if ndim == 0 and num == 1:
  2043. return res.ravel()
  2044. if order == 'F':
  2045. r = range(num - 1, -1, -1)
  2046. else:
  2047. r = range(num)
  2048. subs = ()
  2049. for i in r:
  2050. subs += (res[i],)
  2051. return subs
  2052. def apply_over_axes(func, a, axes):
  2053. """
  2054. Applies a function repeatedly over multiple axes.
  2055. `func` is called as `res = func(a, axis)`, where `axis` is the first element of `axes`.
  2056. The result `res` of the function call must have either the same dimensions as `a` or
  2057. one less dimension. If `res` has one less dimension than `a`, a dimension is inserted before `axis`.
  2058. The call to `func` is then repeated for each axis in `axes`, with `res` as the first argument.
  2059. Args:
  2060. func (function): This function must take two arguments, `func(a, axis)`.
  2061. a (Union[int, float, bool, list, tuple, Tensor]): Input tensor.
  2062. axes (Union[int, list, tuple]): Axes over which `func` is applied; the elements must be integers.
  2063. Returns:
  2064. Tensor. The number of dimensions is the same as `a`, but the shape can be different.
  2065. This depends on whether `func` changes the shape of its output with respect to its input.
  2066. Raises:
  2067. TypeError: If input `a` is not array_like or `axes` is not int or sequence of ints.
  2068. ValueError: If any axis is out of range or duplicate axes exist.
  2069. Supported Platforms:
  2070. ``Ascend`` ``GPU`` ``CPU``
  2071. Examples:
  2072. >>> import mindspore.numpy as np
  2073. >>> x = np.arange(10).reshape(2, 5).astype('float32')
  2074. >>> print(x)
  2075. [[0. 1. 2. 3. 4.]
  2076. [5. 6. 7. 8. 9.]]
  2077. >>> print(np.apply_over_axes(np.sum, x, axes=0))
  2078. [[ 5. 7. 9. 11. 13.]]
  2079. """
  2080. a = _to_tensor(a)
  2081. if isinstance(axes, int):
  2082. axes = (axes,)
  2083. res = a
  2084. for axis in axes:
  2085. res = func(res, axis=axis)
  2086. res = F.expand_dims(res, axis) if res.ndim != a.ndim else res
  2087. if res.ndim != a.ndim:
  2088. _raise_value_error("function is not returning a tensor of the correct shape")
  2089. return res