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

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