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_creations.py 63 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801
  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 numpy as onp
  17. from ..common import Tensor
  18. from ..common import dtype as mstype
  19. from ..ops import functional as F
  20. from ..ops.primitive import constexpr
  21. from ..nn.layer.basic import tril as nn_tril
  22. from ..nn.layer.basic import triu as nn_triu
  23. from .._c_expression import Tensor as Tensor_
  24. from .utils import _check_input_for_asarray, _deep_list, _deep_tensor_to_nparray, \
  25. _broadcast_to_shape, _check_input_tensor, _convert_64_to_32, _get_dtype_from_scalar, \
  26. _expand
  27. from .utils_const import _raise_value_error, _empty, _check_axis_valid, _max, _min, \
  28. _check_same_type, _is_shape_empty, _check_shape, _check_dtype, _tile_size, _abs, \
  29. _raise_type_error, _expanded_shape, _check_is_float, _iota, _type_convert, \
  30. _canonicalize_axis, _list_comprehensions, _ceil, _tuple_getitem, _tuple_slice
  31. from .array_ops import transpose, ravel, concatenate, broadcast_arrays, reshape, broadcast_to
  32. from .dtypes import nan
  33. # According to official numpy reference, the dimension of a numpy array must be less
  34. # than 32
  35. MAX_NUMPY_DIMS = 32
  36. # All types that can be accepted as "array_like" parameters in graph mode.
  37. ARRAY_TYPES = (int, float, bool, list, tuple, Tensor)
  38. def array(obj, dtype=None, copy=True, ndmin=0):
  39. """
  40. Creates a tensor.
  41. This function creates tensors from an array-like object.
  42. Args:
  43. obj (Union[int, float, bool, list, tuple]): Input data, in any form that
  44. can be converted to a `Tensor`. This includes Tensor, list, tuple and numbers.
  45. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, can
  46. be in format of np.int32, or \'int32\'. If dtype is :class:`None`, the data type
  47. of the new tensor will be inferred from obj. Default is :class:`None`.
  48. copy (bool): If `True`, then the object is copied. Otherwise, a copy will
  49. only be made if necessary. Default: `True`.
  50. ndmin (int): Specifies the minimum number of dimensions that the resulting
  51. tensor should have. Ones will be pre-pended to the shape as needed to
  52. meet this requirement. Default: 0
  53. Returns:
  54. Tensor, generated tensor with the specified dtype.
  55. Raises:
  56. TypeError: If input arguments have types not specified above.
  57. ValueError: If input `obj` has different sizes at different dimensions.
  58. Supported Platforms:
  59. ``Ascend`` ``GPU`` ``CPU``
  60. Examples:
  61. >>> import mindspore.numpy as np
  62. >>> print(np.array([1,2,3]))
  63. [1 2 3]
  64. """
  65. res = asarray(obj, dtype)
  66. if ndmin > res.ndim:
  67. res = _expand(res, ndmin)
  68. if copy:
  69. res = copy_(res)
  70. elif dtype is not None and dtype != res.dtype:
  71. res = res.astype(dtype)
  72. return res
  73. @constexpr
  74. def asarray_const(a, dtype=None):
  75. """Converts the input to tensor. Note here `a` cannot be tensor itself."""
  76. _check_input_for_asarray(a)
  77. if dtype is not None:
  78. dtype = _check_dtype(dtype)
  79. if isinstance(a, (float, int, bool)) and dtype is None:
  80. dtype = _get_dtype_from_scalar(a)
  81. if isinstance(a, (list, tuple)):
  82. # Convert all tuple/nested tuples to lists
  83. a = _deep_list(a)
  84. # Convert all tensor sub-elements to numpy arrays
  85. a = _deep_tensor_to_nparray(a)
  86. a = onp.asarray(a)
  87. if a.dtype is onp.dtype('object'):
  88. raise ValueError('Input array must have the same size across all dimensions.')
  89. # If dtype is not specified, we keep consistent with numpy decision
  90. # only exceptions are: we use int/float32
  91. if dtype is None:
  92. dtype = mstype.pytype_to_dtype(a.dtype)
  93. if dtype == mstype.float64:
  94. dtype = mstype.float32
  95. elif dtype == mstype.int64:
  96. dtype = mstype.int32
  97. if isinstance(a, onp.ndarray) and dtype is None:
  98. if a.dtype is onp.dtype('object'):
  99. raise TypeError(f"For Tensor conversion, the input_data is {a} that contains unsupported element.")
  100. dtype = mstype.pytype_to_dtype(a.dtype)
  101. a = Tensor.from_numpy(a)
  102. return Tensor(a, dtype=dtype)
  103. def asarray(a, dtype=None):
  104. """
  105. Converts the input to tensor.
  106. This function converts tensors from an array-like object.
  107. Args:
  108. a (Union[int, float, bool, list, tuple, Tensor]): Input data, in any form that can
  109. be converted to a `Tensor`. This includes Tensor, list, tuple and numbers.
  110. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, can
  111. be in format of np.int32, or \'int32\'. If dtype is :class:`None`, the data type
  112. of the new tensor will be inferred from obj. Default is :class:`None`.
  113. Returns:
  114. Tensor, generated tensor with the specified dtype.
  115. Raises:
  116. TypeError: If input arguments have types not specified above.
  117. ValueError: If input `a` has different sizes at different dimensions.
  118. Supported Platforms:
  119. ``Ascend`` ``GPU`` ``CPU``
  120. Examples:
  121. >>> import mindspore.numpy as np
  122. >>> print(np.asarray([1,2,3]))
  123. [1 2 3]
  124. """
  125. if isinstance(a, Tensor):
  126. if dtype is None or dtype == a.dtype:
  127. return a
  128. return a.astype(dtype)
  129. return asarray_const(a, dtype)
  130. @constexpr
  131. def asfarray_const(a, dtype=mstype.float32):
  132. """Converts the input to tensor. Note here `a` cannot be tensor itself."""
  133. _check_input_for_asarray(a)
  134. if isinstance(a, (list, tuple)):
  135. # Convert all tuple/nested tuples to lists
  136. a = _deep_list(a)
  137. # Convert all tensor sub-elements to numpy arrays
  138. a = _deep_tensor_to_nparray(a)
  139. a = onp.asarray(a)
  140. if a.dtype is onp.dtype('object'):
  141. raise ValueError(f"For Tensor conversion, the input_data is {a} that contains unsupported element.")
  142. a = Tensor.from_numpy(a)
  143. return Tensor(a, dtype)
  144. def asfarray(a, dtype=mstype.float32):
  145. """
  146. Similar to asarray, converts the input to a float tensor.
  147. If non-float dtype is defined, this function will return a float32 tensor instead.
  148. Args:
  149. a (Union[int, float, bool, list, tuple, Tensor]): Input data, in any form that can
  150. be converted to a `Tensor`. This includes Tensor, list, tuple and numbers.
  151. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, can
  152. be in format of np.int32, or \'int32\'. If dtype is :class:`None`, the data type
  153. of the new tensor will be inferred from `a`. Default is :class:`mindspore.float32`.
  154. Returns:
  155. Tensor, generated tensor with the specified float dtype.
  156. Raises:
  157. TypeError: If input arguments have types not specified above.
  158. ValueError: If input `a` has different sizes at different dimensions.
  159. Supported Platforms:
  160. ``Ascend`` ``GPU`` ``CPU``
  161. Examples:
  162. >>> import mindspore.numpy as np
  163. >>> print(np.asfarray([1,2,3]))
  164. [1. 2. 3.]
  165. """
  166. if dtype is None:
  167. return asarray(a)
  168. dtype = _check_dtype(dtype)
  169. # pylint: disable=consider-using-in
  170. if dtype != mstype.float16 and dtype != mstype.float32 and dtype != mstype.float64:
  171. dtype = mstype.float32
  172. if isinstance(a, Tensor):
  173. return a.astype(dtype)
  174. return asfarray_const(a, dtype)
  175. def copy_(a):
  176. """
  177. Returns a tensor copy of the given object.
  178. Args:
  179. a (Union[int, float, bool, list, tuple, Tensor]): Input data, in any form that can
  180. be converted to a `Tensor`. This includes Tensor, list, tuple and numbers.
  181. Returns:
  182. Tensor, has the same data as `a`.
  183. Raises:
  184. TypeError: If input `a` has type not specified above.
  185. ValueError: If input `a` has different sizes at different dimensions.
  186. Supported Platforms:
  187. ``Ascend`` ``GPU`` ``CPU``
  188. Examples:
  189. >>> import mindspore.numpy as np
  190. >>> x = np.ones((2,2))
  191. >>> print(np.copy(x))
  192. [[1. 1.]
  193. [1. 1.]]
  194. """
  195. if not isinstance(a, Tensor):
  196. a = asarray_const(a)
  197. # The current implementation registers a new memory location for copied tensor by
  198. # doing some reduandent operations.
  199. origin_dtype = a.dtype
  200. if origin_dtype == mstype.bool_:
  201. return F.logical_not(F.logical_not(a))
  202. if origin_dtype != mstype.float64:
  203. a = a.astype("float32")
  204. a = a / ones_like(a)
  205. a = a.astype(origin_dtype)
  206. return a
  207. def ones(shape, dtype=mstype.float32):
  208. """
  209. Returns a new tensor of given shape and type, filled with ones.
  210. Args:
  211. shape (Union[int, tuple, list]): the shape of the new tensor.
  212. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
  213. Default is :class:`mstype.float32`.
  214. Returns:
  215. Tensor, with the designated `shape` and `dtype`, filled with ones.
  216. Raises:
  217. TypeError: If input arguments have types not specified above.
  218. ValueError: If `shape` entries have values :math:`< 0`.
  219. Supported Platforms:
  220. ``Ascend`` ``GPU`` ``CPU``
  221. Examples:
  222. >>> import mindspore.numpy as np
  223. >>> print(np.ones((2,2)))
  224. [[1. 1.]
  225. [1. 1.]]
  226. """
  227. shape = _check_shape(shape)
  228. dtype = _check_dtype(dtype)
  229. if _is_shape_empty(shape):
  230. return full(shape, 1.0, dtype)
  231. output = F.fill(dtype, shape, 1)
  232. return output
  233. def zeros(shape, dtype=mstype.float32):
  234. """
  235. Returns a new tensor of given shape and type, filled with zeros.
  236. Args:
  237. shape (Union[int, tuple, list]): the shape of the new tensor.
  238. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
  239. Default is :class:`mstype.float32`.
  240. Returns:
  241. Tensor, with the designated `shape` and `dtype`, filled with zeros.
  242. Raises:
  243. TypeError: If input arguments have types not specified above.
  244. ValueError: If `shape` entries have values :math:`< 0`.
  245. Supported Platforms:
  246. ``Ascend`` ``GPU`` ``CPU``
  247. Examples:
  248. >>> import mindspore.numpy as np
  249. >>> print(np.zeros((2,2)))
  250. [[0. 0.]
  251. [0. 0.]]
  252. """
  253. shape = _check_shape(shape)
  254. dtype = _check_dtype(dtype)
  255. if _is_shape_empty(shape):
  256. return full(shape, 0.0, dtype)
  257. output = F.fill(dtype, shape, 0)
  258. return output
  259. def full(shape, fill_value, dtype=None):
  260. """
  261. Returns a new tensor of given shape and type, filled with `fill_value`.
  262. Args:
  263. shape (Union[int, tuple(int), list(int)]): Shape of the new tensor, e.g.,
  264. :math:`(2, 3)` or :math:`2`.
  265. fill_value (Union[int, float, bool, list, tuple]): Scalar or array_like
  266. fill value.
  267. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype,
  268. if `dtype` is :class:`None`, the data type of the new tensor will be inferred from
  269. `fill_value`. Default is :class:`None`.
  270. Returns:
  271. Tensor, with the designated shape and dtype, filled with `fill_value`.
  272. Raises:
  273. TypeError: If input arguments have types not specified above.
  274. ValueError: If `shape` has entries < 0.
  275. Supported Platforms:
  276. ``Ascend`` ``GPU`` ``CPU``
  277. Examples:
  278. >>> import mindspore.numpy as np
  279. >>> print(np.full((2,2), True))
  280. [[True True]
  281. [True True]]
  282. """
  283. shape = _check_shape(shape)
  284. if not isinstance(fill_value, ARRAY_TYPES):
  285. _raise_type_error("fill value should be int, float, bool, list, tuple, Tensor, but got", fill_value)
  286. if dtype is not None:
  287. dtype = _check_dtype(dtype)
  288. else:
  289. if isinstance(fill_value, (int, float, bool)):
  290. dtype = _get_dtype_from_scalar(fill_value)
  291. if isinstance(fill_value, Tensor):
  292. dtype = fill_value.dtype
  293. if not _is_shape_empty(shape):
  294. if isinstance(fill_value, (int, float, bool)):
  295. return F.fill(dtype, shape, fill_value)
  296. if isinstance(fill_value, (list, tuple)):
  297. fill_value = asarray_const(fill_value)
  298. return broadcast_to(fill_value, shape)
  299. # if shape contains zero, use c.Tensor()
  300. return _convert_64_to_32(empty_compile(dtype, shape))
  301. def arange(start, stop=None, step=None, dtype=None):
  302. """
  303. Returns evenly spaced values within a given interval.
  304. Args:
  305. start(Union[int, float]): Start of interval. The interval includes this value.
  306. When `stop` is provided as a position argument, `start` must be given, when `stop`
  307. is a normal argument, `start` can be optional, and default is 0.
  308. Please see additional examples below.
  309. stop(Union[int, float], optional): End of interval. The interval does not
  310. include this value, except in some cases where `step` is not an integer
  311. and floating point round-off affects the length of out.
  312. step(Union[int, float], optional): Spacing between values. For any output
  313. `out`, this is the distance between two adjacent values, :math:`out[i+1] - out[i]`.
  314. The default step size is 1. If `step` is specified as a position argument,
  315. `start` must also be given.
  316. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
  317. If dtype is None, the data type of the new tensor will be inferred from start,
  318. stop and step. Default is None.
  319. Returns:
  320. Tensor with evenly spaced values.
  321. Raises:
  322. TypeError(PyNative Mode) or RuntimeError(Graph Mode): If input arguments
  323. have types not specified above, or arguments are not given in the correct
  324. orders specified above.
  325. Supported Platforms:
  326. ``Ascend`` ``GPU`` ``CPU``
  327. Examples:
  328. >>> import mindspore.numpy as np
  329. >>> print(np.arange(0, 5, 1))
  330. [0 1 2 3 4]
  331. >>> print(np.arange(3))
  332. [0 1 2]
  333. >>> print(np.arange(start=0, stop=3))
  334. [0 1 2]
  335. >>> print(np.arange(0, stop=3, step=0.5))
  336. [0. 0.5 1. 1.5 2. 2.5]
  337. >>> print(np.arange(stop=3)) # This will lead to TypeError
  338. """
  339. # This implementation was inspired by jax.numpy.arange
  340. # infer the dtype
  341. if dtype is None:
  342. dtype = _get_dtype_from_scalar(start, stop, step)
  343. if stop is None and step is None: # (start, stop, step) -> (0, start, 1)
  344. num = _ceil(start)
  345. out = _iota(mstype.float32, num)
  346. elif step is None: # (start, stop, step) -> (start, stop, 1)
  347. num = _ceil(stop - start)
  348. out = _iota(mstype.float32, num) + start
  349. elif stop is None: # (start, stop, step) -> (0, start, step)
  350. num = _ceil(start / step)
  351. out = _iota(mstype.float32, num) * step
  352. else:
  353. num = _ceil((stop - start) / step)
  354. out = _iota(mstype.float32, num) * step + start
  355. return out.astype(dtype)
  356. def _type_checking_for_xspace(start, stop, num, endpoint, dtype, axis):
  357. """utility parameter checking function for linspace, logspace, geomspace."""
  358. if not isinstance(start, ARRAY_TYPES):
  359. _raise_type_error("start should be int, float, bool, list, tuple, Tensor, but got", start)
  360. if not isinstance(stop, ARRAY_TYPES):
  361. _raise_type_error("end should be int, float, bool, list, tuple, Tensor, but got", stop)
  362. if not isinstance(start, Tensor):
  363. start = _type_convert(Tensor, start).astype(mstype.float32)
  364. if not isinstance(stop, Tensor):
  365. stop = _type_convert(Tensor, stop).astype(mstype.float32)
  366. if not isinstance(num, int):
  367. _raise_type_error("num should be an integer, but got ", num)
  368. if not isinstance(endpoint, bool):
  369. _raise_type_error("endpoint should be an boolean, but got ", endpoint)
  370. if dtype is not None:
  371. dtype = _check_dtype(dtype)
  372. else:
  373. dtype = mstype.float32
  374. axis = _canonicalize_axis(axis, start.ndim+1)
  375. return start, stop, num, endpoint, dtype, axis
  376. def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
  377. """
  378. Returns evenly spaced values within a given interval.
  379. Args:
  380. start (Union[int, list(int), tuple(int), tensor]): The starting value of the sequence.
  381. stop (Union[int, list(int), tuple(int), tensor]): The end value of the sequence,
  382. unless `endpoint` is set to False. In that case, the sequence consists
  383. of all but the last of `num + 1` evenly spaced samples, so that `stop`
  384. is excluded. Note that the step size changes when `endpoint` is False.
  385. num (int, optional): Number of samples to generate. Default is 50.
  386. endpoint (bool, optional): If True, `stop` is the last sample. Otherwise, it is
  387. not included. Default is True.
  388. retstep (bool, optional): If True, return (`samples`, `step`), where `step` is
  389. the spacing between samples.
  390. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype,
  391. If `dtype` is None, infer the data type from other input arguments. Default is None.
  392. axis (int, optional): The axis in the result to store the samples. Relevant
  393. only if start or stop are array-like. By default :math:`(0)`, the samples will
  394. be along a new axis inserted at the beginning. Use :math:`-1` to get an axis at the end.
  395. Default is :math:`0`.
  396. Returns:
  397. Tensor, with `num` equally spaced samples in the closed interval
  398. :math:`[start, stop]` or the half-open interval :math:`[start, stop)`
  399. (depending on whether `endpoint` is True or False).
  400. Step, the size of spacing between samples, only returned if `retstep` is True.
  401. Raises:
  402. TypeError: If input arguments have types not specified above.
  403. Supported Platforms:
  404. ``Ascend`` ``GPU`` ``CPU``
  405. Examples:
  406. >>> import mindspore.numpy as np
  407. >>> print(np.linspace(0, 5, 6))
  408. [0. 1. 2. 3. 4. 5.]
  409. """
  410. # This implementation was inspired by jax.numpy.linspace and numpy.linspace
  411. start, stop, num, endpoint, dtype, axis = _type_checking_for_xspace(start, stop, num, endpoint, dtype, axis)
  412. if not isinstance(retstep, bool):
  413. _raise_type_error("retstep should be an boolean, but got ", retstep)
  414. start, stop = broadcast_arrays(start, stop)
  415. axis = _canonicalize_axis(axis, start.ndim+1)
  416. bounds_shape = start.shape
  417. bounds_shape = _tuple_slice(bounds_shape, None, axis) + (1,) + _tuple_slice(bounds_shape, axis, None)
  418. iota_shape = _list_comprehensions(start.ndim+1, 1, True)
  419. iota_shape = _tuple_slice(iota_shape, None, axis) + (num,) + _tuple_slice(iota_shape, axis+1, None)
  420. num_tensor = _type_convert(Tensor, num).astype(mstype.float32)
  421. div = (num_tensor - 1) if endpoint else num_tensor
  422. if num > 1:
  423. delta = (stop - start) / div
  424. # This is similar to how numpy and jax compute linspace
  425. start_expand = reshape(start, bounds_shape)
  426. incremental_expand = reshape(_iota(mstype.float32, num), iota_shape)
  427. delta_expand = reshape(delta, bounds_shape)
  428. start_expand, incremental_expand, delta_expand = broadcast_arrays(
  429. start_expand, incremental_expand, delta_expand)
  430. out = start_expand + (incremental_expand * delta_expand)
  431. elif num == 1:
  432. delta = nan if endpoint else stop - start
  433. out = reshape(start, bounds_shape)
  434. else: # num == 0
  435. delta = nan
  436. out = _type_convert(Tensor, []).astype(dtype)
  437. if retstep:
  438. return out.astype(dtype), delta
  439. return out.astype(dtype)
  440. def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):
  441. """
  442. Returns numbers spaced evenly on a log scale.
  443. In linear space, the sequence starts at base ** start (base to the power of
  444. start) and ends with base ** stop (see endpoint below).
  445. Args:
  446. start (Union[int, list(int), tuple(int), tensor]): ``base ** start`` is the starting
  447. value of the sequence.
  448. stop (Union[int, list(int), tuple(int), tensor]): ``base ** stop`` is the final value of
  449. the sequence, unless `endpoint` is False. In that case, ``num + 1`` values are spaced
  450. over the interval in log-space, of which all but the last (a sequence of length num)
  451. are returned.
  452. num (int, optional): Number of samples to generate. Default is 50.
  453. endpoint (bool, optional): If True, `stop` is the last sample. Otherwise, it is
  454. not included. Default is True.
  455. base (Union[int, float], optional): The base of the log space. The step size
  456. between the elements in :math:`ln(samples) / ln(base)` (or :math:`log_{base}(samples)`)
  457. is uniform. Default is :math:`10.0`.
  458. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
  459. If `dtype` is None, infer the data type from other input arguments. Default is None.
  460. axis (int, optional): The axis in the result to store the samples. Relevant
  461. only if start or stop is array-like. By default (:math:`0`), the samples will
  462. be along a new axis inserted at the beginning. Use :math:`-1` to get an axis at the end.
  463. Default is :math:`0`.
  464. Returns:
  465. Tensor, equally spaced on a log scale.
  466. Raises:
  467. TypeError: If input arguments have types not specified above.
  468. Supported Platforms:
  469. ``Ascend`` ``GPU`` ``CPU``
  470. Examples:
  471. >>> import mindspore.numpy as np
  472. >>> print(np.logspace(0, 5, 6, base=2.0))
  473. [ 1. 2. 4. 8. 16. 32.]
  474. """
  475. # This implementation was inspired by jax.numpy.linspace and numpy.linspace
  476. start, stop, num, endpoint, dtype, axis = _type_checking_for_xspace(start, stop, num, endpoint, dtype, axis)
  477. if not isinstance(base, (int, float, bool)):
  478. _raise_type_error("base should be a number, but got ", base)
  479. linspace_res = linspace(start, stop, num, endpoint=endpoint, retstep=False, dtype=None, axis=axis)
  480. return F.tensor_pow(base, linspace_res).astype(dtype)
  481. def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):
  482. """
  483. Returns numbers spaced evenly on a log scale (a geometric progression).
  484. This is similar to logspace, but with endpoints specified directly. Each output sample
  485. is a constant multiple of the previous.
  486. Args:
  487. start (Union[int, list(int), tuple(int), tensor]): The starting value of the sequence.
  488. stop (Union[int, list(int), tuple(int), tensor]): The final value of the sequence,
  489. unless endpoint is False. In that case, num + 1 values are spaced over the
  490. interval in log-space, of which all but the last (a sequence of length num) are
  491. returned.
  492. num (int, optional): Number of samples to generate. Default is 50.
  493. endpoint (bool, optional): If True, `stop` is the last sample. Otherwise, it is
  494. not included. Default is True.
  495. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, can
  496. be in format of np.float32, or `float32`.If `dtype` is None, infer the data
  497. type from other input arguments. Default is None.
  498. axis (int, optional): The axis in the result to store the samples. Relevant
  499. only if start or stop is array-like. By default (0), the samples will
  500. be along a new axis inserted at the beginning. Use -1 to get an axis at the end.
  501. Default is 0.
  502. Returns:
  503. Tensor, with samples equally spaced on a log scale.
  504. Raises:
  505. TypeError: If input arguments have types not specified above.
  506. Supported Platforms:
  507. ``Ascend`` ``GPU`` ``CPU``
  508. Examples:
  509. >>> output = np.geomspace(1, 256, num=9)
  510. >>> print(output)
  511. [ 1. 2. 4. 8. 16. 32. 64. 128. 256.]
  512. >>> output = np.geomspace(1, 256, num=8, endpoint=False)
  513. >>> print(output)
  514. [ 1. 2. 4. 8. 16. 32. 64. 128.]
  515. """
  516. start, stop, num, endpoint, dtype, axis = _type_checking_for_xspace(start, stop, num, endpoint, dtype, axis)
  517. root = num
  518. if endpoint:
  519. root -= 1
  520. bases = F.tensor_pow(F.tensor_div(stop, start), asarray_const(1/(root)))
  521. exponents = linspace(zeros(F.shape(bases)), F.fill(F.dtype(bases), F.shape(bases), root),
  522. num, endpoint=endpoint, dtype=dtype, axis=axis)
  523. shape = F.shape(bases)
  524. axis = axis + F.rank(bases) + 1 if axis < 0 else axis
  525. expanded_shape = _tuple_getitem(shape, axis, False) + (1,) + _tuple_getitem(shape, axis)
  526. bases = F.reshape(bases, expanded_shape)
  527. start = F.reshape(start, expanded_shape)
  528. res = F.tensor_mul(F.tensor_pow(bases, exponents), start)
  529. if dtype is not None:
  530. res = F.cast(res, dtype)
  531. return res
  532. def eye(N, M=None, k=0, dtype=mstype.float32):
  533. """
  534. Returns a 2-D tensor with ones on the diagnoal and zeros elsewhere.
  535. Args:
  536. N (int): Number of rows in the output, must be larger than 0.
  537. M (int, optional): Number of columns in the output. If is :class:`None`, defaults to `N`,
  538. if defined, must be larger than 0. Deault is :class:`None`.
  539. k (int, optional): Index of the diagonal: 0 (the default) refers to the main
  540. diagonal, a positive value refers to an upper diagonal, and a negative value
  541. to a lower diagonal. Default is 0.
  542. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
  543. Default is mstype.float32.
  544. Returns:
  545. A tensor of shape (N, M). A tensor where all elements are equal to zero,
  546. except for the k-th diagonal, whose values are equal to one.
  547. Raises:
  548. TypeError: If input arguments have types not specified above.
  549. Supported Platforms:
  550. ``Ascend`` ``GPU`` ``CPU``
  551. Examples:
  552. >>> import mindspore.numpy as np
  553. >>> print(np.eye(2, 2))
  554. [[1. 0.]
  555. [0. 1.]]
  556. """
  557. dtype = _check_dtype(dtype)
  558. if M is None:
  559. M = N
  560. if not (isinstance(M, int) and isinstance(N, int) and isinstance(k, int)):
  561. _raise_type_error("Input tensor dimensions should be integers.")
  562. out = None
  563. if N == 0 or M == 0:
  564. # Fill the shape with any value is fine.
  565. return full((N, M), 0, dtype)
  566. out = F.eye(N, M, dtype)
  567. if k >= M or k <= -N:
  568. return full((N, M), 0, dtype)
  569. if k != 0:
  570. out = out.astype(mstype.float32)
  571. if k > 0:
  572. out_left = full((N, k), 0, dtype)
  573. out_right = out[..., 0:M-k:1]
  574. return concatenate((out_left, out_right), 1).astype(dtype)
  575. if k < 0:
  576. out_upper = full((-k, M), 0, dtype)
  577. out_lower = out[0:N+k:1, ...]
  578. return concatenate((out_upper, out_lower), 0).astype(dtype)
  579. return out
  580. def identity(n, dtype=mstype.float32):
  581. """
  582. Returns the identity tensor.
  583. Args:
  584. n (int): Number of rows and columns in the output, must be larger than 0.
  585. dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype,
  586. default is :class:`mstype.float32`.
  587. Returns:
  588. A tensor of shape `(n, n)`, where all elements are equal to zero,
  589. except for the diagonal, whose values are equal to one.
  590. Supported Platforms:
  591. ``Ascend`` ``GPU`` ``CPU``
  592. Raises:
  593. TypeError: If input arguments have types not specified above.
  594. Examples:
  595. >>> import mindspore.numpy as np
  596. >>> print(np.identity(2))
  597. [[1. 0.]
  598. [0. 1.]]
  599. """
  600. if not isinstance(n, int):
  601. _raise_type_error("Input tensor dimensions should be integers.")
  602. dtype = _check_dtype(dtype)
  603. return eye(n, dtype=dtype)
  604. @constexpr
  605. def empty_compile(dtype, shape):
  606. return Tensor_(dtype, shape)
  607. def empty(shape, dtype=mstype.float32):
  608. """
  609. Returns a new array of given shape and type, without initializing
  610. entries.
  611. Note:
  612. Numpy argument `order` is not supported.
  613. Object arrays are not supported.
  614. Args:
  615. shape (Union[int, tuple(int)]): Shape of the empty array, e.g.,
  616. (2, 3) or 2.
  617. dtype (:class:`mindspore.dtype`, optional): Desired output data-type for the
  618. array, e.g, mstype.int8. Default is mstype.float32.
  619. Returns:
  620. Tensor, array of uninitialized (arbitrary) data of the given
  621. shape and dtype.
  622. Raises:
  623. TypeError: if the input shape or dtype is invalid.
  624. Supported Platforms:
  625. ``Ascend`` ``GPU`` ``CPU``
  626. Examples:
  627. >>> import mindspore.numpy as np
  628. >>> output = np.empty((2, 3))
  629. >>> print(output)
  630. # result may vary
  631. Tensor(shape=[2, 3], dtype=Float32, value=
  632. <uninitialized>)
  633. """
  634. shape = _check_shape(shape)
  635. dtype = _check_dtype(dtype)
  636. return empty_compile(dtype, shape)
  637. def _get_shape(array_like):
  638. """Returns the shape of the array like object."""
  639. if isinstance(array_like, Tensor):
  640. return array_like.shape
  641. return asarray_const(array_like).shape
  642. def _get_dtype(array_like):
  643. """Returns the data type of the array like object."""
  644. if isinstance(array_like, Tensor):
  645. return array_like.dtype
  646. return asarray_const(array_like).dtype
  647. def _x_like(prototype, dtype, shape, constructor, fill_value=None):
  648. """
  649. Returns a tensor with the same shape and type as prototype,
  650. using constructor.
  651. """
  652. if not isinstance(prototype, ARRAY_TYPES):
  653. _raise_type_error("prototype should be int, float, bool, list, tuple, Tensor, but got", prototype)
  654. dtype_out = dtype
  655. shape_out = shape
  656. if dtype_out is None:
  657. dtype_out = _get_dtype(prototype)
  658. if shape_out is None or isinstance(shape_out, (list, tuple)) and not shape_out:
  659. shape_out = _get_shape(prototype)
  660. if fill_value is not None:
  661. return constructor(shape_out, fill_value, dtype_out)
  662. return constructor(shape_out, dtype_out)
  663. def empty_like(prototype, dtype=None, shape=None):
  664. """
  665. Returns a new array with the same shape and type as a given array.
  666. Note:
  667. Input array must have the same size across a dimension.
  668. If `prototype` is not a Tensor, dtype is float32 by default if not provided.
  669. Args:
  670. prototype (Union[Tensor, list, tuple]): The shape and data-type of `prototype`
  671. define these same attributes of the returned array.
  672. dtype (:class:`mindspore.dtype`, optional): Overrides the data type of the
  673. result.
  674. shape (int or sequence of ints, optional): Overrides the shape
  675. of the result.
  676. Returns:
  677. Tensor, array of uninitialized (arbitrary) data with the same
  678. shape and type as `prototype`.
  679. Raises:
  680. ValueError: if `prototype` is not a Tensor, list or tuple.
  681. Supported Platforms:
  682. ``Ascend`` ``GPU`` ``CPU``
  683. Examples:
  684. >>> import mindspore.numpy as np
  685. >>> a = np.ones((4,1,2))
  686. >>> output = np.empty_like(a)
  687. >>> print(output)
  688. # result may vary
  689. Tensor(shape=[4, 1, 2], dtype=Float32, value=
  690. <uninitialized>)
  691. """
  692. return _x_like(prototype, dtype, shape, empty)
  693. def ones_like(a, dtype=None, shape=None):
  694. """
  695. Returns an array of ones with the same shape and type as a given array.
  696. Note:
  697. Input array must have the same size across a dimension.
  698. If `a` is not a Tensor, dtype is float32 by default if not provided.
  699. Args:
  700. a (Union[Tensor, list, tuple]): The shape and data-type of a define these same
  701. attributes of the returned array.
  702. dtype (:class:`mindspore.dtype`, optional): Overrides the data type of the
  703. result.
  704. shape (int or sequence of ints, optional): Overrides the shape
  705. of the result.
  706. Returns:
  707. Tensor, array of ones with the same shape and type as `a`.
  708. Raises:
  709. ValueError: if `a` is not a Tensor, list or tuple.
  710. Supported Platforms:
  711. ``Ascend`` ``GPU`` ``CPU``
  712. Examples:
  713. >>> import mindspore.numpy as np
  714. >>> a = np.ones((4,1,2))
  715. >>> output = np.ones_like(a)
  716. >>> print(output)
  717. [[[1. 1.]]
  718. [[1. 1.]]
  719. [[1. 1.]]
  720. [[1. 1.]]]
  721. """
  722. return _x_like(a, dtype, shape, ones)
  723. def zeros_like(a, dtype=None, shape=None):
  724. """
  725. Returns an array of zeros with the same shape and type as a given array.
  726. Note:
  727. Input array must have the same size across a dimension.
  728. If `a` is not a Tensor, dtype is float32 by default if not provided.
  729. Args:
  730. a (Union[Tensor, list, tuple]): The shape and data-type of a define these same
  731. attributes of the returned array.
  732. dtype (:class:`mindspore.dtype`, optional): Overrides the data type of the
  733. result.
  734. shape (int or sequence of ints, optional): Overrides the shape
  735. of the result.
  736. Returns:
  737. Tensor, array of zeros with the same shape and type as `a`.
  738. Raises:
  739. ValueError: if `a` is not a Tensor, list or tuple.
  740. Supported Platforms:
  741. ``Ascend`` ``GPU`` ``CPU``
  742. Examples:
  743. >>> import mindspore.numpy as np
  744. >>> a = np.ones((4,1,2))
  745. >>> output = np.zeros_like(a)
  746. >>> print(output)
  747. [[[0. 0.]]
  748. [[0. 0.]]
  749. [[0. 0.]]
  750. [[0. 0.]]]
  751. """
  752. return _x_like(a, dtype, shape, zeros)
  753. def full_like(a, fill_value, dtype=None, shape=None):
  754. """
  755. Returns a full array with the same shape and type as a given array.
  756. Note:
  757. Input array must have the same size across a dimension.
  758. If `a` is not a Tensor, dtype is float32 by default if not provided.
  759. Args:
  760. a (Union[Tensor, list, tuple]): The shape and data-type of `a` define these same
  761. attributes of the returned array.
  762. fill_value (scalar): Fill value.
  763. dtype (:class:`mindspore.dtype`, optional): Overrides the data type of the
  764. result.
  765. shape (int or sequence of ints, optional): Overrides the shape
  766. of the result.
  767. Returns:
  768. Tensor, array of fill_value with the same shape and type as `a`.
  769. Raises:
  770. ValueError: if `a` is not a Tensor, list or tuple.
  771. Supported Platforms:
  772. ``Ascend`` ``GPU`` ``CPU``
  773. Examples:
  774. >>> import mindspore.numpy as np
  775. >>> a = np.ones((4,1,2))
  776. >>> output = np.full_like(a, 0.5)
  777. >>> print(output)
  778. [[[0.5 0.5]]
  779. [[0.5 0.5]]
  780. [[0.5 0.5]]
  781. [[0.5 0.5]]]
  782. """
  783. return _x_like(a, dtype, shape, full, fill_value=fill_value)
  784. def tri(N, M=None, k=0, dtype=mstype.float32):
  785. """
  786. Returns a tensor with ones at and below the given diagonal and zeros elsewhere.
  787. Args:
  788. N(int): Number of rows in the array.
  789. M(int, optional): Number of columns in the array. By default, `M` is taken
  790. equal to N.
  791. k(int, optional): The sub-diagonal at and below which the array is filled.
  792. :math:`k = 0` is the main diagonal, while :math:`k < 0` is below it, and :math:`k > 0` is above.
  793. The default is 0.
  794. dtype(:class:`mindspore.dtype`, optional): Data type of the returned array. The default
  795. is :class:`mindspore.dtype`.
  796. Returns:
  797. Tensor with shape `(N, M)`, with its lower triangle filled with
  798. ones and zeros elsewhere; in other words :math:`T[i,j] = 1` for :math:`j <= i + k`,
  799. :math:`0` otherwise.
  800. Raises:
  801. TypeError: If input arguments have types not specified above.
  802. Supported Platforms:
  803. ``Ascend`` ``GPU`` ``CPU``
  804. Examples:
  805. >>> import mindspore.numpy as np
  806. >>> output = np.tri(3, 3, 1)
  807. >>> print(output)
  808. [[1. 1. 0.]
  809. [1. 1. 1.]
  810. [1. 1. 1.]]
  811. """
  812. if M is None:
  813. M = N
  814. return nn_tril((N, M), dtype, k)
  815. def tril(m, k=0):
  816. """
  817. Returns a lower triangle of a tensor.
  818. Returns a copy of a tensor with elements above the `k-th` diagonal zeroed.
  819. Args:
  820. m (Union[Tensor, list, tuple]): The shape and data-type of `m` define these same
  821. attributes of the returned tensor.
  822. k (int, optional): Diagonal above which to zero elements. :math:`k = 0` (the default)
  823. is the main diagonal, :math:`k < 0` is below it and :math:`k > 0` is above.
  824. Returns:
  825. Lower triangle of `m`, of same shape and data-type as `m`.
  826. Supported Platforms:
  827. ``Ascend`` ``GPU`` ``CPU``
  828. Raises:
  829. TypeError: If input arguments have types not specified above.
  830. ValueError: If input `m`\'s rank :math:`< 1`.
  831. Examples:
  832. >>> import mindspore.numpy as np
  833. >>> output = np.tril(np.ones((3, 3)))
  834. >>> print(output)
  835. [[1. 0. 0.]
  836. [1. 1. 0.]
  837. [1. 1. 1.]]
  838. """
  839. if not isinstance(m, Tensor):
  840. m = asarray_const(m)
  841. dtype = m.dtype
  842. m = m.astype(mstype.float32)
  843. assist = nn_tril(m.shape, mstype.float32, k)
  844. return F.tensor_mul(assist, m).astype(dtype)
  845. def triu(m, k=0):
  846. """
  847. Returns an upper triangle of a tensor.
  848. Returns a copy of a tensor with elements below the `k-th` diagonal zeroed.
  849. Args:
  850. m (Union[Tensor, list, tuple]): The shape and data-type of `m` define these same
  851. attributes of the returned tensor.
  852. k (int, optional): Diagonal below which to zero elements. :math:`k = 0` (the default)
  853. is the main diagonal, :math:`k < 0` is below it and :math:`k > 0` is above.
  854. Returns:
  855. Upper triangle of `m`, of same shape and data-type as `m`.
  856. Raises:
  857. TypeError: If input arguments have types not specified above.
  858. ValueError: If input `m`\'s rank < 1.
  859. Supported Platforms:
  860. ``Ascend`` ``GPU`` ``CPU``
  861. Examples:
  862. >>> import mindspore.numpy as np
  863. >>> output = np.triu(np.ones((3, 3)))
  864. >>> print(output)
  865. [[1. 1. 1.]
  866. [0. 1. 1.]
  867. [0. 0. 1.]]
  868. """
  869. if not isinstance(m, Tensor):
  870. m = asarray_const(m)
  871. dtype = m.dtype
  872. m = m.astype(mstype.float32)
  873. assist = nn_triu(m.shape, mstype.float32, k)
  874. return F.tensor_mul(assist, m).astype(dtype)
  875. def diagonal(a, offset=0, axis1=0, axis2=1):
  876. """
  877. Returns specified diagonals.
  878. If `a` is 2-D, returns the diagonal of `a` with the given offset, i.e., the
  879. collection of elements of the form ``a[i, i+offset]``. If `a` has more than two
  880. dimensions, then the axes specified by `axis1` and `axis2` are used to determine
  881. the 2-D sub-array whose diagonal is returned. The shape of the resulting
  882. array can be determined by removing `axis1` and `axis2` and appending an index
  883. to the right equal to the size of the resulting diagonals.
  884. Args:
  885. a (Tensor): Array from which the diagonals are taken.
  886. offset (int, optional): Offset of the diagonal from the main diagonal.
  887. Can be positive or negative. Defaults to main diagonal.
  888. axis1 (int, optional): Axis to be used as the first axis of the 2-D
  889. sub-arrays from which the diagonals should be taken. Defaults to
  890. first axis (0).
  891. axis2 (int, optional): Axis to be used as the second axis of the 2-D
  892. sub-arrays from which the diagonals should be taken. Defaults to
  893. second axis.
  894. Returns:
  895. Tensor, if `a` is 2-D, then `a` 1-D array containing the diagonal. If
  896. ``a.ndim > 2``, then the dimensions specified by `axis1` and `axis2` are removed,
  897. and a new axis inserted at the end corresponding to the diagonal.
  898. Raises:
  899. ValueError: if the input tensor has less than two dimensions.
  900. Supported Platforms:
  901. ``Ascend`` ``GPU`` ``CPU``
  902. Examples:
  903. >>> import mindspore.numpy as np
  904. >>> a = np.arange(4).reshape(2,2)
  905. >>> print(a)
  906. [[0 1]
  907. [2 3]]
  908. >>> output = np.diagonal(a)
  909. >>> print(output)
  910. [0 3]
  911. >>> output = np.diagonal(a, 1)
  912. >>> print(output)
  913. [1]
  914. >>> a = np.arange(8).reshape(2, 2, 2)
  915. >>> print(a)
  916. [[[0 1]
  917. [2 3]]
  918. [[4 5]
  919. [6 7]]]
  920. >>> output = np.diagonal(a, 0, 0, 1)
  921. >>> print(output)
  922. [[0 6]
  923. [1 7]]
  924. """
  925. ndim = F.rank(a)
  926. if ndim < 2:
  927. return _raise_value_error('diagonal requires an array of at least two dimensions')
  928. dtype = F.dtype(a)
  929. if _is_shape_empty(F.shape(a)):
  930. return _empty(dtype, (0,))
  931. cast_type = dtype
  932. if not _check_is_float(dtype):
  933. # reduce_sum only supports float types
  934. cast_type = mstype.float32
  935. a = F.cast(a, cast_type)
  936. axes = _check_axis_valid((axis1, axis2), ndim)
  937. perm = ()
  938. for i in range(ndim):
  939. if i not in axes:
  940. perm += (i,)
  941. perm += axes
  942. a = transpose(a, perm)
  943. shape = F.shape(a)
  944. n, m = shape[-2:]
  945. e = eye(n, m, offset, cast_type)
  946. e = _broadcast_to_shape(e, F.shape(a))
  947. prod = F.tensor_mul(a, e)
  948. res = F.reduce_sum(prod, -1)
  949. begin = ()
  950. for i in range(ndim-2):
  951. begin += (0,)
  952. last_dim_begin = _max(0, -offset)
  953. begin += (last_dim_begin,)
  954. size = F.shape(res)[:-1]
  955. last_dim_end = _min(
  956. shape[-2], _max(0, shape[-1] - offset)) - last_dim_begin
  957. if last_dim_end <= 0:
  958. return _empty(dtype, size + (0,))
  959. size += (last_dim_end,)
  960. res = F.tensor_slice(res, begin, size)
  961. if not _check_same_type(cast_type, dtype):
  962. res = F.cast(res, dtype)
  963. return res
  964. def trace(a, offset=0, axis1=0, axis2=1, dtype=None):
  965. """
  966. Returns the sum along diagonals of the array.
  967. If `a` is 2-D, the sum along its diagonal with the given offset is returned,
  968. i.e., the sum of elements ``a[i,i+offset]`` for all `i`.
  969. If `a` has more than two dimensions, then the axes specified by `axis1` and
  970. `axis2` are used to determine the 2-D sub-arrays whose traces are returned.
  971. The shape of the resulting array is the same as that of a with `axis1` and
  972. `axis2` removed.
  973. Note:
  974. On GPU, the supported dtypes are np.float16, and np.float32.
  975. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.
  976. Args:
  977. a (Tensor): Array from which the diagonals are taken.
  978. offset (int, optional): Offset of the diagonal from the main diagonal.
  979. Can be positive or negative. Defaults to main diagonal.
  980. axis1 (int, optional): Axis to be used as the first axis of the 2-D
  981. sub-arrays from which the diagonals should be taken. Defaults to
  982. first axis (0).
  983. axis2 (int, optional): Axis to be used as the second axis of the 2-D
  984. sub-arrays from which the diagonals should be taken. Defaults to
  985. second axis.
  986. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  987. output Tensor.
  988. Returns:
  989. Tensor, sum_along_diagonals. If `a` is 2-D, the sum along the diagonal
  990. is returned. If `a` has larger dimensions, then an array of sums along
  991. diagonals is returned.
  992. Raises:
  993. ValueError: if the input tensor has less than two dimensions.
  994. Supported Platforms:
  995. ``Ascend`` ``GPU`` ``CPU``
  996. Examples:
  997. >>> import mindspore.numpy as np
  998. >>> output = np.trace(np.eye(3))
  999. >>> print(output)
  1000. 3.0
  1001. >>> a = np.arange(8).reshape((2,2,2))
  1002. >>> output = np.trace(a)
  1003. >>> print(output)
  1004. [6 8]
  1005. >>> a = np.arange(24).reshape((2,2,2,3))
  1006. >>> output = np.trace(a).shape
  1007. >>> print(output)
  1008. (2, 3)
  1009. """
  1010. d = diagonal(a, offset, axis1=axis1, axis2=axis2)
  1011. shape = F.shape(d)
  1012. if dtype is None:
  1013. dtype = F.dtype(d)
  1014. if shape[-1] == 0:
  1015. return _empty(dtype, shape[:-1])
  1016. cast_type = dtype
  1017. if not _check_is_float(dtype):
  1018. # reduce sum only supports float types
  1019. cast_type = mstype.float32
  1020. d = F.cast(d, cast_type)
  1021. res = F.reduce_sum(d, -1)
  1022. if not _check_same_type(cast_type, dtype):
  1023. res = F.cast(res, dtype)
  1024. return res
  1025. def _index(i, size, Cartesian=True):
  1026. """If Cartesian=True, index 0 is swapped with index 1."""
  1027. if Cartesian:
  1028. if i == 1:
  1029. return 0
  1030. if i == 0 and size >= 2:
  1031. return 1
  1032. return i
  1033. def meshgrid(*xi, sparse=False, indexing='xy'):
  1034. """
  1035. Returns coordinate matrices from coordinate vectors.
  1036. Make `N-D` coordinate arrays for vectorized evaluations of `N-D`
  1037. scalar/vector fields over `N-D` grids, given one-dimensional
  1038. coordinate arrays `x1, x2,…, xn`.
  1039. Note:
  1040. Numpy argument copy is not supported, and a copy is always
  1041. returned.
  1042. Args:
  1043. *xi (Tensor): 1-D arrays representing the coordinates
  1044. of a grid.
  1045. indexing (‘xy’, ‘ij’, optional): Cartesian (‘xy’, default) or
  1046. matrix (‘ij’) indexing of output. In the 2-D case with
  1047. inputs of length `M` and `N`, the outputs are of shape `(N, M)`
  1048. for ‘xy’ indexing and `(M, N)` for ‘ij’ indexing. In the 3-D
  1049. case with inputs of length `M`, `N` and `P`, outputs are of shape
  1050. `(N, M, P)` for ‘xy’ indexing and `(M, N, P)` for ‘ij’ indexing.
  1051. sparse (bool, optional): If True a sparse grid is returned in
  1052. order to conserve memory. Default is False.
  1053. Returns:
  1054. Tuple of tensors, for vectors `x1, x2,…, xn` with lengths
  1055. ``Ni=len(xi)``, return `(N1, N2, N3,...Nn)` shaped arrays if
  1056. ``indexing=’ij’`` or `(N2, N1, N3,...Nn)` shaped arrays if
  1057. ``indexing=’xy’`` with the elements of `xi` repeated to fill the matrix
  1058. along the first dimension for `x1`, the second for `x2` and so on.
  1059. Raises:
  1060. TypeError: if the input is not a tensor, or sparse is not boolean, or
  1061. indexing is not 'xy' or 'ij'.
  1062. Supported Platforms:
  1063. ``Ascend`` ``GPU`` ``CPU``
  1064. Examples:
  1065. >>> import mindspore.numpy as np
  1066. >>> x = np.linspace(0, 1, 3)
  1067. >>> y = np.linspace(0, 1, 2)
  1068. >>> xv, yv = np.meshgrid(x, y)
  1069. >>> print(xv)
  1070. [[0. , 0.5, 1. ],
  1071. [0. , 0.5, 1. ]]
  1072. >>> print(yv)
  1073. [[0., 0., 0.],
  1074. [1., 1., 1.]]
  1075. >>> xv, yv = np.meshgrid(x, y, sparse=True)
  1076. >>> print(xv)
  1077. [[0. , 0.5, 1. ]]
  1078. >>> print(yv)
  1079. [[0.],
  1080. [1.]
  1081. """
  1082. _check_input_tensor(*xi)
  1083. if not isinstance(sparse, bool):
  1084. _raise_type_error('argument sparse should be boolean')
  1085. if indexing not in ('xy', 'ij'):
  1086. _raise_type_error("Valid values for `indexing` are 'xy' and 'ij'.")
  1087. shape_out = ()
  1088. for x in xi:
  1089. shape_out += (x.size,)
  1090. if _is_shape_empty(shape_out):
  1091. return ones(shape_out)
  1092. grids = []
  1093. for x in xi:
  1094. if F.rank(x) == 1:
  1095. grids.append(x)
  1096. else:
  1097. grids.append(ravel(x))
  1098. ndim = len(grids)
  1099. Cartesian = indexing == 'xy'
  1100. shape_out = ()
  1101. for i in range(len(grids)):
  1102. grid_index = _index(i, ndim, Cartesian=Cartesian)
  1103. shape_out += (F.shape(grids[grid_index])[0],)
  1104. res = []
  1105. for i, x in enumerate(grids):
  1106. grid_index = _index(i, ndim, Cartesian=Cartesian)
  1107. shape_expanded = _expanded_shape(ndim, shape_out[grid_index], grid_index)
  1108. x = x.reshape(shape_expanded)
  1109. if not sparse:
  1110. x = F.tile(x, _tile_size(shape_expanded, shape_out, ndim))
  1111. res.append(x)
  1112. return res
  1113. class nd_grid:
  1114. """
  1115. Construct a multi-dimensional "meshgrid".
  1116. ``grid = nd_grid()`` creates an instance which will return a mesh-grid
  1117. when indexed.
  1118. If instantiated with an argument of ``sparse=True``, the mesh-grid is
  1119. open (or not fleshed out) so that only one-dimension of each
  1120. returned argument is greater than 1.
  1121. Args:
  1122. sparse (bool): Whether the grid is sparse or not. Default is
  1123. False.
  1124. Returns:
  1125. Tensor or tuple of tensor, a meshgrid. If ``sparse=False``, returns
  1126. tensors are all of the same dimensions; and if ``sparse=True``,
  1127. returns tensors with only one dimension not equal to `1`.
  1128. """
  1129. def __init__(self, sparse=False):
  1130. self.sparse = sparse
  1131. def __getitem__(self, keys):
  1132. if isinstance(keys, slice):
  1133. keys = (keys,)
  1134. xi = []
  1135. for k in keys:
  1136. if not isinstance(k.start, int) or not isinstance(k.stop, int):
  1137. _raise_type_error('slice indices must be integers')
  1138. if k.step:
  1139. step = k.step
  1140. else:
  1141. step = 1
  1142. if isinstance(step, complex):
  1143. v = linspace(k.start, k.stop, int(abs(step)))
  1144. else:
  1145. v = arange(k.start, k.stop, step)
  1146. xi.append(v)
  1147. grids = meshgrid(*xi, sparse=self.sparse, indexing='ij')
  1148. if len(grids) == 1:
  1149. return grids[0]
  1150. if self.sparse:
  1151. return grids
  1152. if isinstance(grids, Tensor_):
  1153. return grids
  1154. expanded = []
  1155. for grid in grids:
  1156. expanded.append(F.expand_dims(grid, 0))
  1157. res = concatenate(tuple(expanded))
  1158. return res
  1159. class mGridClass(nd_grid):
  1160. """
  1161. mgrid is an :class:`nd_grid` instance with ``sparse=False``.
  1162. The dimension and number of the output arrays are equal to the number
  1163. of indexing dimensions. If the step length is not a complex number,
  1164. then the stop is not inclusive. However, if the step length is a complex
  1165. number (e.g. 5j), then the integer part of its magnitude is interpreted
  1166. as specifying the number of points to create between the start and
  1167. stop values, where the stop value is inclusive.
  1168. Note:
  1169. Unlike Numpy, if the step length is a complex number with a real
  1170. component, the step length is handled as equivalent to
  1171. ``int(abs(step))``.
  1172. Returns:
  1173. Tensor or tuple of tensor, a meshgrid.
  1174. Raises:
  1175. TypeError: if slicing indices are not integers.
  1176. Supported Platforms:
  1177. ``Ascend`` ``GPU`` ``CPU``
  1178. Examples:
  1179. >>> from mindspore.numpy import mgrid
  1180. >>> output = mgrid[0:5, 0:5]
  1181. >>> print(output)
  1182. [[[0, 0, 0, 0, 0],
  1183. [1, 1, 1, 1, 1],
  1184. [2, 2, 2, 2, 2],
  1185. [3, 3, 3, 3, 3],
  1186. [4, 4, 4, 4, 4]],
  1187. [[0, 1, 2, 3, 4],
  1188. [0, 1, 2, 3, 4],
  1189. [0, 1, 2, 3, 4],
  1190. [0, 1, 2, 3, 4],
  1191. [0, 1, 2, 3, 4]]]
  1192. >>> output = mgrid[-1:1:5j]
  1193. >>> print(output)
  1194. [-1. , -0.5, 0. , 0.5, 1. ]
  1195. """
  1196. def __init__(self):
  1197. super(mGridClass, self).__init__(sparse=False)
  1198. class oGridClass(nd_grid):
  1199. """
  1200. ogrid is an :class:`nd_grid` instance with ``sparse=True``.
  1201. The dimension and number of the output arrays are equal to the number
  1202. of indexing dimensions. If the step length is not a complex number,
  1203. then the stop is not inclusive. However, if the step length is a complex
  1204. number (e.g. 5j), then the integer part of its magnitude is interpreted
  1205. as specifying the number of points to create between the start and
  1206. stop values, where the stop value is inclusive.
  1207. Note:
  1208. Unlike Numpy, if the step length is a complex number with a real
  1209. component, the step length is handled as equivalent to
  1210. ``int(abs(step))``.
  1211. Raises:
  1212. TypeError: if slicing indices are not integers.
  1213. Supported Platforms:
  1214. ``Ascend`` ``GPU`` ``CPU``
  1215. Examples:
  1216. >>> from mindspore.numpy import ogrid
  1217. >>> output = ogrid[0:5,0:5]
  1218. >>> print(output)
  1219. [Tensor(shape=[5, 1], dtype=Int32, value=
  1220. [[0],
  1221. [1],
  1222. [2],
  1223. [3],
  1224. [4]]), Tensor(shape=[1, 5], dtype=Int32, value=
  1225. [[0, 1, 2, 3, 4]])]
  1226. >>> output = ogrid[-1:1:5j]
  1227. >>> print(output)
  1228. [-1. , -0.5, 0. , 0.5, 1. ]
  1229. """
  1230. def __init__(self):
  1231. super(oGridClass, self).__init__(sparse=True)
  1232. mgrid = mGridClass()
  1233. ogrid = oGridClass()
  1234. def diag(v, k=0):
  1235. """
  1236. Extracts a diagonal or construct a diagonal array.
  1237. Args:
  1238. v (Tensor): If `v` is a 2-D array, return a copy of its `k-th` diagonal.
  1239. If `v` is a 1-D array, return a 2-D array with v on the `k-th` diagonal.
  1240. k (int, optional): Diagonal in question. The default is 0. Use ``k>0`` for
  1241. diagonals above the main diagonal, and ``k<0`` for diagonals below the
  1242. main diagonal.
  1243. Returns:
  1244. Tensor, the extracted diagonal or constructed diagonal array.
  1245. Raises:
  1246. ValueError: if input is not 1-D or 2-D.
  1247. Supported Platforms:
  1248. ``Ascend`` ``GPU`` ``CPU``
  1249. Examples:
  1250. >>> import mindspore.numpy as np
  1251. >>> x = np.arange(9).reshape((3,3))
  1252. >>> print(x)
  1253. [[0 1 2]
  1254. [3 4 5]
  1255. [6 7 8]]
  1256. >>> output = np.diag(x)
  1257. >>> print(output)
  1258. [0 4 8]
  1259. >>> output = np.diag(x, k=1)
  1260. >>> print(output)
  1261. [1 5]
  1262. >>> output = np.diag(x, k=-1)
  1263. >>> print(output)
  1264. [3 7]
  1265. """
  1266. ndim = F.rank(v)
  1267. if ndim == 1:
  1268. return diagflat(v, k=k)
  1269. if ndim == 2:
  1270. shape = F.shape(v)
  1271. dtype = F.dtype(v)
  1272. if _is_shape_empty(shape):
  1273. return _empty(dtype, (0,))
  1274. e = eye(shape[0], shape[1], k, dtype)
  1275. prod = F.tensor_mul(v, e)
  1276. cast_type = dtype
  1277. if not _check_is_float(dtype):
  1278. # reduce sum only supports float types
  1279. cast_type = mstype.float32
  1280. prod = F.cast(prod, cast_type)
  1281. res = F.reduce_sum(prod, 1)
  1282. res = res[_max(0, -k): _min(shape[0], _max(0, shape[1] - k))]
  1283. if not _check_same_type(cast_type, dtype):
  1284. res = F.cast(res, dtype)
  1285. return res
  1286. return _raise_value_error("Input must be 1- or 2-d.")
  1287. def diagflat(v, k=0):
  1288. """
  1289. Creates a two-dimensional array with the flattened input as a diagonal.
  1290. Note:
  1291. On GPU, the supported dtypes are np.float16, and np.float32.
  1292. Args:
  1293. v (Tensor): Input data, which is flattened and set as the `k-th` diagonal
  1294. of the output.
  1295. k (int, optional): Diagonal to set; 0, the default, corresponds to the
  1296. “main” diagonal, a positive (negative) `k` giving the number of the
  1297. diagonal above (below) the main.
  1298. Returns:
  1299. Tensor, The 2-D output array.
  1300. Raises:
  1301. TypeError: if the input is not a tensor.
  1302. Supported Platforms:
  1303. ``Ascend`` ``GPU`` ``CPU``
  1304. Examples:
  1305. >>> import mindspore.numpy as np
  1306. >>> output = np.diagflat(np.asarray([[1,2], [3,4]]))
  1307. >>> print(output)
  1308. [[1 0 0 0]
  1309. [0 2 0 0]
  1310. [0 0 3 0]
  1311. [0 0 0 4]]
  1312. >>> output = np.diagflat(np.asarray([1,2]), 1)
  1313. >>> print(output)
  1314. [[0 1 0]
  1315. [0 0 2]
  1316. [0 0 0]]
  1317. """
  1318. _check_input_tensor(v)
  1319. dtype = F.dtype(v)
  1320. k_abs = _abs(k)
  1321. if _is_shape_empty(F.shape(v)):
  1322. return zeros((k_abs, k_abs), dtype)
  1323. v = ravel(v)
  1324. size = F.shape(v)[0]
  1325. e = eye(size, size, 0, dtype)
  1326. res = F.tensor_mul(v, e)
  1327. if k != 0:
  1328. pad_y = zeros((size, k_abs), dtype)
  1329. pad_x = zeros((k_abs, size + k_abs), dtype)
  1330. if k < 0:
  1331. res = concatenate((res, pad_y), axis=1)
  1332. res = concatenate((pad_x, res), axis=0)
  1333. else:
  1334. res = concatenate((pad_y, res), axis=1)
  1335. res = concatenate((res, pad_x), axis=0)
  1336. return res
  1337. def diag_indices(n, ndim=2):
  1338. """
  1339. Returns the indices to access the main diagonal of an array.
  1340. This returns a tuple of indices that can be used to access the main
  1341. diagonal of an array a with ``a.ndim >= 2`` dimensions and shape `(n, n, …, n)`.
  1342. For ``a.ndim = 2`` this is the usual diagonal, for ``a.ndim > 2`` this is the set
  1343. of indices to access ``a[i, i, ..., i]`` for ``i = [0..n-1]``.
  1344. Args:
  1345. n (int): The size, along each dimension, of the arrays for which
  1346. the returned indices can be used.
  1347. ndim (int, optional): The number of dimensions.
  1348. Returns:
  1349. Tuple of Tensor.
  1350. Raises:
  1351. TypeError: if input are not integers.
  1352. Supported Platforms:
  1353. ``Ascend`` ``GPU`` ``CPU``
  1354. Examples:
  1355. >>> import mindspore.numpy as np
  1356. >>> output = np.diag_indices(5, 3)
  1357. >>> print(output)
  1358. (Tensor(shape=[5], dtype=Int32, value= [0, 1, 2, 3, 4]),
  1359. Tensor(shape=[5], dtype=Int32, value= [0, 1, 2, 3, 4]),
  1360. Tensor(shape=[5], dtype=Int32, value= [0, 1, 2, 3, 4]))
  1361. """
  1362. if not isinstance(n, int) or not isinstance(ndim, int):
  1363. _raise_type_error('input must be integers')
  1364. return _list_comprehensions(ndim, arange(start=0, stop=n), True)
  1365. def ix_(*args):
  1366. r"""
  1367. Constructs an open mesh from multiple sequences.
  1368. This function takes `N` 1-D sequences and returns `N` outputs with `N`
  1369. dimensions each, such that the shape is 1 in all but one dimension
  1370. and the dimension with the non-unit shape value cycles through all
  1371. N dimensions.
  1372. Using ix\_ one can quickly construct index arrays that will index
  1373. the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array
  1374. ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``.
  1375. Note:
  1376. Boolean masks are not supported.
  1377. Args:
  1378. *args (Tensor): 1-D sequences.
  1379. Returns:
  1380. Tuple of Tensor, `N` arrays with `N` dimensions each, with `N` the
  1381. number of input sequences. Together these arrays form an open
  1382. mesh.
  1383. Raises:
  1384. TypeError: if the input is not a tensor.
  1385. Supported Platforms:
  1386. ``Ascend`` ``GPU`` ``CPU``
  1387. Examples:
  1388. >>> import mindspore.numpy as np
  1389. >>> ixgrid = np.ix_(np.array([0, 1]), np.array([2, 4]))
  1390. >>> print(ixgrid)
  1391. [Tensor(shape=[2, 1], dtype=Int32, value=
  1392. [[0],
  1393. [1]]), Tensor(shape=[1, 2], dtype=Int32, value=
  1394. [[2, 4]])]
  1395. """
  1396. # TODO boolean mask
  1397. _check_input_tensor(*args)
  1398. ndim = len(args)
  1399. res = ()
  1400. for i, arr in enumerate(args):
  1401. if F.rank(arr) != 1:
  1402. return _raise_value_error('Cross index must be 1 dimensional')
  1403. res += (F.reshape(arr, _expanded_shape(ndim, arr.size, i)),)
  1404. return res
  1405. def vander(x, N=None, increasing=False):
  1406. """
  1407. Generates a Vandermonde matrix.
  1408. The columns of the output matrix are powers of the input vector. The order of
  1409. the powers is determined by the increasing boolean argument. Specifically, when
  1410. increasing is `False`, the i-th output column is the input vector raised element-wise
  1411. to the power of :math:`N - i - 1`. Such a matrix with a geometric progression in each row
  1412. is named for Alexandre-Theophile Vandermonde.
  1413. Args:
  1414. x (Union[list, tuple, Tensor]): 1-D input array.
  1415. N (int, optional): Number of columns in the output. If N is not specified, a
  1416. square array is returned (``N = len(x)``).
  1417. increasing (bool, optional): Order of the powers of the columns. If True, the
  1418. powers increase from left to right, if False (the default) they are reversed.
  1419. Returns:
  1420. Vandermonde matrix. If `increasing` is `False`, the first column is :math:`x^{(N-1)}`,
  1421. the second :math:`x^{(N-2)}` and so forth. If `increasing` is `True`, the columns are
  1422. :math:`x^0, x^1, ..., x^{(N-1)}`.
  1423. Raises:
  1424. TypeError: If inputs have types not specified above.
  1425. ValueError: If `x` is not 1-D, or `N` < 0.
  1426. Supported Platforms:
  1427. ``Ascend`` ``GPU`` ``CPU``
  1428. Examples:
  1429. >>> import mindspore.numpy as np
  1430. >>> print(np.vander([1,2,3,4,5]))
  1431. [[ 1 1 1 1 1]
  1432. [ 16 8 4 2 1]
  1433. [ 81 27 9 3 1]
  1434. [256 64 16 4 1]
  1435. [625 125 25 5 1]]
  1436. """
  1437. if isinstance(x, (list, tuple)):
  1438. x = asarray_const(x)
  1439. elif not isinstance(x, Tensor):
  1440. _raise_type_error("Input x must be list, tuple or Tensor, but got ", x)
  1441. if x.ndim != 1:
  1442. _raise_value_error("Input x must be 1-D, but got dimension=", x.ndim)
  1443. N = N or x.size
  1444. if not isinstance(N, int):
  1445. _raise_type_error("Input N must be an integer.")
  1446. if N <= 0:
  1447. _raise_value_error("Input N must > 0.")
  1448. if not isinstance(increasing, bool):
  1449. _raise_type_error("increasing must be a bool.")
  1450. exponent = _iota(x.dtype, N, increasing)
  1451. x = F.expand_dims(x, 1)
  1452. exponent = F.expand_dims(exponent, 0)
  1453. return F.tensor_pow(x, exponent)
  1454. def indices(dimensions, dtype=mstype.int32, sparse=False):
  1455. """
  1456. Returns an array representing the indices of a grid.
  1457. Computes an array where the subarrays contain index values 0, 1, …
  1458. varying only along the corresponding axis.
  1459. Args:
  1460. dimensions (tuple or list of ints): The shape of the grid.
  1461. dtype (data type, optional): Data type of the result.
  1462. sparse (boolean, optional): Defaults to False. Return a sparse
  1463. representation of the grid instead of a dense representation.
  1464. Returns:
  1465. Tensor or tuple of Tensor, If `sparse` is False, returns one array
  1466. of grid indices, ``grid.shape = (len(dimensions),) + tuple(dimensions)``.
  1467. If sparse is True, returns a tuple of arrays, with
  1468. ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
  1469. ``dimensions[i]`` in the `ith` place
  1470. Raises:
  1471. TypeError: if input dimensions is not a tuple or list.
  1472. Supported Platforms:
  1473. ``Ascend`` ``GPU`` ``CPU``
  1474. Examples:
  1475. >>> grid = np.indices((2, 3))
  1476. >>> print(indices)
  1477. [Tensor(shape=[2, 3], dtype=Int32, value=
  1478. [[0, 0, 0],
  1479. [1, 1, 1]]), Tensor(shape=[2, 3], dtype=Int32, value=
  1480. [[0, 1, 2],
  1481. [0, 1, 2]])]
  1482. """
  1483. if not isinstance(dimensions, (tuple, list)):
  1484. _raise_type_error('Shape of the grid must be tuple or list')
  1485. grids = ()
  1486. for d in dimensions:
  1487. grids += (arange(d, dtype=dtype),)
  1488. return meshgrid(*grids, sparse=sparse, indexing='ij')