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

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