tinyms

Top-level reference to dtype of common module. This module also provides Numpy-like interfaces in TinyMS.

Examples

>>> import tinyms as ts
>>>
>>> print(ts.ones([2, 3]))
[[1. 1. 1.]
[1. 1. 1.]]
tinyms.dtype_to_nptype(type_)[source]

Convert MindSpore dtype to numpy data type.

Parameters

type_ (mindspore.dtype) – MindSpore’s dtype.

Returns

The data type of numpy.

tinyms.issubclass_(type_, dtype)[source]

Determine whether type_ is a subclass of dtype.

Parameters
  • type_ (mindspore.dtype) – Target MindSpore dtype.

  • dtype (mindspore.dtype) – Compare MindSpore dtype.

Returns

bool, True or False.

tinyms.dtype_to_pytype(type_)[source]

Convert MindSpore dtype to python data type.

Parameters

type_ (mindspore.dtype) – MindSpore’s dtype.

Returns

Type of python.

tinyms.pytype_to_dtype(obj)[source]

Convert python type to MindSpore type.

Parameters

obj (type) – A python type object.

Returns

Type of MindSpore type.

tinyms.get_py_obj_dtype(obj)[source]

Get the MindSpore data type, which corresponds to python type or variable.

Parameters

obj (type) – An object of python type, or a variable of python type.

Returns

Type of MindSpore type.

class tinyms.Tensor(input_data=None, dtype=None, shape=None, init=None)[source]

Tensor is used for data storage.

Tensor inherits tensor object in C++. Some functions are implemented in C++ and some functions are implemented in Python.

Parameters
  • input_data (Union[Tensor, float, int, bool, tuple, list, numpy.ndarray]) – Input data of the tensor.

  • dtype (mindspore.dtype) – Input data should be None, bool or numeric type defined in mindspore.dtype. The argument is used to define the data type of the output tensor. If it is None, the data type of the output tensor will be the same as the input_data. Default: None.

  • shape (Union[tuple, list, int]) – A list of integers, a tuple of integers or an integer as the shape of output. If input_data is available, shape doesn’t need to be set. Default: None.

  • init (Initializer) – The information of init data. ‘init’ is used for delayed initialization in parallel mode. Usually, it is not recommended to use ‘init’ interface to initialize parameters in other conditions. If ‘init’ interface is used to initialize parameters, the Tensor.init_data API needs to be called to convert Tensor to the actual data.

Outputs:

Tensor. If dtype and shape are not set, return a tensor with the same dtype and shape as input_data. If dtype or shape is set, the dtype or shape of the output Tensor is consistent with the setting.

Examples

>>> import numpy as np
>>> import mindspore as ms
>>> from mindspore import Tensor
>>> from mindspore.common.initializer import One
>>> # initialize a tensor with input data
>>> t1 = Tensor(np.zeros([1, 2, 3]), ms.float32)
>>> assert isinstance(t1, Tensor)
>>> assert t1.shape == (1, 2, 3)
>>> assert t1.dtype == ms.float32
>>>
>>> # initialize a tensor with a float scalar
>>> t2 = Tensor(0.1)
>>> assert isinstance(t2, Tensor)
>>> assert t2.dtype == ms.float64
...
>>> # initialize a tensor with init
>>> t3 = Tensor(shape = (1, 3), dtype=ms.float32, init=One())
>>> assert isinstance(t3, Tensor)
>>> assert t3.shape == (1, 3)
>>> assert t3.dtype == ms.float32
property T

Return the transposed tensor.

abs()[source]

Return absolute value element-wisely.

Returns

Tensor, with absolute value element-wisely.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> a = Tensor([1.1, -2.1]).astype("float32")
>>> output = a.abs()
>>> print(output)
[1.1 2.1]
all(axis=(), keep_dims=False)[source]

Check all array elements along a given axis evaluate to True.

Parameters
  • axis (Union[None, int, tuple(int)) – Dimensions of reduction, when the axis is None or empty tuple, reduce all dimensions. Default: ().

  • keep_dims (bool) – Whether to keep the reduced dimensions. Default: False.

Returns

Tensor, if all array elements along the given axis evaluate to True, its value is True, otherwise its value is False. If the axis is None or empty tuple, reduce all dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> a = Tensor([True, True, False])
>>> output = a.all()
>>> print(output)
False
any(axis=(), keep_dims=False)[source]

Check any array element along a given axis evaluate to True.

Parameters
  • axis (Union[None, int, tuple(int)) – Dimensions of reduction, when the axis is None or empty tuple, reduce all dimensions. Default: ().

  • keep_dims (bool) – Whether to keep the reduced dimensions. Default: False.

Returns

Tensor, if any array element along the given axis evaluates to True, its value is True, otherwise its value is False. If the axis is None or empty tuple, reduce all dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> a = Tensor([True, True, False])
>>> output = a.any()
>>> print(output)
True
argmax(axis=None)[source]

Return the indices of the maximum values along an axis.

Parameters

axis (int, optional) – By default, the index is into the flattened tensor, otherwise along the specified axis.

Returns

Tensor, indices into the input tensor. It has the same shape as self.shape with the dimension along axis removed.

Raises

ValueError – if the axis is out of range.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(10, 16).reshape(2, 3).astype("float32"))
>>> print(a.argmax())
5
argmin(axis=None)[source]

Return the indices of the minimum values along an axis.

Parameters

axis (int, optional) – By default, the index is into the flattened tensor, otherwise along the specified axis.

Returns

Tensor, indices into the input tensor. It has the same shape as self.shape with the dimension along axis removed.

Raises

ValueError – if the axis is out of range.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(10, 16).reshape(2, 3).astype("float32"))
>>> print(a.argmin())
0
asnumpy()[source]

Convert tensor to numpy array.

assign_value_cpp(self: mindspore._c_expression.Tensor, arg0: mindspore._c_expression.Tensor) → mindspore._c_expression.Tensor

Assign another tensor value to this.

Arg:

value (mindspore.tensor): The value tensor.

Examples

>>> data = mindspore.Tensor(np.ones((1, 2), np.float32))
>>> data2 = mindspore.Tensor(np.ones((2, 2), np.float32))
>>> data.assign_value(data2)
>>> data.shape
(2, 2)
astype(dtype, copy=True)[source]

Return a copy of the tensor, cast to a specified type.

Parameters
  • dtype (Union[mindspore.dtype, str]) – Designated tensor dtype, can be in format of mindspore.dtype.float32 or float32. Default: mindspore.dtype.float32.

  • copy (bool, optional) – By default, astype always returns a newly allocated tensor. If this is set to false, the input tensor is returned instead of a copy if possible. Default: True.

Returns

Tensor, with the designated dtype.

Raises

TypeError – If dtype has types not specified above, or values cannot be understood.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((1,2,2,1), dtype=np.float32))
>>> x = x.astype("int32")
>>> print(x.dtype)
Int32
choose(choices, mode='clip')[source]

Construct an array from an index array and a list of arrays to choose from.

Parameters
  • choices (Union[tuple, list, Tensor]) – Choice arrays. a and all of the choices must be broadcasted to the same shape. If choices is itself an array, then its outermost dimension (i.e., the one corresponding to choices.shape[0]) is taken as defining the “sequence”.

  • mode (‘raise’, ‘wrap’, ‘clip’, optional) –

    Specifies how indices outside [0, n-1] will be treated:

    ‘raise’ – raise an error (default);

    ‘wrap’ – wrap around;

    ‘clip’ – clip to the range. ‘clip’ mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers.

Returns

Tensor, the merged result.

Supported Platforms:

Ascend GPU CPU

Raises

ValueError – if the input tensor and any of the choices cannot be broadcast.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> choices = [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]
>>> x = Tensor(np.array([2, 3, 1, 0]))
>>> print(x.choose(choices))
[20 31 12  3]
clip(xmin, xmax, dtype=None)[source]

Clips (limits) the values in a Tensor.

Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of \([0, 1]\) is specified, values smaller than 0 become 0, and values larger than 1 become 1.

Note

Currently, clip with xmin=nan or xmax=nan is not supported.

Parameters
  • xmin (Tensor, scalar, None) – Minimum value. If None, clipping is not performed on lower interval edge. Not more than one of xmin and xmax may be None.

  • xmax (Tensor, scalar, None) – Maximum value. If None, clipping is not performed on upper interval edge. Not more than one of xmin and xmax may be None. If xmin or xmax are tensors, then the three tensors will be broadcasted to match their shapes.

  • dtype (mindspore.dtype, optional) – Overrides the dtype of the output Tensor. Default is None.

Returns

Tensor, a tensor with the elements of input tensor, but where values < xmin are replaced with xmin, and those > xmax with xmax.

Raises
  • TypeError – If inputs have types not specified above.

  • ValueError – If the shapes of x1 and x2 cannot broadcast, or both xmin and xmax are None.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> x = Tensor([1, 2, 3, -4, 0, 3, 2, 0]).astype("float32")
>>> output = x.clip(0, 2)
>>> print(output)
[1. 2. 2. 0. 0. 2. 2. 0.]
copy()[source]

Return a copy of the tensor.

Note

The current implementation does not support order argument.

Returns

Copied tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.ones((3,3)).astype("float32"))
>>> output = a.copy()
>>> print(output)
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
cumsum(axis=None, dtype=None)[source]

Return the cumulative sum of the elements along a given axis.

Note

If self.dtype is int8, int16 or bool, the result dtype will be elevated to int32, int64 is not supported.

Parameters
  • axis (int, optional) – Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.

  • dtype (mindspore.dtype, optional) – If not specified, stay the same as original, tensor, unless it has an integer dtype with a precision less than float32. In that case, float32 is used. Default: None.

Raises

ValueError – if the axis is out of range.

Returns

Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.ones((3,3)).astype("float32"))
>>> output = a.cumsum(axis=0)
>>> print(output)
[[1. 1. 1.]
[2. 2. 2.]
[3. 3. 3.]]
data_sync(self: mindspore._c_expression.Tensor, arg0: bool) → None
diagonal(offset=0, axis1=0, axis2=1)[source]

Return specified diagonals.

Parameters
  • offset (int, optional) – Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal.

  • axis1 (int, optional) – Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0).

  • axis2 (int, optional) – Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis.

Returns

Tensor, if a is 2-D, then a 1-D array containing the diagonal.

Raises

ValueError – if the input tensor has less than two dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(4).reshape(2, 2))
>>> print(a)
[[0 1]
[2 3]]
>>> output = a.diagonal()
>>> print(output)
[0 3]
dim(self: mindspore._c_expression.Tensor) → int

Get tensor’s data dimension.

Returns

int, the dimension of tensor.

Examples

>>> data = mindspore.Tensor(np.ones((2, 3)))
>>> data.dim()
2
property dtype

Return the dtype of the tensor (mindspore.dtype).

expand_as(x)[source]

Expand the dimension of target tensor to the dimension of input tensor.

Parameters

x (Tensor) – The input tensor. The shape of input tensor must obey the broadcasting rule.

Returns

Tensor, has the same dimension as input tensor.

fill(value)[source]

Fill the array with a scalar value.

Note

Unlike Numpy, tensor.fill() will always returns a new tensor, instead of filling the original tensor.

Parameters

value (Union[None, int, float, bool]) – All elements of a will be assigned this value.

Returns

Tensor, with the original dtype and shape as input tensor.

Raises

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(4).reshape((2,2)).astype('float32'))
>>> print(a.fill(1.0))
[[1. 1.]
[1. 1.]]
flatten(order='C')[source]

Return a copy of the tensor collapsed into one dimension.

Parameters

order (str, optional) – Can choose between ‘C’ and ‘F’. ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran-style) order. Only ‘C’ and ‘F’ are supported. Default: ‘C’.

Returns

Tensor, has the same data type as input.

Supported Platforms:

Ascend GPU CPU

Raises
  • TypeError – If order is not string type.

  • ValueError – If order is string type, but not ‘C’ or ‘F’.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((2,3,4), dtype=np.float32))
>>> output = x.flatten()
>>> print(output.shape)
(24,)
flush_from_cache()[source]

Flush cache data to host if tensor is cache enable.

static from_numpy(array)[source]

Convert numpy array to Tensor without copy data.

Parameters

array (numpy.array) – The input array.

Returns

Tensor, has the same data type as input array.

property has_init

tensor is inited.

init_data(slice_index=None, shape=None, opt_shard_group=None)[source]

Get the tensor format data of this Tensor. The init_data function can be called once for the same tensor.

Parameters
  • slice_index (int) – Slice index of a parameter’s slices. It is used when initialize a slice of a parameter, it guarantees that devices using the same slice can generate the same tensor. Default: None.

  • shape (list[int]) – Shape of the slice, it is used when initialize a slice of the parameter. Default: None.

  • opt_shard_group (str) – Optimizer shard group which is used in auto or semi auto parallel mode to get one shard of a parameter’s slice. Default: None.

Returns

Initialized Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore as ms
>>> import mindspore.common.initializer as init
>>> x = init.initializer(init.Constant(1), [2, 2], ms.float32)
>>> out = x.init_data()
>>> print(out)
[[1. 1.]
 [1. 1.]]
is_init(self: mindspore._c_expression.Tensor) → bool

Get tensor init_flag.

Returns

bool, whether the tensor init.

Examples

>>> data = mindspore.Tensor(np.ones((2, 3)))
>>> data.is_init()
False
item(index=None)[source]

Getitem from the Tensor with the index.

Note

Tensor.item returns a Tensor scalar instead of a Python scalar.

Parameters

index (Union[None, int, tuple(int)]) – The index in Tensor. Default: None.

Returns

A Tensor scalar, dtype is the same with the original Tensor.

Raises

ValueError – If the length of the index is not euqal to self.ndim.

Supported Platforms:

Ascend GPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1,2,3],[4,5,6]], dtype=np.float32))
>>> x = x.item((0,1))
>>> print(x)
2.0
itemset(*args)[source]

Insert scalar into a tensor (scalar is cast to tensor’s dtype, if possible).

There must be at least 1 argument, and define the last argument as item. Then, tensor.itemset(*args) is equivalent to \(tensor[args] = item\).

Parameters

args (Union[(numbers.Number), (int/tuple(int), numbers.Number)]) – The arguments that specify the index and value. If args contain one argument (a scalar), it is only used in case tensor is of size 1. If args contain two arguments, the last argument is the value to be set and must be a scalar, the first argument specifies a single tensor element location. It is either an int or a tuple.

Returns

A new Tensor, with value set by \(tensor[args] = item\).

Raises
  • ValueError – If the length of the first argument is not euqal to self.ndim.

  • IndexError – If only one argument is provided, and the original Tensor is not scalar.

Supported Platforms:

Ascend GPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1,2,3],[4,5,6]], dtype=np.float32))
>>> x = x.itemset((0,1), 4)
>>> print(x)
[[1. 4. 3.]
[4. 5. 6.]]
property itemsize

Return the length of one tensor element in bytes.

max(axis=None, keepdims=False, initial=None, where=True)[source]

Return the maximum of a tensor or maximum along an axis.

Parameters
  • axis (Union[None, int, tuple of ints], optional) – Axis or axes along which to operate. By default, flattened input is used. If this is a tuple of ints, the maximum is selected over multiple axes, instead of a single axis or all the axes as before. Default: None.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Default: False.

  • initial (scalar, optional) – The minimum value of an output element. Must be present to allow computation on empty slice. Default: None.

  • where (bool Tensor, optional) – A boolean array which is broadcasted to match the dimensions of array, and selects elements to include in the reduction. If non-default value is passed, initial must also be provided. Default: True.

Returns

Tensor or scalar, maximum of input tensor. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension self.ndim - 1.

Raises

TypeError – if arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(4).reshape((2, 2)).astype('float32'))
>>> output = a.max()
>>> print(output)
3.0
mean(axis=(), keep_dims=False)[source]

Reduce a dimension of a tensor by averaging all elements in the dimension.

Parameters
  • axis (Union[None, int, tuple(int), list(int)]) – Dimensions of reduction, when the axis is None or empty tuple, reduce all dimensions. Default: ().

  • keep_dims (bool) – Whether to keep the reduced dimensions. Default: False.

Returns

Tensor, has the same data type as input tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1, 2, 3], dtype=np.float32))
>>> output = input_x.mean()
>>> print(output)
2.0
min(axis=None, keepdims=False, initial=None, where=True)[source]

Return the minimum of a tensor or minimum along an axis.

Parameters
  • axis (Union[None, int, tuple of ints], optional) – Axis or axes along which to operate. By default, flattened input is used. If this is a tuple of ints, the minimum is selected over multiple axes, instead of a single axis or all the axes as before. Default: None.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Default: False.

  • initial (scalar, optional) – The maximum value of an output element. Must be present to allow computation on empty slice. Default: None.

  • where (bool Tensor, optional) – A boolean array which is broadcasted to match the dimensions of array, and selects elements to include in the reduction. If non-default value is passed, initial must also be provided. Default: True.

Returns

Tensor or scalar, minimum of input tensor. If the axis is None, the result is a scalar value. If axis is given, the result is an array of dimension self.ndim - 1.

Raises

TypeError – if arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> import mindspore.numpy as np
>>> a = Tensor(np.arange(4).reshape((2,2)).astype('float32'))
>>> output = a.min()
>>> print(output)
0.0
property nbytes

Return the total number of bytes taken by the tensor.

property ndim

Return the number of tensor dimensions.

ptp(axis=None, keepdims=False)[source]

The name of the function comes from the acronym for ‘peak to peak’.

Note

Numpy arguments dtype and out are not supported.

Parameters
  • axis (Union[None, int, tuple(int)]) – Axis or axes along which the range is computed. The default is to compute the variance of the flattened array. Default: None.

  • keepdims (bool) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. Default is False.

Returns

Tensor.

Raises

TypeError – if self is not a tensor, or axis and keepdims have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> x = Tensor([[4.0, 9.0, 2.0, 10.0], [6.0, 9.0, 7.0, 12.0]]).astype("float32")
>>> print(x.ptp(axis=1))
[8. 6.]
>>> print(x.ptp(axis=0))
[2. 0. 5. 2.]
ravel()[source]

Return a contiguous flattened tensor.

Returns

Tensor, a 1-D tensor, containing the same elements of the input.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((2,3,4), dtype=np.float32))
>>> output = x.ravel()
>>> print(output.shape)
(24,)
repeat(repeats, axis=None)[source]

Repeat elements of an array.

Parameters
  • repeats (Union[int, tuple, list]) – The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.

  • axis (int, optional) – The axis along which to repeat values. By default, use the flattened input tensor, and return a flat output tensor.

Returns

Tensor, has the same shape as input tensor except along the given axis.

Raises
  • ValueError – if the axis is out of range.

  • TypeError – if arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array(3))
>>> print(x.repeat(4))
[3 3 3 3]
>>> x = Tensor(np.array([[1, 2],[3, 4]]))
>>> print(x.repeat(2))
[1 1 2 2 3 3 4 4]
>>> print(x.repeat(3, axis=1))
[[1 1 1 2 2 2]
[3 3 3 4 4 4]]
>>> print(x.repeat([1,2], axis=0))
[[1 2]
[3 4]
[3 4]]
reshape(*shape)[source]

Give a new shape to a tensor without changing its data.

Parameters

shape (Union[int, tuple(int), list(int)]) – The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

Returns

Tensor, with new specified shape.

Raises
  • TypeError – If new_shape is not integer, list or tuple, or x is not tensor.

  • ValueError – If new_shape is not compatible with the original shape.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor
>>> from mindspore import dtype as mstype
>>> x = Tensor([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]], dtype=mstype.float32)
>>> output = x.reshape((3, 2))
>>> print(output)
[[-0.1  0.3]
[ 3.6  0.4]
[ 0.5 -3.2]]
resize(*new_shape)[source]

Changes shape and size of array in-place.

Note

Instead of changing the size of the input array and returns nothing as in numpy, this method returns a new Tensor with the input size. Numpy argument refcheck is not supported.

Parameters

new_shape (Union[ints, tuple of ints]) – Shape of resized array.

Returns

Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[0, 1], [2, 3]]))
>>> x = x.resize(2, 3)
>>> print(x)
[[0 1 2]
[3 0 0]]
searchsorted(v, side='left', sorter=None)[source]

Finds indices where elements should be inserted to maintain order.

Parameters
  • v (Union[int, float, bool, list, tuple, Tensor]) – Values to insert into a.

  • side ('left', 'right', optional) – If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a). Default: left.

  • sorter (Union[int, float, bool, list, tuple, Tensor]) – 1-D optional array of integer indices that sort array a into ascending order. They are typically the result of argsort.

Returns

Tensor, array of insertion points with the same shape as v.

Raises

ValueError – if argument for side or sorter is invalid.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([1, 2, 3, 4, 5]))
>>> print(x.searchsorted(3))
2
set_cast_dtype(self: mindspore._c_expression.Tensor, dtype: mindspore::Type = None) → None
set_dtype(self: mindspore._c_expression.Tensor, arg0: mindspore::Type) → mindspore::Type

Set the tensor’s data type.

Arg:

dtype (mindspore.dtype): The type of output tensor.

Examples

>>> data = mindspore.Tensor(np.ones((1, 2), np.float32))
>>> data.set_dtype(mindspore.int32)
mindspore.int32
set_init_flag(self: mindspore._c_expression.Tensor, arg0: bool) → None

Set tensor init_flag.

Examples

>>> data = mindspore.Tensor(np.ones((2, 3)))
>>> data.set_init_flag(True)
property shape

Returns the shape of the tensor as a tuple.

property size

Returns the total number of elements in tensor.

squeeze(axis=None)[source]

Remove single-dimensional entries from the shape of a tensor.

Parameters

axis (Union[None, int, list(int), tuple(int)], optional) – Selects a subset of the entries of length one in the shape. If an axis is selected with shape entry greater than one, an error is raised. Default is None.

Returns

Tensor, with all or a subset of the dimensions of length 1 removed.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If specified axis has shape entry \(> 1\).

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((1,2,2,1), dtype=np.float32))
>>> x = x.squeeze()
>>> print(x.shape)
(2, 2)
std(axis=None, ddof=0, keepdims=False)[source]

Compute the standard deviation along the specified axis. The standard deviation is the square root of the average of the squared deviations from the mean, i.e., \(std = sqrt(mean(abs(x - x.mean())**2))\).

Return the standard deviation, which is computed for the flattened array by default, otherwise over the specified axis.

Note

Numpy arguments dtype, out and where are not supported.

Parameters
  • axis (Union[None, int, tuple(int)]) –

    Axis or axes along which the standard deviation is computed. Default: None.

    If None, compute the standard deviation of the flattened array.

  • ddof (int) – Means Delta Degrees of Freedom. The divisor used in calculations is \(N - ddof\), where \(N\) represents the number of elements. Default: 0.

  • keepdims – Default: False.

Returns

Standard deviation tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1, 2, 3, 4], dtype=np.float32))
>>> output = input_x.std()
>>> print(output)
1.118034
property strides

Return the tuple of bytes to step in each dimension when traversing a tensor.

sum(axis=None, dtype=None, keepdims=False, initial=None)[source]

Return sum of array elements over a given axis.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • axis (Union[None, int, tuple(int)]) – Axis or axes along which a sum is performed. Default: None. If None, sum all of the elements of the input array. If the axis is negative, it counts from the last to the first axis. If the axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

  • keepdims (bool) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised. Default: False.

  • initial (scalar) – Starting value for the sum. Default: None.

Returns

Tensor. A tensor with the same shape as input, with the specified axis removed. If input tensor is a 0-d array, or if the axis is None, a scalar is returned.

Raises
  • TypeError – If input is not array_like, or axis is not int or tuple of ints, or keepdims is not integer, or initial is not scalar.

  • ValueError – If any axis is out of range or duplicate axes exist.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([-1, 0, 1]).astype(np.float32))
>>> print(input_x.sum())
0.0
>>> input_x = Tensor(np.arange(10).reshape(2, 5).astype(np.float32))
>>> print(input_x.sum(axis=1))
[10. 35.]
swapaxes(axis1, axis2)[source]

Interchange two axes of a tensor.

Parameters
  • axis1 (int) – First axis.

  • axis2 (int) – Second axis.

Returns

Transposed tensor, has the same data type as the input.

Raises
  • TypeError – If axis1 or axis2 is not integer.

  • ValueError – If axis1 or axis2 is not in the range of \([-ndim, ndim-1]\).

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((2,3,4), dtype=np.float32))
>>> output = x.swapaxes(0, 2)
>>> print(output.shape)
(4,3,2)
take(indices, axis=None, mode='clip')[source]

Takes elements from an array along an axis.

Parameters
  • indices (Tensor) – The indices with shape (Nj…) of the values to extract.

  • axis (int, optional) – The axis over which to select values. By default, the flattened input array is used. Default: None.

  • mode (‘raise’, ‘wrap’, ‘clip’, optional) –

    • edge: Pads with the edge values of arr.

    • raise: Raises an error;

    • wrap: Wraps around;

    • clip: Clips to the range. clip mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers.

    Default: clip.

Returns

Tensor, the indexed result.

Raises

ValueError – if axis is out of range, or mode has values other than (‘raise’, ‘wrap’, ‘clip’)

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.array([4, 3, 5, 7, 6, 8]))
>>> indices = Tensor(np.array([0, 1, 4]))
>>> output = a.take(indices)
>>> print(output)
[4 3 6]
to_tensor(slice_index=None, shape=None, opt_shard_group=None)[source]

Return init_data() and get the tensor format data of this Tensor.

Note

The usage of to_tensor is deprecated. Please use init_data.

Parameters
  • slice_index (int) – Slice index of a parameter’s slices. It is used when initialize a slice of a parameter, it guarantees that devices using the same slice can generate the same tensor. Default: None.

  • shape (list[int]) – Shape of the slice, it is used when initialize a slice of the parameter. Default: None.

  • opt_shard_group (str) – Optimizer shard group which is used in auto or semi auto parallel mode to get one shard of a parameter’s slice. Default: None.

Returns

Initialized Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore as ms
>>> import mindspore.common.initializer as init
>>> x = init.initializer(init.Constant(1), [2, 2], ms.float32)
>>> out = x.to_tensor()
>>> print(out)
[[1. 1.]
 [1. 1.]]
trace(offset=0, axis1=0, axis2=1, dtype=None)[source]

Return the sum along diagonals of the array.

Parameters
  • offset (int, optional) – Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal.

  • axis1 (int, optional) – Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0).

  • axis2 (int, optional) – Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor, sum_along_diagonals.

Raises

ValueError – if the input tensor has less than two dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.eye(3, dtype=np.float32))
>>> print(x.trace())
3.0
transpose(*axes)[source]

Return a view of the tensor with axes transposed.

  • For a 1-D tensor this has no effect, as a transposed vector is simply the same vector.

  • For a 2-D tensor, this is a standard matrix transpose.

  • For an n-D tensor, if axes are given, their order indicates how the axes are permuted.

If axes are not provided and tensor.shape = (i[0], i[1],...i[n-2], i[n-1]), then tensor.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]).

Parameters

axes (Union[None, tuple(int), list(int), int], optional) – If axes is None or blank, the method will reverse the order of the axes. If axes is tuple(int) or list(int), tensor.transpose() will transpose the tensor to the new axes order. If axes is int, this form is simply intended as a convenience alternative to the tuple/list form.

Returns

Tensor, has the same dimension as input tensor, with axes suitably permuted.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If the number of axes is not euqal to a.ndim.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((1,2,3), dtype=np.float32))
>>> x = x.transpose()
>>> print(x.shape)
(3, 2, 1)
var(axis=None, ddof=0, keepdims=False)[source]

Compute the variance along the specified axis.

The variance is the average of the squared deviations from the mean, i.e., \(var = mean(abs(x - x.mean())**2)\).

Return the variance, which is computed for the flattened array by default, otherwise over the specified axis.

Note

Numpy arguments dtype, out and where are not supported.

Parameters
  • axis (Union[None, int, tuple(int)]) – Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array. Default: None.

  • ddof (int) – Means Delta Degrees of Freedom. Default: 0. The divisor used in calculations is \(N - ddof\), where \(N\) represents the number of elements.

  • keepdims (bool) – Default: False.

Supported Platforms:

Ascend GPU CPU

Returns

Standard deviation tensor.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1., 2., 3., 4.], np.float32))
>>> output = input_x.var()
>>> print(output)
1.25
view(*shape)[source]

Reshape the tensor according to the input shape.

Parameters

shape (Union[tuple(int), int]) – Dimension of the output tensor.

Returns

Tensor, has the same dimension as the input shape.

property virtual_flag

Used to mark whether the tensor is virtual. If the tensor is virtual, return True.

class tinyms.RowTensor(indices, values, dense_shape)[source]

A sparse representation of a set of tensor slices at given indices.

An RowTensor is typically used to represent a subset of a larger tensor dense of shape [L0, D1, .. , DN] where L0 >> D0.

The values in indices are the indices in the first dimension of the slices that have been extracted from the larger tensor.

The dense tensor dense represented by an RowTensor slices has dense[slices.indices[i], :, :, :, …] = slices.values[i, :, :, :, …].

RowTensor can only be used in the Cell’s construct method.

It is not supported in pynative mode at the moment.

Parameters
  • indices (Tensor) – A 1-D integer Tensor of shape [D0].

  • values (Tensor) – A Tensor of any dtype of shape [D0, D1, …, Dn].

  • dense_shape (tuple(int)) – An integer tuple which contains the shape of the corresponding dense tensor.

Returns

RowTensor, composed of indices, values, and dense_shape.

Examples

>>> import mindspore as ms
>>> import mindspore.nn as nn
>>> from mindspore import RowTensor
>>> class Net(nn.Cell):
...     def __init__(self, dense_shape):
...         super(Net, self).__init__()
...         self.dense_shape = dense_shape
...     def construct(self, indices, values):
...         x = RowTensor(indices, values, self.dense_shape)
...         return x.values, x.indices, x.dense_shape
>>>
>>> indices = Tensor([0])
>>> values = Tensor([[1, 2]], dtype=ms.float32)
>>> out = Net((3, 2))(indices, values)
>>> print(out[0])
[[1. 2.]]
>>> print(out[1])
[0]
>>> print(out[2])
(3, 2)
class tinyms.SparseTensor(indices, values, dense_shape)[source]

A sparse representation of a set of nonzero elememts from a tensor at given indices.

SparseTensor can only be used in the Cell’s construct method.

Pynative mode not supported at the moment.

For a tensor dense, its SparseTensor(indices, values, dense_shape) has dense[indices[i]] = values[i].

Parameters
  • indices (Tensor) – A 2-D integer Tensor of shape [N, ndims], where N and ndims are the number of values and number of dimensions in the SparseTensor, respectively.

  • values (Tensor) – A 1-D tensor of any type and shape [N], which supplies the values for each element in indices.

  • dense_shape (tuple(int)) – A integer tuple of size ndims, which specifies the dense_shape of the sparse tensor.

Returns

SparseTensor, composed of indices, values, and dense_shape.

Examples

>>> import mindspore as ms
>>> import mindspore.nn as nn
>>> from mindspore import SparseTensor
>>> class Net(nn.Cell):
...     def __init__(self, dense_shape):
...         super(Net, self).__init__()
...         self.dense_shape = dense_shape
...     def construct(self, indices, values):
...         x = SparseTensor(indices, values, self.dense_shape)
...         return x.values, x.indices, x.dense_shape
>>>
>>> indices = Tensor([[0, 1], [1, 2]])
>>> values = Tensor([1, 2], dtype=ms.float32)
>>> out = Net((3, 4))(indices, values)
>>> print(out[0])
[1. 2.]
>>> print(out[1])
[[0 1]
 [1 2]]
>>> print(out[2])
(3, 4)
tinyms.ms_function(fn=None, obj=None, input_signature=None)[source]

Create a callable MindSpore graph from a Python function.

This allows the MindSpore runtime to apply optimizations based on graph.

Parameters
  • fn (Function) – The Python function that will be run as a graph. Default: None.

  • obj (Object) – The Python object is used to distinguish the compiled function. Default: None.

  • input_signature (Tensor) – The Tensor which describes the input arguments. The shape and dtype of the Tensor will be supplied to this function. If input_signature is specified, each input to fn must be a Tensor. And the input parameters of fn cannot accept **kwargs. The shape and dtype of actual inputs should keep the same as input_signature. Otherwise, TypeError will be raised. Default: None.

Returns

Function, if fn is not None, returns a callable function that will execute the compiled function; If fn is None, returns a decorator and when this decorator invokes with a single fn argument, the callable function is equal to the case when fn is not None.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> from mindspore import ms_function
...
>>> x = Tensor(np.ones([1, 1, 3, 3]).astype(np.float32))
>>> y = Tensor(np.ones([1, 1, 3, 3]).astype(np.float32))
...
>>> # create a callable MindSpore graph by calling ms_function
>>> def tensor_add(x, y):
...     z = x + y
...     return z
...
>>> tensor_add_graph = ms_function(fn=tensor_add)
>>> out = tensor_add_graph(x, y)
...
>>> # create a callable MindSpore graph through decorator @ms_function
>>> @ms_function
... def tensor_add_with_dec(x, y):
...     z = x + y
...     return z
...
>>> out = tensor_add_with_dec(x, y)
...
>>> # create a callable MindSpore graph through decorator @ms_function with input_signature parameter
>>> @ms_function(input_signature=(Tensor(np.ones([1, 1, 3, 3]).astype(np.float32)),
...                               Tensor(np.ones([1, 1, 3, 3]).astype(np.float32))))
... def tensor_add_with_sig(x, y):
...     z = x + y
...     return z
...
>>> out = tensor_add_with_sig(x, y)
class tinyms.Parameter(default_input, name=None, requires_grad=True, layerwise_parallel=False, parallel_optimizer=True)[source]

An object holding weights of cells, after initialized Parameter is a subtype of Tensor.

Note

In auto_parallel mode of “semi_auto_parallel” and “auto_parallel”, if init Parameter by a Tensor, the type of Parameter will be Tensor. Tensor will save the shape and type info of a tensor with no memory usage. The shape can be changed while compiling for auto-parallel. Call init_data will return a Tensor Parameter with initialized data. If there is an operator in the network that requires part of the inputs to be Parameter, then the Parameters as this part of the inputs are not allowed to be cast. It is recommended to use the default value of name when initialize a parameter as one attribute of a cell, otherwise, the parameter name may be different from expected.

Parameters
  • default_input (Union[Tensor, int, float, numpy.ndarray, list]) – Parameter data, to initialize the parameter data.

  • name (str) – Name of the child parameter. Default: None.

  • requires_grad (bool) – True if the parameter requires gradient. Default: True.

  • layerwise_parallel (bool) – When layerwise_parallel is true in data/hybrid parallel mode, broadcast and gradients communication would not be applied to parameters. Default: False.

  • parallel_optimizer (bool) – It is used to filter the weight shard operation in semi auto or auto parallel mode. It works only when enable parallel optimizer in mindspore.context.set_auto_parallel_context(). Default: True.

Examples

>>> import numpy as np
>>> from mindspore import Parameter, Tensor
>>> import mindspore.ops as ops
>>> import mindspore.nn as nn
>>> import mindspore
>>>
>>> class Net(nn.Cell):
...     def __init__(self):
...         super(Net, self).__init__()
...         self.matmul = ops.MatMul()
...         self.weight = Parameter(Tensor(np.ones((1, 2)), mindspore.float32), name="w", requires_grad=True)
...
...     def construct(self, x):
...         out = self.matmul(self.weight, x)
...         return out
>>> net = Net()
>>> x = Tensor(np.ones((2, 1)), mindspore.float32)
>>> print(net(x))
[[2.]]
>>> net.weight.set_data(Tensor(np.zeros((1, 2)), mindspore.float32))
>>> print(net(x))
[[0.]]
asnumpy(self: mindspore._c_expression.Tensor) → array

Convert tensor to numpy.ndarray.

Returns

numpy.ndarray.

Examples

>>> data = mindspore.Tensor(np.ones((2, 3)))
>>> array = data.asnumpy()
>>> array
array([[1., 1., 1.],
       [1., 1., 1.]])
assign_value_cpp(self: mindspore._c_expression.Tensor, arg0: mindspore._c_expression.Tensor) → mindspore._c_expression.Tensor

Assign another tensor value to this.

Arg:

value (mindspore.tensor): The value tensor.

Examples

>>> data = mindspore.Tensor(np.ones((1, 2), np.float32))
>>> data2 = mindspore.Tensor(np.ones((2, 2), np.float32))
>>> data.assign_value(data2)
>>> data.shape
(2, 2)
property cache_enable

Return whether the parameter is cache enable.

property cache_shape

Return the cache shape corresponding to the parameter if use cache.

clone(init='same')[source]

Clone the parameter.

Parameters

init (Union[Tensor, str, numbers.Number]) – Initialize the shape and dtype of the parameter. If init is a Tensor or numbers.Number, clone a new parameter with the same shape and dtype, and the data of the new parameter will be set according to init. If init is a str, the init should be the alias of the class inheriting from Initializer. For example, if init is ‘same’, clone a new parameter with the same data, shape, and dtype. Default: ‘same’.

Returns

Parameter, a new parameter.

property comm_fusion

Get and set the fusion type (int) for communication operators corresponding to this parameter.

In AUTO_PARALLEL and SEMI_AUTO_PARALLEL mode, some communication operators used for parameters or gradients aggregation are inserted automatically. Set the fusion type for communication operators generated for this parameter. The value of fusion must be greater than or equal to 0. When the value of fusion is 0, operators will not be fused together.

Only support in Ascend environment with Graph mode.

property data

Return the parameter object.

data_sync(self: mindspore._c_expression.Tensor, arg0: bool) → None
dim(self: mindspore._c_expression.Tensor) → int

Get tensor’s data dimension.

Returns

int, the dimension of tensor.

Examples

>>> data = mindspore.Tensor(np.ones((2, 3)))
>>> data.dim()
2
property dtype

Get the MetaTensor’s dtype.

from_numpy(self: array) → mindspore._c_expression.Tensor

Creates a Tensor from a numpy.ndarray without copy.

Arg:

array (numpy.ndarray): The input ndarray.

Returns

Tensor, tensor with shared data to input ndarray.

Examples

>>> a = np.ones((2, 3))
>>> t = mindspore.Tensor.from_numpy(a)
init_data(layout=None, set_sliced=False)[source]

Initialize the parameter’s data.

Parameters
  • layout (Union[None, tuple(list(int))]) –

    Parameter slice layout [dev_mat, tensor_map, slice_shape]. Default: None.

    • dev_mat (list(int)): Device matrix.

    • tensor_map (list(int)): Tensor map.

    • slice_shape (list(int)): Shape of slice.

  • set_sliced (bool) – True if the parameter is set sliced after initializing the data. Default: False.

Raises
  • RuntimeError – If it is from Initializer, and parallel mode has changed after the Initializer created.

  • ValueError – If the length of the layout is less than 3.

  • TypeError – If layout is not tuple.

Returns

Parameter, the Parameter after initializing data. If current Parameter was already initialized before, returns the same initialized Parameter.

property inited_param

Get the new parameter after call the init_data.

Default is a None, If self is a Parameter without data, after call the init_data the initialized Parameter with data will be recorded here.

property is_init

Get the initialization status of the parameter.

This flag only work in GE, and it will be set to False in other backend.

property layerwise_parallel

When layerwise_parallel is true in data/hybrid parallel mode, broadcast and gradients communication would not be applied to parameters.

property name

Get the name of the parameter.

property parallel_optimizer

It is used to filter the weight shard operation in semi auto or auto parallel mode. It works only when enable parallel optimizer in mindspore.context.set_auto_parallel_context().

property parallel_optimizer_comm_recompute

Get and Set the whether do recompute for communication operators corresponding to this parameter when applying parallel optimizer.

In AUTO_PARALLEL and SEMI_AUTO_PARALLEL mode, when applying parallel optimizer, some all_gather operators used for parameters gathering are inserted automatically. The interface is used to control the recompute attr for those all_gather operators.

Note

  • Only Ascend and Graph mode is supported.

  • It is recommended to use cell.recompute(parallel_optimizer_comm_recompute=True/False) to configure the all_gather operators introducing by parallel optimizer rather than using this interface directly.

property requires_grad

Return whether the parameter requires gradient.

set_cast_dtype(self: mindspore._c_expression.Tensor, dtype: mindspore::Type = None) → None
set_data(data, slice_shape=False)[source]

Set Parameter’s data.

Parameters
  • data (Union[Tensor, int, float]) – new data.

  • slice_shape (bool) – If slice the parameter is set to true, the shape is not checked for consistency. Default: False.

Returns

Parameter, the parameter after set data.

set_dtype(self: mindspore._c_expression.Tensor, arg0: mindspore::Type) → mindspore::Type

Set the tensor’s data type.

Arg:

dtype (mindspore.dtype): The type of output tensor.

Examples

>>> data = mindspore.Tensor(np.ones((1, 2), np.float32))
>>> data.set_dtype(mindspore.int32)
mindspore.int32
set_init_flag(self: mindspore._c_expression.Tensor, arg0: bool) → None

Set tensor init_flag.

Examples

>>> data = mindspore.Tensor(np.ones((2, 3)))
>>> data.set_init_flag(True)
set_param_fl(push_to_server=False, pull_from_server=False, requires_aggr=True)[source]

Set the way of parameter and server interaction.

Parameters
  • push_to_server (bool) – Whether the parameter should be pushed to server. Default: False.

  • pull_from_server (bool) – Whether the parameter should be pulled from server. Default: False.

  • requires_aggr (bool) – Whether the parameter should be aggregated in the server. Default: True.

set_param_ps(init_in_server=False)[source]

Set whether the trainable parameter is updated by parameter server and whether the trainable parameter is initialized on server.

Note

It only works when a running task is in the parameter server mode.

Parameters

init_in_server (bool) – Whether trainable parameter updated by parameter server is initialized on server. Default: False.

property shape

Get the MetaTensor’s shape.

property sliced

Get slice status of the parameter.

property unique

whether the parameter is already unique or not.

class tinyms.ParameterTuple[source]

Class for storing tuple of parameters.

Note

It is used to store the parameters of the network into the parameter tuple collection.

clone(prefix, init='same')[source]

Clone the parameters in ParameterTuple element-wisely to generate a new ParameterTuple.

Parameters
  • prefix (str) – Namespace of parameter.

  • init (Union[Tensor, str, numbers.Number]) – Initialize the shape and dtype of the parameters. The definition of init is the same as in Parameter API. If init is ‘same’, the parameters in the new parameter tuple are the same as those in the original parameter tuple. Default: ‘same’.

Raises

RuntimeError – If parameter’s name is not end with embedding_table.

Returns

Tuple, the new Parameter tuple.

count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

tinyms.set_seed(seed)[source]

Set global seed.

Note

The global seed is used by numpy.random, mindspore.common.Initializer, mindspore.ops.composite.random_ops and mindspore.nn.probability.distribution.

If global seed is not set, these packages will use their own default seed independently, numpy.random and mindspore.common.Initializer will choose a random seed, mindspore.ops.composite.random_ops and mindspore.nn.probability.distribution will use zero.

Seed set by numpy.random.seed() only used by numpy.random, while seed set by this API will also used by numpy.random, so just set all seed by this API is recommended.

Parameters

seed (int) – The seed to be set.

Raises

Examples

>>> import numpy as np
>>> import mindspore.ops as ops
>>> from mindspore import Tensor, set_seed, Parameter
>>> from mindspore.common.initializer import initializer
>>>
>>> # Note: (1) Please make sure the code is running in PYNATIVE MODE;
>>> # (2) Because Composite-level ops need parameters to be Tensors, for below examples,
>>> # when using ops.uniform operator, minval and maxval are initialised as:
>>> minval = Tensor(1.0, ms.float32)
>>> maxval = Tensor(2.0, ms.float32)
>>>
>>> # 1. If global seed is not set, numpy.random and initializer will choose a random seed:
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A1
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A2
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W1
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W2
>>> # Rerun the program will get different results:
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A3
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A4
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W3
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W4
>>>
>>> # 2. If global seed is set, numpy.random and initializer will use it:
>>> set_seed(1234)
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A1
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A2
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W1
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W2
>>> # Rerun the program will get the same results:
>>> set_seed(1234)
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A1
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A2
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W1
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W2
>>>
>>> # 3. If neither global seed nor op seed is set, mindspore.ops.composite.random_ops and
>>> # mindspore.nn.probability.distribution will choose a random seed:
>>> c1 = ops.uniform((1, 4), minval, maxval) # C1
>>> c2 = ops.uniform((1, 4), minval, maxval) # C2
>>> # Rerun the program will get different results:
>>> c1 = ops.uniform((1, 4), minval, maxval) # C3
>>> c2 = ops.uniform((1, 4), minval, maxval) # C4
>>>
>>> # 4. If global seed is set, but op seed is not set, mindspore.ops.composite.random_ops and
>>> # mindspore.nn.probability.distribution will calculate a seed according to global seed and
>>> # default op seed. Each call will change the default op seed, thus each call get different
>>> # results.
>>> set_seed(1234)
>>> c1 = ops.uniform((1, 4), minval, maxval) # C1
>>> c2 = ops.uniform((1, 4), minval, maxval) # C2
>>> # Rerun the program will get the same results:
>>> set_seed(1234)
>>> c1 = ops.uniform((1, 4), minval, maxval) # C1
>>> c2 = ops.uniform((1, 4), minval, maxval) # C2
>>>
>>> # 5. If both global seed and op seed are set, mindspore.ops.composite.random_ops and
>>> # mindspore.nn.probability.distribution will calculate a seed according to global seed and
>>> # op seed counter. Each call will change the op seed counter, thus each call get different
>>> # results.
>>> set_seed(1234)
>>> c1 = ops.uniform((1, 4), minval, maxval, seed=2) # C1
>>> c2 = ops.uniform((1, 4), minval, maxval, seed=2) # C2
>>> # Rerun the program will get the same results:
>>> set_seed(1234)
>>> c1 = ops.uniform((1, 4), minval, maxval, seed=2) # C1
>>> c2 = ops.uniform((1, 4), minval, maxval, seed=2) # C2
>>>
>>> # 6. If op seed is set but global seed is not set, 0 will be used as global seed. Then
>>> # mindspore.ops.composite.random_ops and mindspore.nn.probability.distribution act as in
>>> # condition 5.
>>> c1 = ops.uniform((1, 4), minval, maxval, seed=2) # C1
>>> c2 = ops.uniform((1, 4), minval, maxval, seed=2) # C2
>>> # Rerun the program will get the same results:
>>> c1 = ops.uniform((1, 4), minval, maxval, seed=2) # C1
>>> c2 = ops.uniform((1, 4), minval, maxval, seed=2) # C2
>>>
>>> # 7. Recall set_seed() in the program will reset numpy seed and op seed counter of
>>> # mindspore.ops.composite.random_ops and mindspore.nn.probability.distribution.
>>> set_seed(1234)
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A1
>>> c1 = ops.uniform((1, 4), minval, maxval, seed=2) # C1
>>> set_seed(1234)
>>> np_2 = np.random.normal(0, 1, [1]).astype(np.float32) # still get A1
>>> c2 = ops.uniform((1, 4), minval, maxval, seed=2) # still get C1
tinyms.get_seed()[source]

Get global seed.

Returns

Integer. The global seed.

tinyms.abs(x, dtype=None)

Calculates the absolute value element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. Currently the backend kernel only supports float calculation, if the input is not a float, then it will be casted to mstype.float32 and casted back.

Parameters
  • x (Tensor) – Tensor to be used for calculation.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor.

Raises

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.asarray([1, 2, 3, -4, -5], np.float32)
>>> output = np.absolute(x)
>>> print(output)
[1. 2. 3. 4. 5.]
tinyms.absolute(x, dtype=None)[source]

Calculates the absolute value element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. Currently the backend kernel only supports float calculation, if the input is not a float, then it will be casted to mstype.float32 and casted back.

Parameters
  • x (Tensor) – Tensor to be used for calculation.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor.

Raises

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.asarray([1, 2, 3, -4, -5], np.float32)
>>> output = np.absolute(x)
>>> print(output)
[1. 2. 3. 4. 5.]
tinyms.add(x1, x2, dtype=None)[source]

Adds arguments element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – input to be added.

  • x2 (Tensor) – input to be added.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the sum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.full((3, 2), [1, 2])
>>> x2 = np.full((3, 2), [3, 4])
>>> output = np.add(x1, x2)
>>> print(output)
[[4 6]
[4 6]
[4 6]]
tinyms.amax(a, axis=None, keepdims=False, initial=None, where=True)[source]

Returns the maximum of an array or maximum along an axis.

Note

Numpy argument out is not supported. On GPU, the supported dtypes are np.float16, and np.float32.

Parameters
  • a (Tensor) – Input data.

  • axis (None or int or tuple of integers, optional) – defaults to None. Axis or axes along which to operate. By default, flattened input is used. If this is a tuple of integers, the maximum is selected over multiple axes, instead of a single axis or all the axes as before.

  • keepdims (boolean, optional) – defaults to False. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

  • initial (scalar, optional) – defaults to None. The minimum value of an output element. Must be present to allow computation on empty slice.

  • where (boolean Tensor, optional) – defaults to True. A boolean array which is broadcasted to match the dimensions of array, and selects elements to include in the reduction. If non-default value is passed, initial must also be provided.

Returns

Tensor or scalar, maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.arange(4).reshape((2,2)).astype('float32')
>>> output = np.amax(a)
>>> print(output)
3.0
>>> output = np.amax(a, axis=0)
>>> print(output)
[2. 3.]
>>> output = np.amax(a, axis=1)
>>> print(output)
[1. 3.]
>>> output = np.amax(a, where=np.array([False, True]), initial=-1, axis=0)
>>> print(output)
[-1.  3.]
tinyms.amin(a, axis=None, keepdims=False, initial=None, where=True)[source]

Returns the minimum of an array or minimum along an axis.

Note

Numpy argument out is not supported. On GPU, the supported dtypes are np.float16, and np.float32.

Parameters
  • a (Tensor) – Input data.

  • axis (None or int or tuple of integers, optional) – defaults to None. Axis or axes along which to operate. By default, flattened input is used. If this is a tuple of integers, the minimum is selected over multiple axes, instead of a single axis or all the axes as before.

  • keepdims (bool, optional) – defaults to False. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

  • initial (Number, optional) – defaults to None. The maximum value of an output element. Must be present to allow computation on empty slice.

  • where (bool Tensor, optional) – defaults to True. A boolean array which is broadcasted to match the dimensions of array, and selects elements to include in the reduction. If non-default value is passed, initial must also be provided.

Returns

Tensor or scalar, minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.arange(4).reshape((2,2)).astype('float32')
>>> output = np.amin(a)
>>> print(output)
0.0
>>> output = np.amin(a, axis=0)
>>> print(output)
[0. 1.]
>>> output = np.amin(a, axis=1)
>>> print(output)
[0. 2.]
>>> output = np.amin(a, where=np.array([False, True]), initial=10, axis=0)
>>> print(output)
[10.  1.]
tinyms.append(arr, values, axis=None)[source]

Appends values to the end of a tensor.

Parameters
  • arr (Tensor) – Values are appended to a copy of this tensor.

  • values (Tensor) – These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis). If axis is not specified, values can be any shape and will be flattened before use.

  • axis (None, int, optional) – The axis along which values are appended. If axis is not given, both arr and values are flattened before use, default is None.

Returns

Tensor, a copy of tensor with values appended to axis.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If specified axis exceeds arr.ndim.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.ones((2, 3))
>>> b = np.ones((2, 1))
>>> print(np.append(a, b, axis=1).shape)
(2, 4)
tinyms.apply_along_axis(func1d, axis, arr, *args, **kwargs)[source]

Applies a function to 1-D slices along the given axis. Executes func1d(a, *args, **kwargs) where func1d operates on 1-D arrays and a is a 1-D slice of arr along axis.

Parameters
  • func1d (function) – Maps (M,) -> (Nj…). This function should accept 1-D arrays. It is applied to 1-D slices of arr along the specified axis.

  • axis (int) – Axis along which arr is sliced.

  • arr (Tensor) – Input array with shape (Ni…, M, Nk…).

  • args (any) – Additional arguments to func1d.

  • kwargs (any) – Additional named arguments to func1d.

Returns

Tensor with shape (Ni…, Nj…, Nk…), the output array. Its shape is identical to the shape of arr, except along the axis dimension. This axis is removed, and replaced with new dimensions equal to the shape of the return value of func1d. So if func1d returns a scalar, the output will have one fewer dimensions than arr.

Supported Platforms:

Ascend GPU CPU

Raises

ValueError – if axis is out of the range.

Examples

>>> import mindspore.numpy as np
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> print(np.apply_along_axis(np.diag, -1, b))
[[[1 0 0]
[0 2 0]
[0 0 3]]
[[4 0 0]
[0 5 0]
[0 0 6]]
[[7 0 0]
[0 8 0]
[0 0 9]]]
tinyms.apply_over_axes(func, a, axes)[source]

Applies a function repeatedly over multiple axes.

func is called as res = func(a, axis), where axis is the first element of axes. The result res of the function call must have either the same dimensions as a or one less dimension. If res has one less dimension than a, a dimension is inserted before axis. The call to func is then repeated for each axis in axes, with res as the first argument.

Parameters
  • func (function) – This function must take two arguments, func(a, axis).

  • a (Union[int, float, bool, list, tuple, Tensor]) – Input tensor.

  • axes (Union[int, list, tuple]) – Axes over which func is applied; the elements must be integers.

Returns

Tensor. The number of dimensions is the same as a, but the shape can be different. This depends on whether func changes the shape of its output with respect to its input.

Raises
  • TypeError – If input a is not array_like or axes is not int or sequence of ints.

  • ValueError – If any axis is out of range or duplicate axes exist.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.arange(10).reshape(2, 5).astype('float32')
>>> print(x)
[[0. 1. 2. 3. 4.]
 [5. 6. 7. 8. 9.]]
>>> print(np.apply_over_axes(np.sum, x, axes=0))
[[ 5.  7.  9. 11. 13.]]
tinyms.arange(start, stop=None, step=None, dtype=None)[source]

Returns evenly spaced values within a given interval.

Parameters
  • start (Union[int, float]) – Start of interval. The interval includes this value. When stop is provided as a position argument, start must be given, when stop is a normal argument, start can be optional, and default is 0. Please see additional examples below.

  • stop (Union[int, float], optional) – End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.

  • step (Union[int, float], optional) – Spacing between values. For any output out, this is the distance between two adjacent values, \(out[i+1] - out[i]\). The default step size is 1. If step is specified as a position argument, start must also be given.

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype. If dtype is None, the data type of the new tensor will be inferred from start, stop and step. Default is None.

Returns

Tensor with evenly spaced values.

Raises
  • TypeError(PyNative Mode) – If input arguments have types not specified above, or arguments are not given in the correct orders specified above.

  • RuntimeError(Graph Mode) – The inputs that lead to TypeError in Pynative Mode will lead to RuntimeError in Graph Mode.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.arange(0, 5, 1))
[0 1 2 3 4]
>>> print(np.arange(3))
[0 1 2]
>>> print(np.arange(start=0, stop=3))
[0 1 2]
>>> print(np.arange(0, stop=3, step=0.5))
[0.  0.5 1.  1.5 2.  2.5]
>>> print(np.arange(stop=3)) # This will lead to TypeError
tinyms.arccos(x, dtype=None)[source]

Trigonometric inverse cosine, element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor. x-coordinate on the unit circle. For real arguments, the domain is \([-1, 1]\).

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor.

Raises

TypeError – If the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.asarray([1, -1], np.float32)
>>> output = np.arccos(x)
>>> print(output)
[0.        3.1415927]
tinyms.arccosh(x, dtype=None)[source]

Inverse hyperbolic cosine, element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.arange(1, 5).astype('float32')
>>> print(np.arccosh(x))
[0.        1.316958  1.7627472 2.063437 ]
tinyms.arcsin(x, dtype=None)[source]

Inverse sine, element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor. y-coordinate on the unit circle.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Output Tensor.

Raises

TypeError – If the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.asarray([1, -1], np.float32)
>>> output = np.arcsin(x)
>>> print(output)
[ 1.5707964 -1.5707964]
tinyms.arcsinh(x, dtype=None)[source]

Inverse hyperbolic sine element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.arange(5).astype('float32')
>>> print(np.arcsinh(x))
[0.        0.8813736 1.4436355 1.8184465 2.0947125]
tinyms.arctan(x, dtype=None)[source]

Trigonometric inverse tangent, element-wise.

The inverse of tan, so that if \(y = tan(x)\) then \(x = arctan(y)\).

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.arange(5).astype('float32')
>>> print(np.arctan(x))
[0.        0.7853982 1.1071488 1.2490457 1.3258177]
tinyms.arctan2(x1, x2, dtype=None)[source]

Element-wise arc tangent of \(x1/x2\) choosing the quadrant correctly.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – input tensor.

  • x2 (Tensor) – input tensor.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the sum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend CPU GPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.array([-1, +1, +1, -1])
>>> x2 = np.array([-1, -1, +1, +1])
>>> output = np.arctan2(x1, x2)
>>> print(output)
[-2.3561945   2.3561945   0.78539819 -0.78539819]
tinyms.arctanh(x, dtype=None)[source]

Inverse hyperbolic tangent element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if x is a scalar.

Supported Platforms:

Ascend CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([-0.99, -0.75, -0.5, 0, 0.5]).astype('float32')
>>> print(np.arctanh(x))
[-2.646653   -0.97295505 -0.54930615  0.          0.54930615]
tinyms.argmax(a, axis=None)[source]

Returns the indices of the maximum values along an axis.

Note

Numpy argument out is not supported. On Ascend, in case of multiple occurrences of the maximum values, the return indices may not necessarily correspond to the first occurrence.

Parameters
  • a (Union[int, float, bool, list, tuple, Tensor]) – Input array.

  • axis (int, optional) – By default, the index is into the flattened array, otherwise along the specified axis.

Returns

Tensor, array of indices into the array. It has the same shape as a.shape with the dimension along axis removed.

Raises

ValueError – if axis is out of range.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.arange(10, 16).reshape(2, 3)
>>> print(np.argmax(a))
5
>>> print(np.argmax(a, axis=0))
[1 1 1]
>>> print(np.argmax(a, axis=1))
[2 2]
tinyms.argmin(a, axis=None)[source]

Returns the indices of the minimum values along an axis.

Note

Numpy argument out is not supported.

Parameters
  • a (Union[int, float, bool, list, tuple, Tensor]) – Input array.

  • axis (int, optional) – By default, the index is into the flattened array, otherwise along the specified axis.

Returns

Tensor, array of indices into the array. It has the same shape as a.shape with the dimension along axis removed.

Raises

ValueError – if axis is out of range.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.arange(10, 16).reshape(2, 3)
>>> print(np.argmin(a))
0
>>> print(np.argmin(a, axis=0))
[0 0 0]
>>> print(np.argmin(a, axis=1))
[0 0]
tinyms.array(obj, dtype=None, copy=True, ndmin=0)[source]

Creates a tensor.

This function creates tensors from an array-like object.

Parameters
  • obj (Union[int, float, bool, list, tuple]) – Input data, in any form that can be converted to a Tensor. This includes Tensor, list, tuple and numbers.

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype, can be in format of np.int32, or ‘int32’. If dtype is None, the data type of the new tensor will be inferred from obj. Default is None.

  • copy (bool) – If True, then the object is copied. Otherwise, a copy will only be made if necessary. Default: True.

  • ndmin (int) – Specifies the minimum number of dimensions that the resulting tensor should have. Ones will be pre-pended to the shape as needed to meet this requirement. Default: 0

Returns

Tensor, generated tensor with the specified dtype.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If input obj has different sizes at different dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.array([1,2,3]))
[1 2 3]
tinyms.array_equal(a1, a2, equal_nan=False)[source]

Returns True if input arrays have same shapes and all elements equal.

Note

In mindspore, a bool tensor is returned instead, since in Graph mode, the value cannot be traced and computed at compile time.

Since on Ascend, nan is treated differently, currently the argument equal_nan is not supported on Ascend.

Parameters
Returns

Scalar bool tensor, value is True if inputs are equal, False otherwise.

Raises

TypeError – If inputs have types not specified above.

Supported Platforms:

GPU CPU Ascend

Examples

>>> import mindspore.numpy as np
>>> a = [0,1,2]
>>> b = [[0,1,2], [0,1,2]]
>>> print(np.array_equal(a,b))
False
tinyms.array_equiv(a1, a2)[source]

Returns True if input arrays are shape consistent and all elements equal.

Shape consistent means they are either the same shape, or one input array can be broadcasted to create the same shape as the other one.

Note

In mindspore, a bool tensor is returned instead, since in Graph mode, the value cannot be traced and computed at compile time.

Parameters

a1/a2 (Union[int, float, bool, list, tuple, Tensor]) – Input arrays.

Returns

Scalar bool tensor, value is True if inputs are equivalent, False otherwise.

Raises

TypeError – If inputs have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = [0,1,2]
>>> b = [[0,1,2], [0,1,2]]
>>> print(np.array_equiv(a,b))
True
tinyms.array_split(x, indices_or_sections, axis=0)[source]

Splits a tensor into multiple sub-tensors.

Note

Currently, array_split only supports mindspore.float32 on CPU.

The only difference between np.split and np.array_split is that np.array_split allows indices_or_sections to be an integer that does not equally divide the axis. For a tensor of length l that should be split into n sections, it returns \(l % n\) sub-arrays of size \(l//n + 1\) and the rest of size \(l//n\).

Parameters
  • x (Tensor) – A Tensor to be divided.

  • indices_or_sections (Union[int, tuple(int), list(int)]) – If integer, \(N\), the tensor will be divided into \(N\) tensors along axis. If tuple(int), list(int) or of sorted integers, the entries indicate where along axis the array is split. For example, \([2, 3]\) would, for \(axis=0\), result in three sub-tensors \(x[:2]\), \(x[2:3]\). If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.

  • axis (int) – The axis along which to split. Default: 0.

Returns

A list of sub-tensors.

Raises
  • TypeError – If argument indices_or_sections is not integer, tuple(int) or list(int) or argument axis is not integer.

  • ValueError – If argument axis is out of range of \([-x.ndim, x.ndim)\).

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> input_x = np.arange(9).astype("float32")
>>> output = np.array_split(input_x, 4)
>>> print(output)
(Tensor(shape=[3], dtype=Float32,
    value= [ 0.00000000e+00,  1.00000000e+00,  2.00000000e+00]),
Tensor(shape=[2], dtype=Float32,
    value= [ 3.00000000e+00,  4.00000000e+00]),
Tensor(shape=[2], dtype=Float32,
    value= [ 5.00000000e+00,  6.00000000e+00]),
Tensor(shape=[2], dtype=Float32,
    value= [ 7.00000000e+00,  8.00000000e+00]))
tinyms.array_str(a)[source]

Returns a string representation of the data in an array.

The data in the array is returned as a single string. This function is similar to array_repr, the difference being that array_repr also returns information on the kind of array and its data type.

Note

Numpy argument max_line_width, precision and suppress_small are not supported. Graph mode does not support the function.

Parameters

a (Tensor) – Input data.

Returns

String.

Supported Platforms:

Ascend GPU CPU

Raises

TypeError – If input is not tensor.

Examples

>>> import mindspore.numpy as np
>>> x = np.arange(5)
>>> np.array_str(x)
'[0 1 2 3 4]'
tinyms.asarray(a, dtype=None)[source]

Converts the input to tensor.

This function converts tensors from an array-like object.

Parameters
  • a (Union[int, float, bool, list, tuple, Tensor]) – Input data, in any form that can be converted to a Tensor. This includes Tensor, list, tuple and numbers.

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype, can be in format of np.int32, or ‘int32’. If dtype is None, the data type of the new tensor will be inferred from obj. Default is None.

Returns

Tensor, generated tensor with the specified dtype.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If input a has different sizes at different dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.asarray([1,2,3]))
[1 2 3]
tinyms.asfarray(a, dtype=mindspore.float32)[source]

Similar to asarray, converts the input to a float tensor.

If non-float dtype is defined, this function will return a float32 tensor instead.

Parameters
  • a (Union[int, float, bool, list, tuple, Tensor]) – Input data, in any form that can be converted to a Tensor. This includes Tensor, list, tuple and numbers.

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype, can be in format of np.int32, or ‘int32’. If dtype is None, the data type of the new tensor will be inferred from a. Default is mindspore.float32.

Returns

Tensor, generated tensor with the specified float dtype.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If input a has different sizes at different dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.asfarray([1,2,3]))
[1. 2. 3.]
tinyms.atleast_1d(*arys)[source]

Converts inputs to arrays with at least one dimension.

Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.

Note

In graph mode, returns a tuple of tensor instead of a list of tensors.

Parameters

*arys (Tensor) – one or more input tensors.

Returns

Tensor, or list of tensors, each with a.ndim >= 1.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.ones((2, 3))
>>> b = np.ones(())
>>> c = np.ones(5)
>>> output = np.atleast_1d(a, b, c)
>>> print(output)
    [Tensor(shape=[2, 3], dtype=Float32, value=
    [[1.00000000e+00, 1.00000000e+00, 1.00000000e+00],
    [1.00000000e+00, 1.00000000e+00, 1.00000000e+00]]),
    Tensor(shape=[1], dtype=Float32, value= [1.00000000e+00]),
    Tensor(shape=[5], dtype=Float32,
    value= [1.00000000e+00, 1.00000000e+00, 1.00000000e+00,
    1.00000000e+00, 1.00000000e+00])]
tinyms.atleast_2d(*arys)[source]

Reshapes inputs as arrays with at least two dimensions.

Note

In graph mode, returns a tuple of tensor instead of a list of tensors.

Parameters

*arys (Tensor) – one or more input tensors.

Returns

Tensor, or list of tensors, each with a.ndim >= 2.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.ones((2, 3))
>>> b = np.ones(())
>>> c = np.ones(5)
>>> output = np.atleast_2d(a, b, c)
>>> print(output)
    [Tensor(shape=[2, 3], dtype=Float32, value=
    [[1.00000000e+00, 1.00000000e+00, 1.00000000e+00],
    [1.00000000e+00, 1.00000000e+00, 1.00000000e+00]]),
    Tensor(shape=[1, 1], dtype=Float32, value= [[1.00000000e+00]]),
    Tensor(shape=[1, 5], dtype=Float32,
    value= [[1.00000000e+00, 1.00000000e+00, 1.00000000e+00,
    1.00000000e+00, 1.00000000e+00]])]
tinyms.atleast_3d(*arys)[source]

Reshapes inputs as arrays with at least three dimensions.

Note

In graph mode, returns a tuple of tensor instead of a list of tensors.

Parameters

*arys (Tensor) – one or more input tensors.

Returns

Tensor, or list of tensors, each with a.ndim >= 3. For example, a 1-D array of shape (N,) becomes a tensor of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a tensor of shape (M, N, 1).

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.ones((2, 3))
>>> b = np.ones(())
>>> c = np.ones(5)
>>> output = np.atleast_3d(a, b, c)
>>> print(output)
    [Tensor(shape=[2, 3, 1], dtype=Float32, value=
    [[[1.00000000e+00], [1.00000000e+00], [1.00000000e+00]],
    [[1.00000000e+00], [1.00000000e+00], [1.00000000e+00]]]),
    Tensor(shape=[1, 1, 1], dtype=Float32, value= [[[1.00000000e+00]]]),
    Tensor(shape=[1, 5, 1], dtype=Float32,
    value= [[[1.00000000e+00], [1.00000000e+00], [1.00000000e+00],
    [1.00000000e+00], [1.00000000e+00]]])]
tinyms.average(x, axis=None, weights=None, returned=False)[source]

Computes the weighted average along the specified axis.

Parameters
  • x (Tensor) – A Tensor to be averaged.

  • axis (Union[None, int, tuple(int)]) – Axis along which to average x. Default: None. If the axis is None, it will average over all of the elements of the tensor x. If the axis is negative, it counts from the last to the first axis.

  • weights (Union[None, Tensor]) – Weights associated with the values in x. Default: None. If weights is None, all the data in x are assumed to have a weight equal to one. If weights is 1-D tensor, the length must be the same as the given axis. Otherwise, weights should have the same shape as x.

  • returned (bool) – Default: False. If True, the tuple (average, sum_of_weights) is returned. If False, only the average is returned.

Returns

Averaged Tensor. If returned is True, return tuple.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> input_x = np.array([[1., 2.], [3., 4.]])
>>> output = np.average(input_x, axis=0, weights=input_x, returned=True)
>>> print(output)
(Tensor(shape=[2], dtype=Float32, value= [ 2.50000000e+00,  3.33333325e+00]),
 Tensor(shape=[2], dtype=Float32, value= [ 4.00000000e+00,  6.00000000e+00]))
tinyms.bartlett(M)[source]

Returns the Bartlett window. The Bartlett window is very similar to a triangular window, except that the end points are at zero. It is often used in signal processing for tapering a signal, without generating too much ripple in the frequency domain.

Parameters

M (int) – Number of points in the output window. If zero or less, an empty array is returned.

Returns

Tensor, the triangular window, with the maximum value normalized to one (the value one appears only if the number of samples is odd), with the first and last samples equal to zero.

Raises

TypeError – if M is not an int.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.bartlett(12))
[0.         0.18181819 0.36363637 0.5454545  0.72727275 0.9090909
0.9090909  0.72727275 0.5454545  0.36363637 0.18181819 0.        ]
tinyms.bincount(x, weights=None, minlength=0, length=None)[source]

Count number of occurrences of each value in array of non-negative ints. The number of bins (of size 1) is one larger than the largest value in x. If minlength is specified, there will be at least this number of bins in the output array (though it will be longer if necessary, depending on the contents of x). Each bin gives the number of occurrences of its index value in x. If weights is specified the input array is weighted by it, i.e. if a value n is found at position i, out[n] += weight[i] instead of out[n] += 1.

Note

The additional argument length specifies the number of bins (overriding x.max() + 1), which must be provided in graph mode. If x contains negative values, no error will be raised, and negative values are treated as zeros instead.

Parameters
  • x (Union[list, tuple, Tensor]) – 1-d input array.

  • weights (Union[int, float, bool, list, tuple, Tensor], optional) – Weights, array of the same shape as x. Defaults to None.

  • minlength (int, optional) – A minimum number of bins for the output array. Defaults to 0.

  • length (int, optional) – Number of bins. Defaults to None.

Returns

Tensor, the result of binning the input array. The length of out is equal to np.amax(x)+1.

Raises

ValueError – if x is not one-dimensional, or if x and weights do not have the same shape.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.bincount(np.arange(5)))
[1 1 1 1 1]
>>> print(np.bincount(np.array([0, 1, 1, 3, 2, 1, 7])))
[1 3 1 1 0 0 0 1]
>>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights
>>> x = np.array([0, 1, 1, 2, 2, 2])
>>> print(np.bincount(x,  weights=w))
[0.3 0.7 1.1]
tinyms.bitwise_and(x1, x2, dtype=None)[source]

Computes the bit-wise AND of two arrays element-wise. Computes the bit-wise AND of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator &.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – Input array.

  • x2 (Tensor) – Input array. Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, this is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend

Examples

>>> import mindspore.numpy as np
>>> print(np.bitwise_and(13, 17))
1
tinyms.bitwise_not(x, dtype=None)

Computes bit-wise inversion, or bit-wise NOT, element-wise. Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ~. For signed integer inputs, the two’s complement is returned. In a two’s-complement system negative numbers are represented by the two’s complement of the absolute value. This is the most common method of representing signed integers on computers [1]. A N-bit two’s-complement system can represent every integer in the range -2^{N-1} to +2^{N-1}-1.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. Supported dtypes on Ascend: np.int16, np.uint16.

Parameters
  • x (Tensor) – Only integer and boolean types are handled.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar.

Supported Platforms:

Ascend

Examples

>>> import mindspore.numpy as np
>>> print(np.invert(np.array(13, dtype=np.uint16)))
65522
tinyms.bitwise_or(x1, x2, dtype=None)[source]

Computes the bit-wise OR of two arrays element-wise. Computes the bit-wise OR of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator |.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – Input array.

  • x2 (Tensor) – Input array. Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, this is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend

Examples

>>> import mindspore.numpy as np
>>> print(np.bitwise_or(13, 16))
29
tinyms.bitwise_xor(x1, x2, dtype=None)[source]

Computes the bit-wise XOR of two arrays element-wise. Computes the bit-wise XOR of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ^.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – Input array.

  • x2 (Tensor) – Input array. Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, this is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend

Examples

>>> import mindspore.numpy as np
>>> print(np.bitwise_xor(13, 17))
28
tinyms.blackman(M)[source]

Returns the Blackman window. The Blackman window is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window.

Parameters

M (int) – Number of points in the output window. If zero or less, an empty array is returned.

Returns

Tensor, the window, with the maximum value normalized to one (the value one appears only if the number of samples is odd).

Raises

TypeError – if M is not an int.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.blackman(12))
[-1.4901161e-08  3.2606430e-02  1.5990365e-01  4.1439798e-01
7.3604518e-01  9.6704674e-01  9.6704674e-01  7.3604518e-01
4.1439798e-01  1.5990365e-01  3.2606430e-02 -1.4901161e-08]
tinyms.broadcast_arrays(*args)[source]

Broadcasts any number of arrays against each other.

Note

Numpy argument subok is not supported. In graph mode, returns a tuple of Tensor instead of a list of Tensor.

Parameters

*args (Tensor) – The arrays to broadcast.

Returns

List of Tensor.

Raises

ValueError – if arrays cannot be broadcast.

Supported Platforms:

Ascend GPU CPU

Example

>>> import mindspore.numpy as np
>>> x = np.array([[1,2,3]])
>>> y = np.array([[4],[5]])
>>> output = np.broadcast_arrays(x, y)
>>> print(output)
[Tensor(shape=[2, 3], dtype=Int32, value=
[[1, 2, 3],
[1, 2, 3]]), Tensor(shape=[2, 3], dtype=Int32, value=
[[4, 4, 4],
[5, 5, 5]])]
tinyms.broadcast_to(array, shape)[source]

Broadcasts an array to a new shape.

Parameters
  • array (Tensor) – The array to broadcast.

  • shape (tuple) – The shape of the desired array.

Returns

Tensor, original array broadcast to the given shape.

Raises

ValueError – if array cannot be broadcast to shape.

Supported Platforms:

Ascend GPU CPU

Example

>>> import mindspore.numpy as np
>>> x = np.array([1, 2, 3])
>>> output = np.broadcast_to(x, (3, 3))
>>> print(output)
[[1 2 3]
[1 2 3]
[1 2 3]]
tinyms.cbrt(x, dtype=None)[source]

Returns the cube-root of a tensor, element-wise.

Note

Numpy arguments casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.asarray([1, -1, 3, -8, 64])
>>> output = np.cbrt(a)
>>> print(output)
[ 1.        -1.         1.4422495 -2.         4.       ]
tinyms.ceil(x, dtype=None)[source]

Returns the ceiling of the input, element-wise.

The ceil of the scalar x is the smallest integer i, such that i >= x.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. On GPU, the supported dtypes are np.float16, and np.float32.

Parameters
  • x (Tensor) – input values.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the floor of each element in x. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> output = np.ceil(a)
>>> print(output)
[-1. -1. -0.  1.  2.  2.  2.]
tinyms.choose(a, choices, mode='clip')[source]

Construct an array from an index array and a list of arrays to choose from. Given an “index” array a of integers and a sequence of n arrays (choices), a and each choice array are first broadcast, as necessary, to arrays of a common shape; calling these Ba and Bchoices[i], i = 0,…,n-1 we have that, necessarily, Ba.shape == Bchoices[i].shape for each i. Then, a new array with shape Ba.shape is created as follows:

  • if mode='raise' (the default), then, first of all, each element of a (and thus Ba) must be in the range [0, n-1]; now, suppose that i (in that range) is the value at the (j0, j1, …, jm) position in Ba - then the value at the same position in the new array is the value in Bchoices[i] at that same position;

  • if mode='wrap', values in a (and thus Ba) may be any (signed) integer; modular arithmetic is used to map integers outside the range [0, n-1] back into that range; and then the new array is constructed as above;

  • if mode='clip', values in a (and thus Ba) may be any (signed) integer; negative integers are mapped to 0; values greater than n-1 are mapped to n-1; and then the new array is constructed as above.

Note

Numpy argument out is not supported. mode = 'raise' is not supported, and the default mode is ‘clip’ instead.

Parameters
  • a (int array) – This array must contain integers in [0, n-1], where n is the number of choices, unless mode=wrap or mode=clip, in which cases any integers are permissible.

  • choices (sequence of arrays) – Choice arrays. a and all of the choices must be broadcastable to the same shape. If choices is itself an array, then its outermost dimension (i.e., the one corresponding to choices.shape[0]) is taken as defining the “sequence”.

  • mode (‘raise’, ‘wrap’, ‘clip’, optional) –

    Specifies how indices outside [0, n-1] will be treated:

    ‘raise’ – raise an error;

    ‘wrap’ – wrap around;

    ‘clip’ – clip to the range. ‘clip’ mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers.

Returns

Tensor, the merged result.

Raises

ValueError – if a and any of the choices cannot be broadcast.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> choices = [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]
>>> print(np.choose([2, 3, 1, 0], choices))
[20 31 12  3]
>>> print(np.choose([2, 4, 1, 0], choices, mode='clip'))
[20 31 12  3]
>>> print(np.choose([2, 4, 1, 0], choices, mode='wrap'))
[20  1 12  3]
>>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
>>> choices = [-10, 10]
>>> print(np.choose(a, choices))
[[ 10 -10  10]
 [-10  10 -10]
 [ 10 -10  10]]
tinyms.clip(x, xmin, xmax, dtype=None)[source]

Clips (limits) the values in an array.

Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of \([0, 1]\) is specified, values smaller than 0 become 0, and values larger than 1 become 1.

Parameters
  • x (Tensor) – Tensor containing elements to clip.

  • xmin (Tensor, scalar, None) – Minimum value. If None, clipping is not performed on lower interval edge. Not more than one of xmin and xmax may be None.

  • xmax (Tensor, scalar, None) – Maximum value. If None, clipping is not performed on upper interval edge. Not more than one of xmin and xmax may be None. If xmin or xmax are tensors, then the three tensors will be broadcasted to match their shapes.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor, a tensor with the elements of x, but where values < xmin are replaced with xmin, and those > xmax with xmax.

Raises
  • TypeError – If inputs have types not specified above.

  • ValueError – If the shapes of x1 and x2 cannot broadcast, or both xmin and xmax are None.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.asarray([1, 2, 3, -4, 0, 3, 2, 0])
>>> output = np.clip(x, 0, 2)
>>> print(output)
[1 2 2 0 0 2 2 0]
tinyms.column_stack(tup)[source]

Stacks 1-D tensors as columns into a 2-D tensor. 2-D tensors are stacked as-is, like np.hstack.

Parameters

tup (Union[Tensor, tuple, list]) – A sequence of 1-D or 2-D tensors. All of them must have the same shape except the axis to be concatenated.

Returns

2-D Tensor, formed by stacking the given tensors.

Supported Platforms:

Ascend GPU CPU

Raises

Examples

>>> import mindspore.numpy as np
>>> x1 = np.array([1, 2, 3]).astype('int32')
>>> x2 = np.array([4, 5, 6]).astype('int32')
>>> output = np.column_stack((x1, x2))
>>> print(output)
[[1 4]
 [2 5]
 [3 6]]
tinyms.concatenate(arrays, axis=0)[source]

Joins a sequence of tensors along an existing axis.

Note

To match Numpy behaviour, \(axis >= 32\) will not cause value error, the axis will be treated as None instead.

Parameters
  • arrays (Union[Tensor, tuple(Tensor), list(Tensor)]) – a tensor or a list of tensors to be concatenated.

  • axis (Union[None, int], optional) – The axis along which the tensors will be joined, if axis is None, tensors are flattened before use. Default is 0.

Returns

A tensor concatenated from a tensor or a list of tensors.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If axis is not in the range of \([-ndim, ndim-1]\), and less than 32.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.ones((1,2,3))
>>> x2 = np.ones((1,2,1))
>>> x = np.concatenate((x1, x2), axis=-1)
>>> print(x.shape)
(1, 2, 4)
tinyms.convolve(a, v, mode='full')[source]

Returns the discrete, linear convolution of two one-dimensional sequences.

Note

If v is longer than a, the tensors are swapped before computation.

Parameters
  • a (Union[list, tuple, Tensor]) – First one-dimensional input tensor.

  • v (Union[list, tuple, Tensor]) – Second one-dimensional input tensor.

  • mode (str, optional) – By default, mode is ‘full’. This returns the convolution at each point of overlap, with an output shape of \((N+M-1,)\). At the end-points of the convolution, the signals do not overlap completely, and boundary effects may be seen. If mode is ‘same’, it returns output of length \(max(M, N)\). Boundary effects are still visible. If mode is ‘valid’, it returns output of length \(max(M, N) - min(M, N) + 1\). The convolution product is only given for points where the signals overlap completely. Values outside the signal boundary have no effect.

Returns

Tensor, discrete, linear convolution of a and v.

Raises
  • TypeError – if the inputs have types not specified above.

  • ValueError – if a and v are empty or have wrong dimensions

Supported Platforms:

GPU

Examples

>>> import mindspore.numpy as np
>>> output = np.convolve([1., 2., 3., 4., 5.], [2., 3.], mode="valid")
>>> print(output)
[ 7. 12. 17. 22.]
tinyms.copysign(x1, x2, dtype=None)[source]

Changes the sign of x1 to that of x2, element-wise.

If x2 is a scalar, its sign will be copied to all elements of x1.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. Complex inputs are not supported now.

Parameters
  • x1 (Union[int, float, list, tuple, Tensor]) – Values to change the sign of.

  • x2 (Union[int, float, list, tuple, Tensor]) – The sign of x2 is copied to x1. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. The values of x1 with the sign of x2. This is a scalar if both x1 and x2 are scalars.

Raises

TypeError – if dtype of the input is not in the given types or the input can not be converted to tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.copysign(np.array([1, -1, -1]), np.array([-1, 1, -1]))
>>> print(output)
[-1  1 -1]
tinyms.corrcoef(x, y=None, rowvar=True, dtype=None)[source]

Returns Pearson product-moment correlation coefficients.

Please refer to the documentation for cov for more detail. The relationship between the correlation coefficient matrix, R, and the covariance matrix, C, is \(R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }\) The values of R are between -1 and 1, inclusive.

Note

Currently, complex numbers are not supported.

Parameters
  • x (Union[int, float, bool, tuple, list, Tensor]) – A 1-D or 2-D array containing multiple variables and observations. Each row of x represents a variable, and each column a single observation of all those variables. Also see rowvar below.

  • y (Union[int, float, bool, tuple, list, Tensor], optional) – An additional set of variables and observations.

  • rowvar (bool, optional) – If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations.

  • dtype (mindspore.dtype, optional) – Data-type of the result. By default, the return data-type will have at least float32 precision.

Returns

Tensor, The correlation coefficient matrix of the variables.

Raises
  • TypeError – if the inputs have types not specified above.

  • ValueError – if x and y have wrong dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.corrcoef([[2., 3., 4., 5.], [0., 2., 3., 4.], [7., 8., 9., 10.]])
>>> print(output)
[[1.         0.9827076  1.        ]
[0.9827077  0.99999994 0.9827077 ]
[1.         0.9827076  1.        ]]
tinyms.correlate(a, v, mode='valid')[source]

Cross-correlation of two 1-dimensional sequences.

This function computes the correlation as generally defined in signal processing texts:

\(c_{av}[k] = sum_n a[n+k] * conj(v[n])\)

with a and v sequences being zero-padded where necessary and conj being the conjugate.

Note

Currently, complex numbers are not supported.

Parameters
  • a (Union[list, tuple, Tensor]) – First input sequence.

  • v (Union[list, tuple, Tensor]) – Second input sequence.

  • mode (str, optional) – By default, mode is ‘valid’. If mode is ‘valid’, it returns output of length \(max(M, N) - min(M, N) + 1\). The convolution product is only given for points where the signals overlap completely. Values outside the signal boundary have no effect. If mode is ‘full’, it returns the convolution at each point of overlap, with an output shape of \((N + M - 1,)\). At the end-points of the convolution, the signals do not overlap completely, and boundary effects may be seen. If mode is ‘same’, it returns output of length \(max(M, N)\). Boundary effects are still visible.

Returns

Tensor. Discrete cross-correlation of a and v.

Raises
  • TypeError – if the inputs can not be converted to tensor.

  • ValueError – if a and v are empty or have wrong dimensions

Supported Platforms:

GPU

Examples

>>> import mindspore.numpy as np
>>> output = np.correlate([1, 2, 3], [0, 1, 0.5])
>>> print(output)
[3.5]
>>> output = np.correlate([1, 2, 3], [0, 1, 0.5], mode="same")
>>> print(output)
[2.  3.5 3. ]
>>> output = np.correlate([1, 2, 3, 4, 5], [1, 2], mode="same")
>>> print(output)
[ 2.  5.  8. 11. 14.]
tinyms.cos(x, dtype=None)[source]

Cosine element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.arange(5).astype('float32')
>>> print(np.cos(x))
[ 1.          0.5403023  -0.41614684 -0.9899925  -0.6536436 ]
tinyms.cosh(x, dtype=None)[source]

Hyperbolic cosine, element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if x is a scalar.

Supported Platforms:

Ascend CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.arange(5).astype('float32')
>>> print(np.cosh(x))
[ 1.         1.5430807  3.7621956 10.067662  27.308233 ]
tinyms.count_nonzero(x, axis=None, keepdims=False)[source]

Counts the number of non-zero values in the tensor x.

Parameters
  • x (Tensor) – The tensor for which to count non-zeros.

  • axis (Union[int,tuple], optional) – Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of x.

  • keepdims (bool, optional) – If this is set to True, the axes that are counted are left in the result as dimensions with size one. With this option, the result will broadcast correctly against x.

Returns

Tensor, indicating number of non-zero values in the x along a given axis. Otherwise, the total number of non-zero values in x is returned.

Raises
  • TypeError – If axis is not int or tuple.

  • ValueError – If axis is not in range [-x.ndim, x.ndim)

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.asarray([1, 2, 3, -4, 0, 3, 2, 0])
>>> output = np.count_nonzero(x)
>>> print(output)
6
tinyms.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None, dtype=None)[source]

Estimates a covariance matrix, given data and weights.

Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, \(X = [x_1, x_2, ... x_N]^T\), then the covariance matrix element \(C_{ij}\) is the covariance of \(x_i\) and \(x_j\). The element \(C_{ii}\) is the variance of \(x_i\).

Note

fweights and aweights must be all positive, in Numpy if negative values are detected, a value error will be raised, in MindSpore we converts all values to positive instead.

Parameters
  • m (Union[Tensor, list, tuple]) – A 1-D or 2-D tensor containing multiple variables and observations. Each row of m represents a variable, and each column represents a single observation of all those variables. Also see rowvar below.

  • y (Union[Tensor, list, tuple], optional) – An additional set of variables and observations. y has the same form as that of m, default is None.

  • rowvar (bool, optional) – If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations.

  • bias (bool, optional) – Default Normalization (False) is by \((N - 1)\), where \(N\) is the number of observations given (unbiased estimate). If bias is True, then Normalization is by N. These values can be overridden by using the keyword ddof.

  • ddof (int, optional) – If not None, the default value implied by bias is overridden. Note that \(ddof=1\) will return the unbiased estimate, even if both fweights and aweights are specified, and \(ddof=0\) will return the simple average. See the notes for the details. The default value is None.

  • fweights (Union[Tensor, list, tuple], optional) – 1-D tensor of integer frequency weights; the number of times each observation vector should be repeated. The default value is None.

  • aweights (Union[Tensor, list, tuple], optional) – 1-D tensor of observation vector weights. These relative weights are typically larger for observations considered more important and smaller for observations considered less important. If \(ddof=0\) the tensor of weights can be used to assign probabilities to observation vectors. The default value is None.

  • dtype (Union[mindspore.dtype, str], optional) – Data-type of the result. By default, the return data-type will have mstype.float32 precision.

Returns

Tensor, the covariance matrix of the variables.

Raises
  • TypeError – if the inputs have types not specified above.

  • ValueError – if m and y have wrong dimensions.

  • RuntimeError – if aweights and fweights have dimensions > 2.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.cov([[2., 3., 4., 5.], [0., 2., 3., 4.], [7., 8., 9., 10.]])
>>> print(output)
[[1.6666666 2.1666667 1.6666666]
[2.1666667 2.9166667 2.1666667]
[1.6666666 2.1666667 1.6666666]]
tinyms.cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None)[source]

Returns the cross product of two (arrays of) vectors.

The cross product of a and b in \(R^3\) is a vector perpendicular to both a and b. If a and b are arrays of vectors, the vectors are defined by the last axis of a and b by default, and these axes can have dimensions 2 or 3. Where the dimension of either a or b is 2, the third component of the input vector is assumed to be zero and the cross product calculated accordingly. In cases where both input vectors have dimension 2, the z-component of the cross product is returned.

Parameters
  • a (Union[list, tuple, Tensor]) – Components of the first vector(s).

  • b (Union[list, tuple, Tensor]) – Components of the second vector(s).

  • axisa (int, optional) – Axis of a that defines the vector(s). By default, the last axis.

  • axisb (int, optional) – Axis of b that defines the vector(s). By default, the last axis.

  • axisc (int, optional) – Axis of c containing the cross product vector(s). Ignored if both input vectors have dimension 2, as the return is scalar. By default, the last axis.

  • axis (int, optional) – If defined, the axis of a, b and c that defines the vector(s) and cross product(s). Overrides axisa, axisb and axisc.

Returns

Tensor, vector cross product(s).

Raises

ValueError – when the dimensions of the vector(s) in a and/or b does not equal 2 or 3.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([[1,2,3], [4,5,6]])
>>> y = np.array([[4,5,6], [1,2,3]])
>>> output = np.cross(x, y)
>>> print(output)
[[-3  6 -3]
[ 3 -6  3]]
>>> output = np.cross(x, y, axisc=0)
>>> print(output)
[[-3  3]
[ 6 -6]
[-3  3]]
tinyms.cumprod(a, axis=None, dtype=None)[source]

Returns the cumulative product of elements along a given axis.

Note

Numpy argument out is not supported.

Parameters
  • a (Union[int, float, bool, list, tuple, Tensor]) – Input tensor.

  • axis (int, optional) – Axis along which the cumulative product is computed. By default the input is flattened.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor.

Raises
  • TypeError – If the input can not be converted to tensor or axis is not integer.

  • ValueError – If axis is out of range.

Supported Platforms:

Ascend GPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([1, 2, 3])
>>> print(np.cumprod(x))
[1 2 6]
tinyms.cumsum(a, axis=None, dtype=None)[source]

Returns the cumulative sum of the elements along a given axis.

Note

If a.dtype is int8, int16 or bool, the result dtype will be elevated to int32.

Parameters
  • a (Tensor) – Input tensor.

  • axis (int, optional) – Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.

  • dtype (mindspore.dtype, optional) – If not specified, stay the same as a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.

Returns

Tensor.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If axis is out of range.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.cumsum(np.ones((3,3)), axis=0)
>>> print(output)
[[1. 1. 1.]
 [2. 2. 2.]
 [3. 3. 3.]]
tinyms.deg2rad(x, dtype=None)[source]

Converts angles from degrees to radians.

Parameters
  • x (Tensor) – Angles in degrees.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor, the corresponding angle in radians. This is a tensor scalar if x is a tensor scalar.

Raises

TypeError – if x is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.asarray([1, 2, 3, -4, -5])
>>> output = np.deg2rad(x)
>>> print(output)
[ 0.01745329  0.03490658  0.05235988 -0.06981317 -0.08726647]
tinyms.diag(v, k=0)[source]

Extracts a diagonal or construct a diagonal array.

Parameters
  • v (Tensor) – If v is a 2-D array, return a copy of its k-th diagonal. If v is a 1-D array, return a 2-D array with v on the k-th diagonal.

  • k (int, optional) – Diagonal in question. The default is 0. Use k>0 for diagonals above the main diagonal, and k<0 for diagonals below the main diagonal.

Returns

Tensor, the extracted diagonal or constructed diagonal array.

Raises

ValueError – if input is not 1-D or 2-D.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.arange(9).reshape((3,3))
>>> print(x)
[[0 1 2]
[3 4 5]
[6 7 8]]
>>> output = np.diag(x)
>>> print(output)
[0 4 8]
>>> output = np.diag(x, k=1)
>>> print(output)
[1 5]
>>> output = np.diag(x, k=-1)
>>> print(output)
[3 7]
tinyms.diag_indices(n, ndim=2)[source]

Returns the indices to access the main diagonal of an array.

This returns a tuple of indices that can be used to access the main diagonal of an array a with a.ndim >= 2 dimensions and shape (n, n, …, n). For a.ndim = 2 this is the usual diagonal, for a.ndim > 2 this is the set of indices to access a[i, i, ..., i] for i = [0..n-1].

Parameters
  • n (int) – The size, along each dimension, of the arrays for which the returned indices can be used.

  • ndim (int, optional) – The number of dimensions.

Returns

Tuple of Tensor.

Raises

TypeError – if input are not integers.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.diag_indices(5, 3)
>>> print(output)
(Tensor(shape=[5], dtype=Int32, value= [0, 1, 2, 3, 4]),
Tensor(shape=[5], dtype=Int32, value= [0, 1, 2, 3, 4]),
Tensor(shape=[5], dtype=Int32, value= [0, 1, 2, 3, 4]))
tinyms.diagflat(v, k=0)[source]

Creates a two-dimensional array with the flattened input as a diagonal.

Note

On GPU, the supported dtypes are np.float16, and np.float32.

Parameters
  • v (Tensor) – Input data, which is flattened and set as the k-th diagonal of the output.

  • k (int, optional) – Diagonal to set; 0, the default, corresponds to the “main” diagonal, a positive (negative) k giving the number of the diagonal above (below) the main.

Returns

Tensor, The 2-D output array.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.diagflat(np.asarray([[1,2], [3,4]]))
>>> print(output)
[[1 0 0 0]
[0 2 0 0]
[0 0 3 0]
[0 0 0 4]]
>>> output = np.diagflat(np.asarray([1,2]), 1)
>>> print(output)
[[0 1 0]
[0 0 2]
[0 0 0]]
tinyms.diagonal(a, offset=0, axis1=0, axis2=1)[source]

Returns specified diagonals.

If a is 2-D, returns the diagonal of a with the given offset, i.e., the collection of elements of the form a[i, i+offset]. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-array whose diagonal is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals.

Parameters
  • a (Tensor) – Array from which the diagonals are taken.

  • offset (int, optional) – Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal.

  • axis1 (int, optional) – Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0).

  • axis2 (int, optional) – Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis.

Returns

Tensor, if a is 2-D, then a 1-D array containing the diagonal. If a.ndim > 2, then the dimensions specified by axis1 and axis2 are removed, and a new axis inserted at the end corresponding to the diagonal.

Raises

ValueError – if the input tensor has less than two dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.arange(4).reshape(2,2).astype(np.float32)
>>> print(a)
[[0. 1.]
[2. 3.]]
>>> output = np.diagonal(a)
>>> print(output)
[0. 3.]
>>> output = np.diagonal(a, 1)
>>> print(output)
[1.]
>>> a = np.arange(8).reshape(2, 2, 2).astype(np.float32)
>>> print(a)
[[[0. 1.]
[2. 3.]]
[[4. 5.]
[6. 7.]]]
>>> output = np.diagonal(a, 0, 0, 1)
>>> print(output)
[[0. 6.]
[1. 7.]]
tinyms.diff(a, n=1, axis=-1, prepend=None, append=None)[source]

Calculates the n-th discrete difference along the given axis.

The first difference is given by \(out[i] = a[i+1] - a[i]\) along the given axis, higher differences are calculated by using diff iteratively.

Note

Since zero-shaped Tensor is not supported in MindSpore, a value error is raised if an empty Tensor is encountered.

Parameters
  • a (Tensor) – Input tensor.

  • n (int, optional) – The number of times values are differenced. If zero, the input is returned as-is.

  • axis (int, optional) – The axis along which the difference is taken, default is the last axis.

  • prepend/append (Tensor, optional) – Values to prepend or append to a along axis prior to performing the difference. Scalar values are expanded to arrays with length 1 in the direction of axis and the shape of the input array in along all other axes. Otherwise the dimension and shape must match a except along axis.

Returns

The n-th differences. The shape of the output is the same as a except along axis where the dimension is smaller by n. The type of the output is the same as the type of the difference between any two elements of a. This is the same as the type of a in most cases.

Raises
Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> arr = np.array([1, 3, -1, 0, 4])
>>> print(np.diff(arr, n=2))
[-6  5  3]
tinyms.digitize(x, bins, right=False)[source]

Returns the indices of the bins to which each value in input array belongs. If values in x are beyond the bounds of bins, 0 or len(bins) is returned as appropriate.

Parameters
  • x (Union[int, float, bool, list, tuple, Tensor]) – Input array to be binned.

  • bins (Union[list, tuple, Tensor]) – Array of bins. It has to be 1-dimensional and monotonic.

  • right (boolean, optional) – Indicating whether the intervals include the right or the left bin edge. Default behavior is (right==False) indicating that the interval does not include the right edge. The left bin end is open in this case, i.e., bins[i-1] <= x < bins[i] is the default behavior for monotonically increasing bins.

Returns

Tensor of ints, output array of indices, of same shape as x.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([1.2, 10.0, 12.4, 15.5, 20.])
>>> bins = np.array([0, 5, 10, 15, 20])
>>> inds = np.digitize(x, bins)
>>> print(inds)
[1 3 3 4 5]
tinyms.divide(x1, x2, dtype=None)[source]

Returns a true division of the inputs, element-wise.

Instead of the Python traditional ‘floor division’, this returns a true division.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – the divident.

  • x2 (Tensor) – the divisor.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, this is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.full((3, 2), [1, 2])
>>> x2 = np.full((3, 2), [3, 4])
>>> output = np.divide(x1, x2)
>>> print(output)
[[0.33333334 0.5       ]
[0.33333334 0.5       ]
[0.33333334 0.5       ]]
tinyms.divmod(x1, x2, dtype=None)

Returns element-wise quotient and remainder simultaneously.

Parameters
  • x1 (Union[Tensor]) – Dividend tensor.

  • x2 (Union[Tensor, int, float, bool]) – Divisor. If x1.shape != x2.shape, they must be broadcastable to a common shape.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Element-wise quotient and remainder from floor division, in format of (quotient, remainder)

Raises

TypeError – if x1 and x2 are not Tensor or scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.array([1, 2, 3, 4, 5])
>>> print(np.divmod(a, 1.5))
(Tensor(shape=[5], dtype=Float32,
 value= [ 0.00000000e+00,  1.00000000e+00,  2.00000000e+00,  2.00000000e+00,  3.00000000e+00]),
 Tensor(shape=[5], dtype=Float32,
 value= [ 1.00000000e+00,  5.00000000e-01,  0.00000000e+00,  1.00000000e+00,  5.00000000e-01]))
tinyms.dot(a, b)[source]

Returns the dot product of two arrays.

Specifically, If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation). If both a and b are 2-D arrays, it is matrix multiplication. If either a or b is 0-D (scalar), it is equivalent to multiply. If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b. If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b: dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

Note

Numpy argument out is not supported. On GPU, the supported dtypes are np.float16, and np.float32. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.

Parameters
Returns

Tensor or scalar, the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned

Raises

ValueError – If the last dimension of a is not the same size as the second-to-last dimension of b.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.full((1, 3), 7).astype('float32')
>>> b = np.full((2, 3, 4), 5).astype('float32')
>>> output = np.dot(a, b)
>>> print(output)
[[[105. 105. 105. 105.]
[105. 105. 105. 105.]]]
tinyms.dsplit(x, indices_or_sections)[source]

Splits a tensor into multiple sub-tensors along the 3rd axis (depth). It is equivalent to split with \(axis=2\) (default), the array is always split along the third axis regardless of the array dimension.

Parameters
  • x (Tensor) – A Tensor to be divided.

  • indices_or_sections (Union[int, tuple(int), list(int)]) – If integer, \(N\), the tensor will be divided into \(N\) equal tensors along axis. If tuple(int), list(int) or of sorted integers, the entries indicate where along axis the array is split. For example, \([2, 3]\) would, for \(axis=0\), result in three sub-tensors \(x[:2]\), \(x[2:3]\). If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.

Returns

A list of sub-tensors.

Raises

TypeError – If argument indices_or_sections is not integer.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> input_x = np.arange(6).reshape((1, 2, 3)).astype('float32')
>>> output = np.dsplit(input_x, 3)
>>> print(output)
(Tensor(shape=[1, 2, 1], dtype=Float32,
value=[[[ 0.00000000e+00],
        [ 3.00000000e+00]]]),
Tensor(shape=[1, 2, 1], dtype=Float32,
value=[[[ 1.00000000e+00],
        [ 4.00000000e+00]]]),
Tensor(shape=[1, 2, 1], dtype=Float32,
value=[[[ 2.00000000e+00],
        [ 5.00000000e+00]]]))
tinyms.dstack(tup)[source]

Stacks tensors in sequence depth wise (along the third axis). This is equivalent to concatenation along the third axis. 1-D tensors \((N,)\) should be reshaped to \((1,N,1)\). 2-D tensors \((M,N)\) should be reshaped to \((M,N,1)\) before concatenation.

Parameters

tup (Union[Tensor, tuple, list]) – A sequence of tensors. The tensors must have the same shape along all but the third axis. 1-D or 2-D tensors must have the same shape.

Returns

Stacked Tensor, formed by stacking the given tensors.

Supported Platforms:

Ascend GPU CPU

Raises

Examples

>>> import mindspore.numpy as np
>>> x1 = np.array([1, 2, 3]).astype('float32')
>>> x2 = np.array([4, 5, 6]).astype('float32')
>>> output = np.dstack((x1, x2))
>>> print(output)
[[[1. 4.]
  [2. 5.]
  [3. 6.]]]
tinyms.ediff1d(ary, to_end=None, to_begin=None)[source]

The differences between consecutive elements of a tensor.

Parameters
  • ary (Tensor) – If necessary, will be flattened before the differences are taken.

  • to_end (Tensor or scalar, optional) – Number(s) to append at the end of the returned differences.

  • to_begin (Tensor or scalar, optional) – Number(s) to prepend at the beginning of the returned differences.

Returns

The differences.

Raises

TypeError – If inputs have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> arr = np.array([1, 3, -1, 0, 4])
>>> print(np.ediff1d(arr))
[ 2 -4  1  4]
tinyms.empty(shape, dtype=mindspore.float32)[source]

Returns a new array of given shape and type, without initializing entries.

Note

Numpy argument order is not supported. Object arrays are not supported.

Parameters
  • shape (Union[int, tuple(int)]) – Shape of the empty array, e.g., (2, 3) or 2.

  • dtype (mindspore.dtype, optional) – Desired output data-type for the array, e.g, mstype.int8. Default is mstype.float32.

Returns

Tensor, array of uninitialized (arbitrary) data of the given shape and dtype.

Raises

TypeError – if the input shape or dtype is invalid.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.empty((2, 3))
>>> print(output)
# result may vary
Tensor(shape=[2, 3], dtype=Float32, value=
<uninitialized>)
tinyms.empty_like(prototype, dtype=None, shape=None)[source]

Returns a new array with the same shape and type as a given array.

Note

Input array must have the same size across a dimension. If prototype is not a Tensor, dtype is float32 by default if not provided.

Parameters
  • prototype (Union[Tensor, list, tuple]) – The shape and data-type of prototype define these same attributes of the returned array.

  • dtype (mindspore.dtype, optional) – Overrides the data type of the result.

  • shape (int or sequence of ints, optional) – Overrides the shape of the result.

Returns

Tensor, array of uninitialized (arbitrary) data with the same shape and type as prototype.

Raises

ValueError – if prototype is not a Tensor, list or tuple.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.ones((4,1,2))
>>> output = np.empty_like(a)
>>> print(output)
# result may vary
Tensor(shape=[4, 1, 2], dtype=Float32, value=
<uninitialized>)
tinyms.equal(x1, x2, dtype=None)[source]

Returns the truth value of (x1 == x2) element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – Input array.

  • x2 (Tensor) – Input array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, element-wise comparison of x1 and x2. Typically of type bool, unless dtype is passed. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.equal(np.array([0, 1, 3]), np.arange(3))
>>> print(output)
[ True  True False]
tinyms.exp(x, dtype=None)[source]

Calculates the exponential of all elements in the input array.

Note

Numpy arguments casting, order, subok, signature, and extobj are not supported. When where is provided, out must have a tensor value. out is not supported for storing the result, however it can be used in combination with where to set the value at indices for which where is set to False. On GPU, the supported dtypes are np.float16, and np.float32. On CPU, the supported dtypes are np.float16, np.float32, np.float64.

Parameters
  • x (Tensor) – input data.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, element-wise exponential of x. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.exp(np.arange(5).astype(np.float32))
>>> print(output)
[ 1.         2.718282   7.3890557 20.085537  54.598145 ]
tinyms.exp2(x, dtype=None)[source]

Calculates 2**p for all p in the input array.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. On GPU, the supported dtypes are np.float16, and np.float32.

Parameters
  • x (Tensor) – input values.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, element-wise 2 to the power x.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([2, 3]).astype(np.float32)
>>> output = np.exp2(x)
>>> print(output)
[4. 8.]
tinyms.expand_dims(a, axis)[source]

Expands the shape of a tensor.

Inserts a new axis that will appear at the axis position in the expanded tensor shape.

Parameters
  • a (Tensor) – Input tensor array.

  • axis (Union[int, list(int), tuple(int)]) – Position in the expanded axes where the new axis is placed,

Returns

Tensor, with the number of dimensions increased at specified axis.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If axis exceeds a.ndim.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.ones((2,2))
>>> x = np.expand_dims(x,0)
>>> print(x.shape)
(1, 2, 2)
tinyms.expm1(x, dtype=None)[source]

Calculates exp(x) - 1 for all elements in the array.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. On GPU, the supported dtypes are np.float16, and np.float32. On CPU, the supported dtypes are np.float16, and np.float32.

Parameters
  • x (Tensor) – input data.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, element-wise exponential minus one, out = exp(x) - 1. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.expm1(np.arange(5).astype(np.float32))
>>> print(output)
[ 0.         1.7182819  6.389056  19.085537  53.59815  ]
tinyms.eye(N, M=None, k=0, dtype=mindspore.float32)[source]

Returns a 2-D tensor with ones on the diagonal and zeros elsewhere.

Parameters
  • N (int) – Number of rows in the output, must be larger than 0.

  • M (int, optional) – Number of columns in the output. If is None, defaults to N, if defined, must be larger than 0. Deault is None.

  • k (int, optional) – Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal. Default is 0.

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype. Default is mstype.float32.

Returns

A tensor of shape (N, M). A tensor where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one.

Raises

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.eye(2, 2))
[[1. 0.]
[0. 1.]]
tinyms.fabs(x, dtype=None)

Calculates the absolute value element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. Currently the backend kernel only supports float calculation, if the input is not a float, then it will be casted to mstype.float32 and casted back.

Parameters
  • x (Tensor) – Tensor to be used for calculation.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor.

Raises

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.asarray([1, 2, 3, -4, -5], np.float32)
>>> output = np.absolute(x)
>>> print(output)
[1. 2. 3. 4. 5.]
tinyms.fix(x)[source]

Rounds to nearest integer towards zero.

Rounds an array of floats element-wise to nearest integer towards zero. The rounded values are returned as floats.

Note

Numpy argument out is not supported.

Parameters

x (Tensor) – An array of floats to be rounded.

Returns

Tensor.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.fix(np.array([2.1, 2.9, -2.1, -2.9]))
>>> print(output)
[ 2.  2. -2. -2.]
tinyms.flip(m, axis=None)[source]

Reverses the order of elements in an array along the given axis.

The shape of the array is preserved, but the elements are reordered.

Parameters
  • m (Tensor) – Input array.

  • axis (None or int or tuple of integers, optional) – Axis or axes along which to flip over. The default, axis=None, will flip over all of the axes of the input array. If axis is negative it counts from the last to the first axis. If axis is a tuple of integers, flipping is performed on all of the axes specified in the tuple.

Returns

Tensor, with the entries of axis reversed.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

GPU CPU

Example

>>> import mindspore.numpy as np
>>> A = np.arange(8.0).reshape((2,2,2))
>>> output = np.flip(A)
>>> print(output)
[[[7. 6]
[5. 4]]
[[3. 2]
[1. 0]]]
>>> output = np.flip(A, (0, 2))
>>> print(output)
[[[5. 4]
[7. 6]]
[[1. 0]
[3. 2]]]
tinyms.fliplr(m)[source]

Flips the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before.

Parameters

m (Tensor) – Input array.

Returns

Tensor.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

GPU CPU

Example

>>> import mindspore.numpy as np
>>> A = np.arange(8.0).reshape((2,2,2))
>>> output = np.fliplr(A)
>>> print(output)
[[[2. 3.]
[0. 1.]]
[[6. 7.]
[4. 5.]]]
tinyms.flipud(m)[source]

Flips the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before.

Parameters

m (Tensor) – Input array.

Returns

Tensor.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

GPU CPU

Example

>>> import mindspore.numpy as np
>>> A = np.arange(8.0).reshape((2,2,2))
>>> output = np.flipud(A)
>>> print(output)
[[[4. 5.]
[6. 7.]]
[[0. 1.]
[2. 3.]]]
tinyms.float_power(x1, x2, dtype=None)[source]

First array elements raised to powers from second array, element-wise.

Raise each base in x1 to the positionally-corresponding power in x2. x1 and x2 must be broadcastable to the same shape. This differs from the power function in that integers, float16, and float64 are promoted to floats with a minimum precision of float32 so that the result is always inexact. The intent is that the function will return a usable result for negative powers and seldom overflow for positive powers.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. Integers and floats are promoted to float32 instead of float64.

Parameters
  • x1 (Tensor) – the bases.

  • x2 (Tensor) – the exponenets.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the bases in x1 raised to the exponents in x2. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.arange(6)
>>> x2 = np.array(3)
>>> output = np.float_power(x1, x2)
>>> print(output)
[  0.   1.   8.  27.  64. 125.]
tinyms.floor(x, dtype=None)[source]

Returns the floor of the input, element-wise.

The floor of the scalar x is the largest integer i, such that i <= x.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. On GPU, the supported dtypes are np.float16 and np.float32. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.

Parameters
  • x (Tensor) – input data.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the floor of each element in x. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.floor(np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]))
>>> print(output)
[-2. -2. -1.  0.  1.  1.  2.]
tinyms.floor_divide(x1, x2, dtype=None)[source]

Returns the largest integer smaller or equal to the division of the inputs. It is equivalent to the Python // operator and pairs with the Python % (remainder), function so that a = a % b + b * (a // b) up to roundoff.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – Input array.

  • x2 (Tensor) – Input array.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.floor_divide(np.array([1., 2., 3., 4.]), np.array(2.5))
>>> print(output)
[0. 0. 1. 1.]
tinyms.fmod(x1, x2, dtype=None)[source]

Returns the element-wise remainder of division.

This is the NumPy implementation of the C library function fmod, the remainder has the same sign as the dividend x1. It is equivalent to the Matlab(TM) rem function and should not be confused with the Python modulus operator x1 % x2.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – the first input arrays.

  • x2 (Tensor) – the second input arrays.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the remainder of the division of x1 by x2. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.fmod(np.array([-3, -2, -1, 1, 2, 3]), np.array(2))
>>> print(output)
[-1  0 -1  1  0  1]
tinyms.full(shape, fill_value, dtype=None)[source]

Returns a new tensor of given shape and type, filled with fill_value.

Parameters
  • shape (Union[int, tuple(int), list(int)]) – Shape of the new tensor, e.g., \((2, 3)\) or \(2\).

  • fill_value (Union[int, float, bool, list, tuple]) – Scalar or array_like fill value.

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype, if dtype is None, the data type of the new tensor will be inferred from fill_value. Default is None.

Returns

Tensor, with the designated shape and dtype, filled with fill_value.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If shape has entries < 0.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.full((2,2), True))
[[True True]
[True True]]
tinyms.full_like(a, fill_value, dtype=None, shape=None)[source]

Returns a full array with the same shape and type as a given array.

Note

Input array must have the same size across a dimension. If a is not a Tensor, dtype is float32 by default if not provided.

Parameters
  • a (Union[Tensor, list, tuple]) – The shape and data-type of a define these same attributes of the returned array.

  • fill_value (scalar) – Fill value.

  • dtype (mindspore.dtype, optional) – Overrides the data type of the result.

  • shape (int or sequence of ints, optional) – Overrides the shape of the result.

Returns

Tensor, array of fill_value with the same shape and type as a.

Raises

ValueError – if a is not a Tensor, list or tuple.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.ones((4,1,2))
>>> output = np.full_like(a, 0.5)
>>> print(output)
[[[0.5 0.5]]
[[0.5 0.5]]
[[0.5 0.5]]
[[0.5 0.5]]]
tinyms.gcd(x1, x2, dtype=None)[source]

Returns the greatest common divisor of |x1| and |x2|.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – input data.

  • x2 (Tensor) – input data.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the greatest common divisor of the absolute value of the inputs. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.gcd(np.arange(6), np.array(20))
>>> print(output)
[20  1  2  1  4  5]
tinyms.geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0)[source]

Returns numbers spaced evenly on a log scale (a geometric progression).

This is similar to logspace, but with endpoints specified directly. Each output sample is a constant multiple of the previous.

Parameters
  • start (Union[int, list(int), tuple(int), tensor]) – The starting value of the sequence.

  • stop (Union[int, list(int), tuple(int), tensor]) – The final value of the sequence, unless endpoint is False. In that case, num + 1 values are spaced over the interval in log-space, of which all but the last (a sequence of length num) are returned.

  • num (int, optional) – Number of samples to generate. Default is 50.

  • endpoint (bool, optional) – If True, stop is the last sample. Otherwise, it is not included. Default is True.

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype, can be in format of np.float32, or float32.If dtype is None, infer the data type from other input arguments. Default is None.

  • axis (int, optional) – The axis in the result to store the samples. Relevant only if start or stop is array-like. By default (0), the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end. Default is 0.

Returns

Tensor, with samples equally spaced on a log scale.

Raises

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> output = np.geomspace(1, 256, num=9)
>>> print(output)
[  1.   2.   4.   8.  16.  32.  64. 128. 256.]
>>> output = np.geomspace(1, 256, num=8, endpoint=False)
>>> print(output)
[  1.   2.   4.   8.  16.  32.  64. 128.]
tinyms.gradient(f, *varargs, axis=None, edge_order=1)[source]

Returns the gradient of a N-dimensional array. The gradient is computed using second order accurate central differences in the interior points and either first or second order accurate one-sides (forward or backwards) differences at the boundaries. The returned gradient hence has the same shape as the input array.

Note

Currently we only support edge_order`=1 and uniform spacing of `varargs.

Parameters
  • f (Union[tuple, list, Tensor]) – An N-dimensional array containing samples of a scalar function.

  • varargs (Union[tuple[number], tuple[tensor scalar]], optional) – Spacing between f values. Default unitary spacing for all dimensions. Spacing can be specified using: 1. single scalar to specify a sample distance for all dimensions. 2. N scalars to specify a constant sample distance for each dimension.

  • edge_order (int) – Gradient is calculated using N-th order accurate differences at the boundaries. Default: 1.

  • axis (Union[None, int, tuple(int), list(int)], optional) – Gradient is calculated only along the given axis or axes. The default (axis = None) is to calculate the gradient for all the axes of the input tensor. axis may be negative, in which case it counts from the last to the first axis.

Returns

gradient, a list of tensors (or a single tensor if there is only one dimension to be calculated). Each derivative has the same shape as f.

Raises
  • TypeError – if the inputs have types not specified above.

  • ValueError – if axis values out of bounds, or shape of f has entries < 1.

  • NotImplementedError – if edge_order != 1, or varargs contains non-scalar entries.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.gradient([[1, 2, 6], [3, 4, 5]], axis=-1)
>>> print(output)
[[1.  2.5 4. ]
[1.  1.  1. ]]
tinyms.greater(x1, x2, dtype=None)[source]

Returns the truth value of (x1 > x2) element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – Input array.

  • x2 (Tensor) – Input array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, element-wise comparison of x1 and x2. Typically of type bool, unless dtype is passed. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.greater(np.array([4, 2]), np.array([2, 2]))
>>> print(output)
[ True False]
tinyms.greater_equal(x1, x2, dtype=None)[source]

Returns the truth value of (x1 >= x2) element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – Input array.

  • x2 (Tensor) – Input array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, element-wise comparison of x1 and x2. Typically of type bool, unless dtype is passed. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.greater_equal(np.array([4, 2, 1]), np.array([2, 2, 2]))
>>> print(output)
[ True  True False]
tinyms.hamming(M)[source]

Returns the Hamming window. The Hamming window is a taper formed by using a weighted cosine.

Parameters

M (int) – Number of points in the output window. If zero or less, an empty array is returned.

Returns

Tensor, the window, with the maximum value normalized to one (the value one appears only if the number of samples is odd).

Raises

TypeError – if M is not an int.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.hamming(12))
[0.08000001 0.15302339 0.34890914 0.6054648  0.841236   0.9813669
0.9813668  0.8412359  0.6054647  0.34890908 0.15302327 0.08000001]
tinyms.hanning(M)[source]

Returns the Hanning window. The Hanning window is a taper formed by using a weighted cosine.

Parameters

M (int) – Number of points in the output window. If zero or less, an empty array is returned.

Returns

Tensor, the window, with the maximum value normalized to one (the value one appears only if the number of samples is odd).

Raises

TypeError – if M is not an int.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.hanning(12))
[0.         0.07937324 0.29229254 0.5711574  0.8274304  0.9797465
0.97974646 0.82743025 0.5711573  0.29229245 0.07937312 0.        ]
tinyms.heaviside(x1, x2, dtype=None)[source]

Computes the Heaviside step function.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – Input values.

  • x2 (Tensor) – The value of the function when x1 is 0. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the output array, element-wise Heaviside step function of x1. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.heaviside(np.array([-1.5, 0, 2.0]), np.array(0.5))
>>> print(output)
[0.  0.5 1. ]
>>> output = np.heaviside(np.array([-1.5, 0, 2.0]), np.array(1))
>>> print(output)
[0. 1. 1.]
tinyms.histogram(a, bins=10, range=None, weights=None, density=False)[source]

Computes the histogram of a dataset.

Note

String values for bins is not supported. Deprecated numpy argument normed is not supported.

Parameters
  • a (Union[int, float, bool, list, tuple, Tensor]) – Input data. The histogram is computed over the flattened array.

  • bins (Union[int, tuple, list, Tensor], optional) – If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths.

  • range ((float, float), optional) – The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()). Values outside the range are ignored. The first element of the range must be less than or equal to the second.

  • weights (Union[int, float, bool, list, tuple, Tensor], optional) – An array of weights, of the same shape as a. If density is True, the weights are normalized, so that the integral of the density over the range remains 1.

  • density (boolean, optional) – If False, the result will contain the number of samples in each bin. If True, the result is the value of the probability density function at the bin, normalized such that the integral over the range is 1. Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability mass function.

Returns

(Tensor, Tensor), the values of the histogram and the bin edges.

Raises

ValueError – if x and weights do not have the same size.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import numpy as np
>>> print(np.histogram([1, 2, 1], bins=[0, 1, 2, 3]))
(Tensor(shape=[3], dtype=Float32, value= [ 0.00000000e+00,  2.00000000e+00,  1.00000000e+00]),
Tensor(shape=[4], dtype=Int32, value= [0, 1, 2, 3]))
>>> print(np.histogram(np.arange(4), bins=np.arange(5), density=True))
(Tensor(shape=[4], dtype=Float32, value=
[ 2.50000000e-01,  2.50000000e-01,  2.50000000e-01,  2.50000000e-01]),
Tensor(shape=[5], dtype=Int32, value= [0, 1, 2, 3, 4]))
>>> print(np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3]))
(Tensor(shape=[3], dtype=Float32, value= [ 1.00000000e+00,  4.00000000e+00,  1.00000000e+00]),
Tensor(shape=[4], dtype=Int32, value= [0, 1, 2, 3]))
tinyms.histogram2d(x, y, bins=10, range=None, weights=None, density=False)[source]

Computes the multidimensional histogram of some data.

Note

Deprecated numpy argument normed is not supported.

Parameters
  • x (Union[list, tuple, Tensor]) – An array with shape (N,) containing the x coordinates of the points to be histogrammed.

  • y (Union[list, tuple, Tensor]) – An array with shape (N,) containing the y coordinates of the points to be histogrammed.

  • bins (Union[int, tuple, list], optional) –

    The bin specification:

    If int, the number of bins for the two dimensions (nx=ny=bins).

    If array_like, the bin edges for the two dimensions (x_edges=y_edges=bins).

    If [int, int], the number of bins in each dimension (nx, ny = bins).

    If [array, array], the bin edges in each dimension (x_edges, y_edges = bins).

    A combination [int, array] or [array, int], where int is the number of bins and array is the bin edges.

  • range (Union[list, tuple], optional) – has shape (2, 2), the leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the bins parameters): [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be considered outliers and not tallied in the histogram.

  • weights (Union[list, tuple, Tensor], optional) – An array with shape (N,) of values w_i weighing each sample (x_i, y_i).

  • density (boolean, optional) – If False, the default, returns the number of samples in each bin. If True, returns the probability density function at the bin, bin_count / sample_count / bin_volume.

Returns

(Tensor, Tensor, Tensor), the values of the bi-directional histogram and the bin edges along the first and second dimensions.

Raises

ValueError – if range does not have the same size as the number of samples.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import numpy as np
>>> x = np.arange(5)
>>> y = np.arange(2, 7)
>>> print(np.histogram2d(x, y, bins=(2, 3)))
(Tensor(shape=[2, 3], dtype=Float32, value=
[[ 2.00000000e+00,  0.00000000e+00,  0.00000000e+00],
[ 0.00000000e+00,  1.00000000e+00,  2.00000000e+00]]),
Tensor(shape=[3], dtype=Float32, value= [ 0.00000000e+00,  2.00000000e+00,  4.00000000e+00]),
Tensor(shape=[4], dtype=Float32, value=
[ 2.00000000e+00,  3.33333349e+00,  4.66666698e+00,  6.00000000e+00]))
tinyms.histogram_bin_edges(a, bins=10, range=None, weights=None)[source]

Function to calculate only the edges of the bins used by the histogram function.

Note

String values for bins is not supported.

Parameters
  • a (Union[int, float, bool, list, tuple, Tensor]) – Input data. The histogram is computed over the flattened array.

  • bins ((Union[int, tuple, list, Tensor])) – If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths.

  • range ((float, float), optional) – The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()). Values outside the range are ignored. The first element of the range must be less than or equal to the second. Default is None.

  • weights (Union[int, float, bool, list, tuple, Tensor], optional) – An array of weights, of the same shape as a. Each value in a only contributes its associated weight towards the bin count (instead of 1). This is currently not used by any of the bin estimators, but may be in the future. Default is None.

Returns

Tensor, the edges to pass into histogram.

Supported Platforms:

Ascend GPU CPU

Raises

TypeError – if bins is an array and not one-dimensional.

Examples

>>> import mindspore.numpy as np
>>> arr = np.array([0, 0, 0, 1, 2, 3, 3, 4, 5])
>>> print(np.histogram_bin_edges(arr, bins=2))
[0.  2.5 5. ]
tinyms.histogramdd(sample, bins=10, range=None, weights=None, density=False)[source]

Computes the multidimensional histogram of some data.

Note

Deprecated numpy argument normed is not supported.

Parameters
  • sample (Union[list, tuple, Tensor]) –

    The data to be histogrammed, either (N, D) array, or (D, N) array_like. Note the unusual interpretation of sample when an array_like:

    When an array, each row is a coordinate in a D-dimensional space, such as histogramdd(np.array([p1, p2, p3])).

    When an array_like, each element is the list of values for single coordinate, such as histogramdd((X, Y, Z)).

    The first form should be preferred.

  • bins (Union[int, tuple, list], optional) –

    The bin specification:

    A sequence of arrays describing the monotonically increasing bin edges along each dimension.

    The number of bins for each dimension (nx, ny, =bins)

    The number of bins for all dimensions (nx=ny=…=bins).

  • range (Union[list, tuple], optional) – A sequence of length D, each an optional (lower, upper) tuple giving the outer bin edges to be used if the edges are not given explicitly in bins. An entry of None in the sequence results in the minimum and maximum values being used for the corresponding dimension. The default, None, is equivalent to passing a tuple of D None values.

  • weights (Union[list, tuple, Tensor], optional) – An array with shape (N,) of values w_i weighing each sample (x_i, y_i, z_i, …).

  • density (boolean, optional) – If False, the default, returns the number of samples in each bin. If True, returns the probability density function at the bin, bin_count / sample_count / bin_volume.

Returns

(Tensor, list of Tensor), the values of the histogram and the bin edges.

Raises

ValueError – if range does not have the same size as the number of samples.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import numpy as np
>>> sample = np.arange(15).reshape(5, 3)
>>> print(sample)
[[ 0  1  2]
[ 3  4  5]
[ 6  7  8]
[ 9 10 11]
[12 13 14]]
>>> print(np.histogramdd(sample, bins=(2, 3, 4)))
(Tensor(shape=[2, 3, 4], dtype=Float32, value=
[[[ 1.00000000e+00,  1.00000000e+00,  0.00000000e+00,  0.00000000e+00],
[ 0.00000000e+00,  0.00000000e+00,  0.00000000e+00,  0.00000000e+00],
[ 0.00000000e+00,  0.00000000e+00,  0.00000000e+00,  0.00000000e+00]],
[[ 0.00000000e+00,  0.00000000e+00,  0.00000000e+00,  0.00000000e+00],
[ 0.00000000e+00,  0.00000000e+00,  1.00000000e+00,  0.00000000e+00],
[ 0.00000000e+00,  0.00000000e+00,  0.00000000e+00,  2.00000000e+00]]]),
[Tensor(shape=[3], dtype=Float32, value= [ 0.00000000e+00,  6.00000000e+00,  1.20000000e+01]),
Tensor(shape=[4], dtype=Float32, value=
[ 1.00000000e+00,  5.00000000e+00,  9.00000000e+00,  1.30000000e+01]),
Tensor(shape=[5], dtype=Float32, value=
[ 2.00000000e+00,  5.00000000e+00,  8.00000000e+00,  1.10000000e+01,  1.40000000e+01])])
tinyms.hsplit(x, indices_or_sections)[source]

Splits a tensor into multiple sub-tensors horizontally (column-wise). It is equivalent to split with \(axis=1\) (default), the array is always split along the second axis regardless of the array dimension.

Parameters
  • x (Tensor) – A Tensor to be divided.

  • indices_or_sections (Union[int, tuple(int), list(int)]) – If integer, \(N\), the tensor will be divided into \(N\) equal tensors along axis. If tuple(int), list(int) or of sorted integers, the entries indicate where along axis the array is split. For example, \([2, 3]\) would, for \(axis=0\), result in three sub-tensors \(x[:2]\), \(x[2:3]\). If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.

Returns

A list of sub-tensors.

Raises

TypeError – If argument indices_or_sections is not integer.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> input_x = np.arange(6).reshape((2, 3)).astype('float32')
>>> output = np.hsplit(input_x, 3)
>>> print(output)
(Tensor(shape=[2, 1], dtype=Float32,
value=[[ 0.00000000e+00],
       [ 3.00000000e+00]]),
Tensor(shape=[2, 1], dtype=Float32,
value=[[ 1.00000000e+00],
       [ 4.00000000e+00]]),
Tensor(shape=[2, 1], dtype=Float32,
value=[[ 2.00000000e+00],
       [ 5.00000000e+00]]))
tinyms.hstack(tup)[source]

Stacks tensors in sequence horizontally. This is equivalent to concatenation along the second axis, except for 1-D tensors where it concatenates along the first axis.

Parameters

tup (Union[Tensor, tuple, list]) – A sequence of 1-D or 2-D tensors. The tensors must have the same shape along all but the second axis, except 1-D tensors which can be any length.

Returns

Stacked Tensor, formed by stacking the given tensors.

Supported Platforms:

Ascend GPU CPU

Raises

Examples

>>> import mindspore.numpy as np
>>> x1 = np.array([1, 2, 3]).astype('float32')
>>> x2 = np.array([4, 5, 6]).astype('float32')
>>> output = np.hstack((x1, x2))
>>> print(output)
[1. 2. 3. 4. 5. 6.]
tinyms.hypot(x1, x2, dtype=None)[source]

Given the “legs” of a right triangle, returns its hypotenuse.

Equivalent to sqrt(x1**2 + x2**2), element-wise. If x1 or x2 is scalar_like (i.e., unambiguously cast-able to a scalar type), it is broadcast for use with each element of the other argument. (See Examples)

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. On GPU, the supported dtypes are np.float16 and np.float32. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.

Parameters
  • x1 (Tensor) – Leg of the traingle(s).

  • x2 (Tensor) – Leg of the triangle(s). If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the hypotenuse of the triangle(s). This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.hypot(3*np.ones((3, 3)), 4*np.ones((3, 3)))
>>> print(output)
[[5. 5. 5.]
[5. 5. 5.]
[5. 5. 5.]]
>>> output = np.hypot(3*np.ones((3, 3)), np.array([4.0]))
>>> print(output)
[[5. 5. 5.]
[5. 5. 5.]
[5. 5. 5.]]
tinyms.identity(n, dtype=mindspore.float32)[source]

Returns the identity tensor.

Parameters
  • n (int) – Number of rows and columns in the output, must be larger than 0.

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype, default is mstype.float32.

Returns

A tensor of shape (n, n), where all elements are equal to zero, except for the diagonal, whose values are equal to one.

Supported Platforms:

Ascend GPU CPU

Raises

TypeError – If input arguments have types not specified above.

Examples

>>> import mindspore.numpy as np
>>> print(np.identity(2))
[[1. 0.]
[0. 1.]]
tinyms.in1d(ar1, ar2, invert=False)[source]

Tests whether each element of a 1-D array is also present in a second array.

Returns a boolean array the same length as ar1 that is True where an element of ar1 is in ar2 and False otherwise.

Note

Numpy argument assume_unique is not supported since the implementation does not rely on the uniqueness of the input arrays.

Parameters
  • ar1 (Union[int, float, bool, list, tuple, Tensor]) – Input array with shape (M,).

  • ar2 (Union[int, float, bool, list, tuple, Tensor]) – The values against which to test each value of ar1.

  • invert (boolean, optional) – If True, the values in the returned array are inverted (that is, False where an element of ar1 is in ar2 and True otherwise). Default is False.

Returns

Tensor, with shape (M,). The values ar1[in1d] are in ar2.

Supported Platforms:

Ascend GPU CPU

Examples

>>> test = np.array([0, 1, 2, 5, 0])
>>> states = [0, 2]
>>> mask = np.in1d(test, states)
>>> print(mask)
[ True False  True False  True]
>>> mask = np.in1d(test, states, invert=True)
>>> print(mask)
[False  True False  True False]
tinyms.indices(dimensions, dtype=mindspore.int32, sparse=False)[source]

Returns an array representing the indices of a grid.

Computes an array where the subarrays contain index values 0, 1, … varying only along the corresponding axis.

Parameters
  • dimensions (tuple or list of ints) – The shape of the grid.

  • dtype (mindspore.dtype, optional) – Data type of the result.

  • sparse (boolean, optional) – Defaults to False. Return a sparse representation of the grid instead of a dense representation.

Returns

Tensor or tuple of Tensor, If sparse is False, returns one array of grid indices, grid.shape = (len(dimensions),) + tuple(dimensions). If sparse is True, returns a tuple of arrays, with grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1) with dimensions[i] in the ith place

Raises

TypeError – if input dimensions is not a tuple or list.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> grid = np.indices((2, 3))
>>> print(grid)
[Tensor(shape=[2, 3], dtype=Int32, value=
[[0, 0, 0],
[1, 1, 1]]), Tensor(shape=[2, 3], dtype=Int32, value=
[[0, 1, 2],
[0, 1, 2]])]
tinyms.inner(a, b)[source]

Returns the inner product of two tensors.

Ordinary inner product of vectors for 1-D tensors (without complex conjugation), in higher dimensions a sum product over the last axes.

Note

Numpy argument out is not supported. On GPU, the supported dtypes are np.float16, and np.float32. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.

Parameters
  • a (Tensor) – input tensor. If a and b are nonscalar, their last dimensions must match.

  • b (Tensor) – input tensor. If a and b are nonscalar, their last dimensions must match.

Returns

Tensor or scalar.

Raises

ValueError – if x1.shape[-1] != x2.shape[-1].

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.ones((5, 3))
>>> b = np.ones((2, 7, 3))
>>> output = np.inner(a, b)
>>> print(output)
[[[3. 3. 3. 3. 3. 3. 3.]
[3. 3. 3. 3. 3. 3. 3.]]
[[3. 3. 3. 3. 3. 3. 3.]
[3. 3. 3. 3. 3. 3. 3.]]
[[3. 3. 3. 3. 3. 3. 3.]
[3. 3. 3. 3. 3. 3. 3.]]
[[3. 3. 3. 3. 3. 3. 3.]
[3. 3. 3. 3. 3. 3. 3.]]
[[3. 3. 3. 3. 3. 3. 3.]
[3. 3. 3. 3. 3. 3. 3.]]]
tinyms.interp(x, xp, fp, left=None, right=None)[source]

One-dimensional linear interpolation for monotonically increasing sample points. Returns the one-dimensional piecewise linear interpolant to a function with given discrete data points (xp, fp), evaluated at x.

Note

Numpy argument period is not supported. Complex values are not supported.

Parameters
  • x (Union[int, float, bool, list, tuple, Tensor]) – The x-coordinates at which to evaluate the interpolated values.

  • xp (Union[int, float, bool, list, tuple, Tensor]) – 1-D sequence of floats, the x-coordinates of the data points, must be increasing.

  • fp (Union[int, float, bool, list, tuple, Tensor]) – 1-D sequence of floats, the y-coordinates of the data points, same length as xp.

  • left (float, optional) – Value to return for x < xp[0], default is fp[0] once obtained.

  • right (float, optional) – Value to return for x > xp[-1], default is fp[-1] once obtained.

Returns

Tensor, the interpolated values, same shape as x.

Raises

ValueError – if xp or fp is not one-dimensional, or if xp and fp do not have the same length.

Supported Platforms:

Ascend GPU CPU

Examples

>>> xp = [1, 2, 3]
>>> fp = [3, 2, 0]
>>> print(np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp))
[3.         3.         2.5        0.55999994 0.        ]
>>> UNDEF = -99.0
>>> print(np.interp(3.14, xp, fp, right=UNDEF))
-99.0
tinyms.invert(x, dtype=None)[source]

Computes bit-wise inversion, or bit-wise NOT, element-wise. Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ~. For signed integer inputs, the two’s complement is returned. In a two’s-complement system negative numbers are represented by the two’s complement of the absolute value. This is the most common method of representing signed integers on computers [1]. A N-bit two’s-complement system can represent every integer in the range -2^{N-1} to +2^{N-1}-1.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. Supported dtypes on Ascend: np.int16, np.uint16.

Parameters
  • x (Tensor) – Only integer and boolean types are handled.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar.

Supported Platforms:

Ascend

Examples

>>> import mindspore.numpy as np
>>> print(np.invert(np.array(13, dtype=np.uint16)))
65522
tinyms.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)[source]

Returns a boolean tensor where two tensors are element-wise equal within a tolerance.

The tolerance values are positive, typically very small numbers. The relative difference (\(rtol * abs(b)\)) and the absolute difference atol are added together to compare against the absolute difference between a and b.

Note

For finite values, isclose uses the following equation to test whether two floating point values are equivalent. \(absolute(a - b) <= (atol + rtol * absolute(b))\) On Ascend, input arrays containing inf or NaN are not supported.

Parameters
  • a (Union[Tensor, list, tuple]) – Input first tensor to compare.

  • b (Union[Tensor, list, tuple]) – Input second tensor to compare.

  • rtol (numbers.Number) – The relative tolerance parameter (see Note).

  • atol (numbers.Number) – The absolute tolerance parameter (see Note).

  • equal_nan (bool) – Whether to compare NaN as equal. If True, NaN in a will be considered equal to NaN in b in the output tensor.

Returns

A bool tensor of where a and b are equal within the given tolerance.

Raises

TypeError – If inputs have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> a = np.array([0,1,2,float('inf'),float('inf'),float('nan')])
>>> b = np.array([0,1,-2,float('-inf'),float('inf'),float('nan')])
>>> print(np.isclose(a, b))
[ True  True False False  True False]
>>> print(np.isclose(a, b, equal_nan=True))
[ True  True False False  True  True]
tinyms.isfinite(x, dtype=None)[source]

Tests element-wise for finiteness (not infinity or not Not a Number).

The result is returned as a boolean array.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. On GPU, the supported dtypes are np.float16, and np.float32.

Parameters
  • x (Tensor) – Input values.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, true where x is not positive infinity, negative infinity, or NaN; false otherwise. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.isfinite(np.array([np.inf, 1., np.nan]).astype('float32'))
>>> print(output)
[False  True False]
tinyms.isin(element, test_elements, invert=False)[source]

Calculates element in test_elements, broadcasting over element only. Returns a boolean array of the same shape as element that is True where an element of element is in test_elements and False otherwise.

Note

Numpy argument assume_unique is not supported since the implementation does not rely on the uniqueness of the input arrays.

Parameters
  • element (Union[int, float, bool, list, tuple, Tensor]) – Input array.

  • test_elements (Union[int, float, bool, list, tuple, Tensor]) – The values against which to test each value of element.

  • invert (boolean, optional) – If True, the values in the returned array are inverted, as if calculating element not in test_elements. Default is False.

Returns

Tensor, has the same shape as element. The values element[isin] are in test_elements.

Supported Platforms:

Ascend GPU CPU

Examples

>>> element = 2*np.arange(4).reshape((2, 2))
>>> test_elements = [1, 2, 4, 8]
>>> mask = np.isin(element, test_elements)
>>> print(mask)
[[False  True]
[ True False]]
>>> mask = np.isin(element, test_elements, invert=True)
>>> print(mask)
[[ True False]
[False  True]]
tinyms.isinf(x, dtype=None)[source]

Tests element-wise for positive or negative infinity.

Returns a boolean array of the same shape as x, True where x == +/-inf, otherwise False.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. Only np.float32 is currently supported.

Parameters
  • x (Tensor) – Input values.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, true where x is positive or negative infinity, false otherwise. This is a scalar if x is a scalar.

Supported Platforms:

GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.isinf(np.array(np.inf, np.float32))
>>> print(output)
True
>>> output = np.isinf(np.array([np.inf, -np.inf, 1.0, np.nan], np.float32))
>>> print(output)
[ True  True False False]
tinyms.isnan(x, dtype=None)[source]

Tests element-wise for NaN and return result as a boolean array.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. Only np.float32 is currently supported.

Parameters
  • x (Tensor) – Input values.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, true where x is NaN, false otherwise. This is a scalar if x is a scalar.

Supported Platforms:

GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.isnan(np.array(np.nan, np.float32))
>>> print(output)
True
>>> output = np.isnan(np.array(np.inf, np.float32))
>>> print(output)
False
tinyms.isneginf(x)[source]

Tests element-wise for negative infinity, returns result as bool array.

Note

Numpy argument out is not supported. Only np.float32 is currently supported.

Parameters

x (Tensor) – Input values.

Returns

Tensor or scalar, true where x is negative infinity, false otherwise. This is a scalar if x is a scalar.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.isneginf(np.array([-np.inf, 0., np.inf, np.nan], np.float32))
>>> print(output)
[ True False False False]
tinyms.isposinf(x)[source]

Tests element-wise for positive infinity, returns result as bool array.

Note

Numpy argument out is not supported. Only np.float32 is currently supported.

Parameters

x (Tensor) – Input values.

Returns

Tensor or scalar, true where x is positive infinity, false otherwise. This is a scalar if x is a scalar.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.isposinf(np.array([-np.inf, 0., np.inf, np.nan], np.float32))
>>> print(output)
[False False  True False]
tinyms.isscalar(element)[source]

Returns True if the type of element is a scalar type.

Note

Only object types recognized by the mindspore parser are supported, which includes objects, types, methods and functions defined within the scope of mindspore. Other built-in types are not supported.

Parameters

element (any) – Input argument, can be of any type and shape.

Returns

Boolean, True if element is a scalar type, False if it is not.

Raises

TypeError – if the type of element is not supported by mindspore parser.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.isscalar(3.1)
>>> print(output)
True
>>> output = np.isscalar(np.array(3.1))
>>> print(output)
False
>>> output = np.isscalar(False)
>>> print(output)
True
>>> output = np.isscalar('numpy')
>>> print(output)
True
tinyms.ix_(*args)[source]

Constructs an open mesh from multiple sequences.

This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in all but one dimension and the dimension with the non-unit shape value cycles through all N dimensions. Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].

Note

Boolean masks are not supported.

Parameters

*args (Tensor) – 1-D sequences.

Returns

Tuple of Tensor, N arrays with N dimensions each, with N the number of input sequences. Together these arrays form an open mesh.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> ixgrid = np.ix_(np.array([0, 1]), np.array([2, 4]))
>>> print(ixgrid)
(Tensor(shape=[2, 1], dtype=Int32, value=
[[0],
[1]]), Tensor(shape=[1, 2], dtype=Int32, value=
[[2, 4]]))
tinyms.kron(a, b)[source]

Kronecker product of two arrays.

Computes the Kronecker product, a composite array made of blocks of the second array scaled by the first.

Note

Booleans are not supported.

Parameters
Returns

Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.kron([1,10,100], [5,6,7])
>>> print(output)
[  5   6   7  50  60  70 500 600 700]
>>> output = np.kron([5,6,7], [1,10,100])
>>> print(output)
[  5  50 500   6  60 600   7  70 700]
>>> output = np.kron(np.eye(2), np.ones((2,2)))
>>> print(output)
[[1. 1. 0. 0.]
[1. 1. 0. 0.]
[0. 0. 1. 1.]
[0. 0. 1. 1.]]
tinyms.lcm(x1, x2, dtype=None)[source]

Returns the lowest common multiple of |x1| and |x2|.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – input data.

  • x2 (Tensor) – input data.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the lowest common multiple of the absolute value of the inputs. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.lcm(np.arange(6), np.array(20))
>>> print(output)
[ 0 20 20 60 20 20]
tinyms.less(x1, x2, dtype=None)[source]

Returns the truth value of (x1 < x2) element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – input array.

  • x2 (Tensor) – Input array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, element-wise comparison of x1 and x2. Typically of type bool, unless dtype is passed. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.less(np.array([1, 2]), np.array([2, 2]))
>>> print(output)
[ True False]
tinyms.less_equal(x1, x2, dtype=None)[source]

Returns the truth value of (x1 <= x2) element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – Input array.

  • x2 (Tensor) – Input array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, element-wise comparison of x1 and x2. Typically of type bool, unless dtype is passed. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.less_equal(np.array([4, 2, 1]), np.array([2, 2, 2]))
>>> print(output)
[False  True  True]
tinyms.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)[source]

Returns evenly spaced values within a given interval.

Parameters
  • start (Union[int, list(int), tuple(int), tensor]) – The starting value of the sequence.

  • stop (Union[int, list(int), tuple(int), tensor]) – The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False.

  • num (int, optional) – Number of samples to generate. Default is 50.

  • endpoint (bool, optional) – If True, stop is the last sample. Otherwise, it is not included. Default is True.

  • retstep (bool, optional) – If True, return (samples, step), where step is the spacing between samples.

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype, If dtype is None, infer the data type from other input arguments. Default is None.

  • axis (int, optional) – The axis in the result to store the samples. Relevant only if start or stop are array-like. By default, the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end. Default is 0.

Returns

Tensor, with num equally spaced samples in the closed interval \([start, stop]\) or the half-open interval \([start, stop)\) (depending on whether endpoint is True or False).

Step, the size of spacing between samples, only returned if retstep is True.

Raises

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.linspace(0, 5, 6))
[0. 1. 2. 3. 4. 5.]
tinyms.log(x, dtype=None)[source]

Returns the natural logarithm, element-wise.

The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. The natural logarithm is logarithm in base e.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. On GPU, the supported dtypes are np.float16, and np.float32. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.

Parameters
  • x (Tensor) – Input array.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the natural logarithm of x, element-wise. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([2, 3, 4]).astype('float32')
>>> output = np.log(x)
>>> print(output)
[0.69314575 1.09861    1.3862929 ]
tinyms.log10(x, dtype=None)[source]

Base-10 logarithm of x.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([10, 100, 1000]).astype('float16')
>>> output = np.log10(x)
>>> print(output)
[1. 2. 3.]
tinyms.log1p(x, dtype=None)[source]

Returns the natural logarithm of one plus the input array, element-wise.

Calculates log(1 + x).

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input array.

  • dtype (mindspore.dtype) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([1, 2, 3]).astype('float16')
>>> output = np.log1p(x)
>>> print(output)
[0.6934 1.099 1.387 ]
tinyms.log2(x, dtype=None)[source]

Base-2 logarithm of x.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([2, 4, 8]).astype('float16')
>>> output = np.log2(x)
>>> print(output)
[1. 2. 3.]
tinyms.logaddexp(x1, x2, dtype=None)[source]

Logarithm of the sum of exponentiations of the inputs.

Calculates log(exp(x1) + exp(x2)). This function is useful in statistics where the calculated probabilities of events may be so small as to exceed the range of normal floating point numbers. In such cases the logarithm of the calculated probability is stored. This function allows adding probabilities stored in such a fashion.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – Input array.

  • x2 (Tensor) – Input array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.array([1, 2, 3]).astype('float16')
>>> x2 = np.array(2).astype('float16')
>>> output = np.logaddexp(x1, x2)
>>> print(output)
[2.312 2.693 3.312]
tinyms.logaddexp2(x1, x2, dtype=None)[source]

Logarithm of the sum of exponentiations of the inputs in base of 2.

Calculates log2(2**x1 + 2**x2). This function is useful in machine learning when the calculated probabilities of events may be so small as to exceed the range of normal floating point numbers. In such cases the base-2 logarithm of the calculated probability can be used instead. This function allows adding probabilities stored in such a fashion.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – Input tensor.

  • x2 (Tensor) – Input tensor. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.array([2, 4, 8]).astype('float16')
>>> x2 = np.array(2).astype('float16')
>>> output = np.logaddexp2(x1, x2)
>>> print(output)
[3. 4.32 8.02]
tinyms.logical_and(x1, x2, dtype=None)[source]

Computes the truth value of x1 AND x2 element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – Input tensor.

  • x2 (Tensor) – Input tensor. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. Boolean result of the logical AND operation applied to the elements of x1 and x2; the shape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.array([True, False])
>>> x2 = np.array([False, False])
>>> output = np.logical_and(x1, x2)
>>> print(output)
[False False]
tinyms.logical_not(a, dtype=None)[source]

Computes the truth value of NOT a element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • a (Tensor) – The input tensor whose dtype is bool.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. Boolean result with the same shape as a of the NOT operation on elements of a. This is a scalar if a is a scalar.

Raises

TypeError – if the input is not a tensor or its dtype is not bool.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.array([True, False])
>>> output = np.logical_not(a)
>>> print(output)
[False  True]
tinyms.logical_or(x1, x2, dtype=None)[source]

Computes the truth value of x1 OR x2 element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – Input tensor.

  • x2 (Tensor) – Input tensor. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.array([True, False])
>>> x2 = np.array([False, True])
>>> output = np.logical_or(x1, x2)
>>> print(output)
[ True  True]
tinyms.logical_xor(x1, x2, dtype=None)[source]

Computes the truth value of x1 XOR x2, element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – Input tensor.

  • x2 (Tensor) – Input tensor. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. Boolean result of the logical AND operation applied to the elements of x1 and x2; the shape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.array([True, False])
>>> x2 = np.array([False, False])
>>> output = np.logical_xor(x1, x2)
>>> print(output)
[True False]
tinyms.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0)[source]

Returns numbers spaced evenly on a log scale.

In linear space, the sequence starts at base ** start (base to the power of start) and ends with base ** stop (see endpoint below).

Parameters
  • start (Union[int, list(int), tuple(int), tensor]) – base ** start is the starting value of the sequence.

  • stop (Union[int, list(int), tuple(int), tensor]) – base ** stop is the final value of the sequence, unless endpoint is False. In that case, num + 1 values are spaced over the interval in log-space, of which all but the last (a sequence of length num) are returned.

  • num (int, optional) – Number of samples to generate. Default is 50.

  • endpoint (bool, optional) – If True, stop is the last sample. Otherwise, it is not included. Default is True.

  • base (Union[int, float], optional) – The base of the log space. The step size between the elements in \(ln(samples) / ln(base)\) (or \(log_{base}(samples)\)) is uniform. Default is 10.0.

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype. If dtype is None, infer the data type from other input arguments. Default is None.

  • axis (int, optional) – The axis in the result to store the samples. Relevant only if start or stop is array-like. By default, the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end. Default is 0.

Returns

Tensor, equally spaced on a log scale.

Raises

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.logspace(0, 5, 6, base=2.0))
[ 1.  2.  4.  8. 16. 32.]
tinyms.matmul(x1, x2, dtype=None)[source]

Returns the matrix product of two arrays.

Note

Numpy arguments out, casting, order, subok, signature, and extobj are not supported. On GPU, the supported dtypes are np.float16 and np.float32. On CPU, the supported dtypes are np.float16 and np.float32.

Parameters
  • x1 (Tensor) – Input tensor, scalar not allowed.

  • x2 (Tensor) – Input tensor, scalar not allowed.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the matrix product of the inputs. This is a scalar only when both x1, x2 are 1-d vectors.

Raises

ValueError – If the last dimension of x1 is not the same size as the second-to-last dimension of x2, or if a scalar value is passed in.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.arange(2*3*4).reshape(2, 3, 4).astype('float32')
>>> x2 = np.arange(4*5).reshape(4, 5).astype('float32')
>>> output = np.matmul(x1, x2)
>>> print(output)
[[[  70.   76.   82.   88.   94.]
[ 190.  212.  234.  256.  278.]
[ 310.  348.  386.  424.  462.]]
[[ 430.  484.  538.  592.  646.]
[ 550.  620.  690.  760.  830.]
[ 670.  756.  842.  928. 1014.]]]
tinyms.max(a, axis=None, keepdims=False, initial=None, where=True)

Returns the maximum of an array or maximum along an axis.

Note

Numpy argument out is not supported. On GPU, the supported dtypes are np.float16, and np.float32.

Parameters
  • a (Tensor) – Input data.

  • axis (None or int or tuple of integers, optional) – defaults to None. Axis or axes along which to operate. By default, flattened input is used. If this is a tuple of integers, the maximum is selected over multiple axes, instead of a single axis or all the axes as before.

  • keepdims (boolean, optional) – defaults to False. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

  • initial (scalar, optional) – defaults to None. The minimum value of an output element. Must be present to allow computation on empty slice.

  • where (boolean Tensor, optional) – defaults to True. A boolean array which is broadcasted to match the dimensions of array, and selects elements to include in the reduction. If non-default value is passed, initial must also be provided.

Returns

Tensor or scalar, maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.arange(4).reshape((2,2)).astype('float32')
>>> output = np.amax(a)
>>> print(output)
3.0
>>> output = np.amax(a, axis=0)
>>> print(output)
[2. 3.]
>>> output = np.amax(a, axis=1)
>>> print(output)
[1. 3.]
>>> output = np.amax(a, where=np.array([False, True]), initial=-1, axis=0)
>>> print(output)
[-1.  3.]
tinyms.maximum(x1, x2, dtype=None)[source]

Returns the element-wise maximum of array elements.

Compares two arrays and returns a new array containing the element-wise maxima.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. On Ascend, input arrays containing inf or NaN are not supported.

Parameters
  • x1 (Tensor) – Input array

  • x2 (Tensor) – The array holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.maximum(np.array([2, 3, 4]), np.array([1, 5, 2]))
>>> print(output)
[2 5 4]
tinyms.mean(a, axis=None, keepdims=False, dtype=None)[source]

Computes the arithmetic mean along the specified axis.

Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis.

Note

Numpy arguments out is not supported. On GPU, the supported dtypes are np.float16, and np.float32.

Parameters
  • a (Tensor) – input tensor containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

  • axis (None or int or tuple of integers, optional) – Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. If this is a tuple of ints, a mean is performed over multiple axes.

  • keepdims (bool, optional) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input tensor.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, an array containing the mean values.

Raises

ValueError – if axes are out of the range of [-a.ndim, a.ndim), or if the axes contain duplicates.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.arange(6, dtype='float32')
>>> output = np.mean(a, 0)
>>> print(output)
2.5
tinyms.meshgrid(*xi, sparse=False, indexing='xy')[source]

Returns coordinate matrices from coordinate vectors.

Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,…, xn.

Note

Numpy argument copy is not supported, and a copy is always returned.

Parameters
  • *xi (Tensor) – 1-D arrays representing the coordinates of a grid.

  • indexing (‘xy’, ‘ij’, optional) – Cartesian (‘xy’, default) or matrix (‘ij’) indexing of output. In the 2-D case with inputs of length M and N, the outputs are of shape (N, M) for ‘xy’ indexing and (M, N) for ‘ij’ indexing. In the 3-D case with inputs of length M, N and P, outputs are of shape (N, M, P) for ‘xy’ indexing and (M, N, P) for ‘ij’ indexing.

  • sparse (bool, optional) – If True a sparse grid is returned in order to conserve memory. Default is False.

Returns

Tuple of tensors, for vectors x1, x2,…, xn with lengths Ni=len(xi), return (N1, N2, N3,…Nn) shaped arrays if indexing=’ij’ or (N2, N1, N3,…Nn) shaped arrays if indexing=’xy’ with the elements of xi repeated to fill the matrix along the first dimension for x1, the second for x2 and so on.

Raises

TypeError – if the input is not a tensor, or sparse is not boolean, or indexing is not ‘xy’ or ‘ij’.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.linspace(0, 1, 3)
>>> y = np.linspace(0, 1, 2)
>>> xv, yv = np.meshgrid(x, y)
>>> print(xv)
[[0.  0.5 1. ]
[0.  0.5 1. ]]
>>> print(yv)
[[0.  0.  0.]
[1.  1.  1.]]
>>> xv, yv = np.meshgrid(x, y, sparse=True)
>>> print(xv)
[[0.  0.5  1. ]]
>>> print(yv)
[[0.]
[1.]]
tinyms.min(a, axis=None, keepdims=False, initial=None, where=True)

Returns the minimum of an array or minimum along an axis.

Note

Numpy argument out is not supported. On GPU, the supported dtypes are np.float16, and np.float32.

Parameters
  • a (Tensor) – Input data.

  • axis (None or int or tuple of integers, optional) – defaults to None. Axis or axes along which to operate. By default, flattened input is used. If this is a tuple of integers, the minimum is selected over multiple axes, instead of a single axis or all the axes as before.

  • keepdims (bool, optional) – defaults to False. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

  • initial (Number, optional) – defaults to None. The maximum value of an output element. Must be present to allow computation on empty slice.

  • where (bool Tensor, optional) – defaults to True. A boolean array which is broadcasted to match the dimensions of array, and selects elements to include in the reduction. If non-default value is passed, initial must also be provided.

Returns

Tensor or scalar, minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.arange(4).reshape((2,2)).astype('float32')
>>> output = np.amin(a)
>>> print(output)
0.0
>>> output = np.amin(a, axis=0)
>>> print(output)
[0. 1.]
>>> output = np.amin(a, axis=1)
>>> print(output)
[0. 2.]
>>> output = np.amin(a, where=np.array([False, True]), initial=10, axis=0)
>>> print(output)
[10.  1.]
tinyms.minimum(x1, x2, dtype=None)[source]

Element-wise minimum of tensor elements.

Compares two tensors and returns a new tensor containing the element-wise minima.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. On Ascend, input arrays containing inf or NaN are not supported.

Parameters
  • x1 (Tensor) – first input tensor to be compared.

  • x2 (Tensor) – second input tensor to be compared.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor, element-wise minimum of x1 and x2.

Raises
  • TypeError – If inputs have types not specified above.

  • ValueError – If the shapes of x1 and x2 cannot be broadcast.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.asarray([1, 2])
>>> b = np.asarray([[1, 3],[1, 4]])
>>> print(np.minimum(a, b))
[[1 2]
[1 2]]
tinyms.mod(x1, x2, dtype=None)

Returns element-wise remainder of division.

Computes the remainder complementary to the floor_divide function. It is equivalent to the Python modulus operator x1 % x2 and has the same sign as the divisor x2. The MATLAB function equivalent to np.remainder is mod.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – input array.

  • x2 (Tensor) – input array.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the element-wise remainder of the quotient floor_divide(x1, x2). This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.remainder(np.array([4, 7]), np.array([2, 3]))
>>> print(output)
[0 1]
>>> output = np.remainder(np.arange(7), np.array(5))
>>> print(output)
[0 1 2 3 4 0 1]
tinyms.moveaxis(a, source, destination)[source]

Moves axes of an array to new positions.

Other axes remain in their original order.

Parameters
  • a (Tensor) – The array whose axes should be reordered.

  • source (int or sequence of ints) – Original positions of the axes to move. These must be unique.

  • destination (int or sequence of ints) – Destination positions for each of the original axes. These must also be unique.

Returns

Tensor, array with moved axes.

Raises

ValueError – if axes are out of the range of [-a.ndim, a.ndim), or if the axes contain duplicates.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.zeros((3, 4, 5))
>>> output = np.moveaxis(x, 0, -1)
>>> print(output.shape)
(4, 5, 3)
>>> output = np.moveaxis(x, -1, 0)
>>> print(output.shape)
(5, 3, 4)
>>> output = np.moveaxis(x, [0, 1, 2], [-1, -2, -3])
>>> print(output.shape)
(5, 4, 3)
tinyms.multi_dot(arrays)[source]

Computes the dot product of two or more arrays in a single function call, while automatically selecting the fastest evaluation order. multi_dot chains numpy.dot and uses optimal parenthesization of the matrices [1] <en.wikipedia.org/wiki/Matrix_chain_multiplication>. Depending on the shapes of the matrices, this can speed up the multiplication a lot. If the first argument is 1-D it is treated as a row vector. If the last argument is 1-D it is treated as a column vector. The other arguments must be 2-D.

Note

Numpy argument out is not supported.

Parameters

arrays (sequence of array_like) – If the first argument is 1-D it is treated as row vector. If the last argument is 1-D it is treated as column vector. The other arguments must be 2-D.

Returns

Tensor, the dot product of the supplied arrays.

Raises

ValueError – arrays are not 2-D.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> A = np.ones((10000, 100))
>>> B = np.ones((100, 1000))
>>> C = np.ones((1000, 5))
>>> D = np.ones((5, 333))
>>> output = np.multi_dot([A, B, C, D])
>>> print(output)
[[500000. 500000. 500000. ... 500000. 500000. 500000.]
[500000. 500000. 500000. ... 500000. 500000. 500000.]
[500000. 500000. 500000. ... 500000. 500000. 500000.]
...
[500000. 500000. 500000. ... 500000. 500000. 500000.]
[500000. 500000. 500000. ... 500000. 500000. 500000.]
[500000. 500000. 500000. ... 500000. 500000. 500000.]]
tinyms.multiply(x1, x2, dtype=None)[source]

Multiplies arguments element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – input tensor to be multiplied.

  • x2 (Tensor) – input tensor to be multiplied.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the product of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.full((3, 2), [1, 2])
>>> x2 = np.full((3, 2), [3, 4])
>>> output = np.multiply(x1, x2)
>>> print(output)
[[3 8]
[3 8]
[3 8]]
tinyms.nancumsum(a, axis=None, dtype=None)[source]

Return the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are encountered and leading NaNs are replaced by zeros.

Zeros are returned for slices that are all-NaN or empty.

Note

If a.dtype is int8, int16 or bool, the result dtype will be elevated to int32.

Parameters
  • a (Tensor) – Input tensor.

  • axis (int, optional) – Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.

  • dtype (mindspore.dtype, optional) – If not specified, stay the same as a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.

Returns

Tensor.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If axis is out of range.

Supported Platforms:

GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.array([[1, 2], [3, np.nan]])
>>> output = np.nancumsum(a)
>>> print(output)
[1. 3. 6. 6.]
>>> output = np.nancumsum(a, axis=0)
>>> print(output)
[[1. 2.]
[4. 2.]]
>>> output = np.nancumsum(a, axis=1)
>>> print(output)
[[1. 3.]
[3. 3.]]
tinyms.nanmax(a, axis=None, dtype=None, keepdims=False)[source]

Return the maximum of an array or maximum along an axis, ignoring any NaNs.

Note

Numpy arguments out is not supported. For all NaN slices, a very small negative number is returned instead of NaN.

Parameters
  • a (Union[int, float, list, tuple, Tensor]) – Array containing numbers whose maximum is desired. If a is not an array, a conversion is attempted.

  • axis (Union[int, tuple of int, None], optional) – Axis or axes along which the maximum is computed. The default is to compute the maximum of the flattened array.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

  • keepdims (boolean, optional) – defaults to False. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

Returns

Tensor.

Raises

ValueError – if axes are out of the range of [-a.ndim, a.ndim), or if the axes contain duplicates.

Supported Platforms:

GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.array([[1, 2], [3, np.nan]])
>>> output = np.nanmax(a)
>>> print(output)
3.0
>>> output = np.nanmax(a, axis=0)
>>> print(output)
[3. 2.]
tinyms.nanmean(a, axis=None, dtype=None, keepdims=False)[source]

Computes the arithmetic mean along the specified axis, ignoring NaNs.

Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float32 intermediate and return values are used for integer inputs.

Note

Numpy arguments out is not supported.

Parameters
  • a (Union[int, float, list, tuple, Tensor]) – Array containing numbers whose mean is desired. If a is not an array, a conversion is attempted.

  • axis (Union[int, tuple of int, None], optional) – Axis or axes along which the mean is computed. The default is to compute the mean of the flattened array.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

  • keepdims (boolean, optional) – defaults to False. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

Returns

Tensor.

Raises

ValueError – if axes are out of the range of [-a.ndim, a.ndim), or if the axes contain duplicates.

Supported Platforms:

GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.array([[1, np.nan], [3, 4]])
>>> output = np.nanmean(a)
>>> print(output)
2.6666667
>>> output = np.nanmean(a, axis=0)
>>> print(output)
[2. 4.]
>>> output = np.nanmean(a, axis=1)
>>> print(output)
[1.  3.5]
tinyms.nanmin(a, axis=None, dtype=None, keepdims=False)[source]

Returns the minimum of array elements over a given axis, ignoring any NaNs.

Note

Numpy arguments out is not supported. For all-NaN slices, a very large number is returned instead of NaN. On Ascend, since checking for NaN is currently not supported, it is not recommended to use np.nanmin. If the array does not contain NaN, np.min should be used instead.

Parameters
  • a (Union[int, float, list, tuple, Tensor]) – Array containing numbers whose minimum is desired. If a is not an array, a conversion is attempted.

  • axis (Union[int, tuple of int, None], optional) – Axis or axes along which the minimum is computed. The default is to compute the minimum of the flattened array.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

  • keepdims (boolean, optional) – defaults to False. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

Returns

Tensor.

Raises

ValueError – if axes are out of the range of [-a.ndim, a.ndim), or if the axes contain duplicates.

Supported Platforms:

GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.array([[1, 2], [3, np.nan]])
>>> output = np.nanmin(a)
>>> print(output)
1.0
>>> output = np.nanmin(a, axis=0)
>>> print(output)
[1. 2.]
tinyms.nanstd(a, axis=None, dtype=None, ddof=0, keepdims=False)[source]

Computes the standard deviation along the specified axis, while ignoring NaNs.

Returns the standard deviation, a measure of the spread of a distribution, of the non-NaN array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

Note

Numpy arguments out is not supported. On GPU, the supported dtypes are np.float16, and np.float32.

Parameters
  • a (Union[int, float, list, tuple, Tensor]) – Calculates the standard deviation of the non-NaN values.

  • axis (Union[int, tuple of int, None], optional) – Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

  • ddof (int, optional) – “Delta Degrees of Freedom”: the divisor used in the calculation is N - ddof, where N represents the number of non-NaN elements. By default ddof is zero.

  • keepdims (boolean, optional) – defaults to False. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

Returns

Tensor.

Raises

ValueError – if axes are out of the range of [-a.ndim, a.ndim), or if the axes contain duplicates.

Supported Platforms:

GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.array([[1, np.nan], [3, 4]])
>>> output = np.nanstd(a)
>>> print(output)
1.2472192
>>> output = np.nanstd(a, axis=0)
>>> print(output)
[1. 0.]
>>> output = np.nanstd(a, axis=1)
>>> print(output)
[0.  0.5]
tinyms.nansum(a, axis=None, dtype=None, keepdims=False)[source]

Returns the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.

Note

Numpy arguments out is not supported.

Parameters
  • a (Union[int, float, list, tuple, Tensor]) – Array containing numbers whose sum is desired. If a is not an array, a conversion is attempted.

  • axis (Union[int, tuple of int, None], optional) – Axis or axes along which the sum is computed. The default is to compute the sum of the flattened array.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

  • keepdims (boolean, optional) – defaults to False. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

Returns

Tensor.

Raises

ValueError – if axes are out of the range of [-a.ndim, a.ndim), or if the axes contain duplicates.

Supported Platforms:

GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.array([[1, 1], [1, np.nan]])
>>> output = np.nansum(a)
>>> print(output)
3.0
>>> output = np.nansum(a, axis=0)
>>> print(output)
[2. 1.]
tinyms.nanvar(a, axis=None, dtype=None, ddof=0, keepdims=False)[source]

Computes the variance along the specified axis, while ignoring NaNs.

Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis.

Note

Numpy arguments out is not supported. On GPU, the supported dtypes are np.float16, and np.float32.

Parameters
  • a (Union[int, float, list, tuple, Tensor]) – Array containing numbers whose variance is desired. If a is not an array, a conversion is attempted.

  • axis (Union[int, tuple of int, None], optional) – Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

  • ddof (int, optional) – “Delta Degrees of Freedom”: the divisor used in the calculation is N - ddof, where N represents the number of non-NaN elements. By default ddof is zero.

  • keepdims (boolean, optional) – defaults to False. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.

Returns

Tensor.

Raises

ValueError – if axes are out of the range of [-a.ndim, a.ndim), or if the axes contain duplicates.

Supported Platforms:

GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.array([[1, np.nan], [3, 4]])
>>> output = np.nanvar(a)
>>> print(output)
1.5555557
>>> output = np.nanvar(a, axis=0)
>>> print(output)
[1. 0.]
>>> output = np.nanvar(a, axis=1)
>>> print(output)
[0.   0.25]
tinyms.negative(a, dtype=None)[source]

Numerical negative, element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • a (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.asarray([1, -1]).astype('float32')
>>> output = np.negative(a)
>>> print(output)
[-1. 1.]
tinyms.norm(x, ord=None, axis=None, keepdims=False)[source]

Matrix or vector norm. This function is able to return one of eight different matrix norms, or one of an infinite number of vector norms (described below), depending on the value of the ord parameter.

Note

Nuclear norm and 2-norm are not supported for matrices.

Parameters
  • x (Union[int, float, bool, list, tuple, Tensor]) – Input array. If axis is None, x must be 1-D or 2-D, unless ord is None. If both axis and ord are None, the 2-norm of x.ravel will be returned.

  • ord (Union[None, 'fro', 'nuc', inf, -inf, int, float], optional) – Order of the norm. inf means numpy’s inf object. The default is None.

  • axis (Union[None, int, 2-tuple of integers], optional) – If axis is an integer, it specifies the axis of x along which to compute the vector norms. If axis is a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix norms of these matrices are computed. If axis is None then either a vector norm (when x is 1-D) or a matrix norm (when x is 2-D) is returned. The default is None.

  • keepdims (boolean, optional) – If this is set to True, the axes which are normed over are left in the result as dimensions with size one. With this option the result will broadcast correctly against the original x.

Returns

Tensor, norm of the matrix or vector(s).

Raises

ValueError – If the norm order is not defined.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.norm(np.arange(9).astype(np.float32)))
14.282857
tinyms.not_equal(x1, x2, dtype=None)[source]

Returns (x1 != x2) element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – First input tensor to be compared.

  • x2 (Tensor) – Second input tensor to be compared.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, element-wise comparison of x1 and x2. Typically of type bool, unless dtype is passed. This is a scalar if both x1 and x2 are scalars.

Raises

TypeError – If the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.asarray([1, 2])
>>> b = np.asarray([[1, 3],[1, 4]])
>>> print(np.not_equal(a, b))
[[False  True]
[False  True]]
tinyms.not_equal(x1, x2, dtype=None)[source]

Returns (x1 != x2) element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – First input tensor to be compared.

  • x2 (Tensor) – Second input tensor to be compared.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, element-wise comparison of x1 and x2. Typically of type bool, unless dtype is passed. This is a scalar if both x1 and x2 are scalars.

Raises

TypeError – If the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.asarray([1, 2])
>>> b = np.asarray([[1, 3],[1, 4]])
>>> print(np.not_equal(a, b))
[[False  True]
[False  True]]
tinyms.ones(shape, dtype=mindspore.float32)[source]

Returns a new tensor of given shape and type, filled with ones.

Parameters
  • shape (Union[int, tuple, list]) – the shape of the new tensor.

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype. Default is mstype.float32.

Returns

Tensor, with the designated shape and dtype, filled with ones.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If shape entries have values \(< 0\).

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.ones((2,2)))
[[1. 1.]
[1. 1.]]
tinyms.ones_like(a, dtype=None, shape=None)[source]

Returns an array of ones with the same shape and type as a given array.

Note

Input array must have the same size across a dimension. If a is not a Tensor, dtype is float32 by default if not provided.

Parameters
  • a (Union[Tensor, list, tuple]) – The shape and data-type of a define these same attributes of the returned array.

  • dtype (mindspore.dtype, optional) – Overrides the data type of the result.

  • shape (int or sequence of ints, optional) – Overrides the shape of the result.

Returns

Tensor, array of ones with the same shape and type as a.

Raises

ValueError – if a is not a Tensor, list or tuple.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.ones((4,1,2))
>>> output = np.ones_like(a)
>>> print(output)
[[[1. 1.]]
[[1. 1.]]
[[1. 1.]]
[[1. 1.]]]
tinyms.outer(a, b)[source]

Computes the outer product of two vectors.

Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product is:

[[a0*b0  a0*b1 ... a0*bN ]

[a1*b0    .              ]

[ ...          .         ]

[aM*b0            aM*bN ]]

Note

Numpy argument out is not supported. On GPU, the supported dtypes are np.float16, and np.float32. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.

Parameters
  • a (Tensor) – first input vector. Input is flattened if not already 1-dimensional.

  • b (Tensor) – second input vector. Input is flattened if not already 1-dimensional.

Returns

Tensor or scalar, out[i, j] = a[i] * b[j].

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.full(7, 2).astype('float32')
>>> b = np.full(4, 3).astype('float32')
>>> output = np.outer(a, b)
>>> print(output)
[[6. 6. 6. 6.]
[6. 6. 6. 6.]
[6. 6. 6. 6.]
[6. 6. 6. 6.]
[6. 6. 6. 6.]
[6. 6. 6. 6.]
[6. 6. 6. 6.]]
tinyms.pad(arr, pad_width, mode='constant', stat_length=None, constant_values=0, end_values=0, reflect_type='even', **kwargs)[source]

Pads an array.

Note

Currently, median mode is not supported. reflect and symmetric mode only supports GPU backend.

Parameters
  • arr (Union[list, tuple, Tensor]) – The array to pad.

  • pad_width (Union[int, tuple, list]) – Number of values padded to the edges of each axis. ((before_1, after_1), ... (before_N, after_N)) creates unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes.

  • mode (string, optional) –

    One of the following string values:

    • constant (default): Pads with a constant value.

    • edge: Pads with the edge values of arr.

    • linear_ramp: Pads with the linear ramp between end_value and the arr edge value.

    • maximum: Pads with the maximum value of all or part of the vector along each axis.

    • mean: Pads with the mean value of all or part of the vector along each axis.

    • median: Pads with the median value of all or part of the vector along each axis.

    • minimum: Pads with the minimum value of all or part of the vector along each axis.

    • reflect: Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.

    • symmetric: Pads with the reflection of the vector mirrored along the edge of the arr.

    • wrap: Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning.

    • empty: Pads with undefined values.

    • <function>: The padding function, if used, should modify and return a new 1-d tensor. It has the following signature: padding_func(tensor, iaxis_pad_width, iaxis, kwargs)

  • stat_length (Union[tuple, list, int], optional) – Used in ‘maximum’, ‘mean’, ‘median’, and ‘minimum’. Number of values at edge of each axis used to calculate the statistic value. ((before_1, after_1), ... (before_N, after_N)) creates unique statistic lengths for each axis. ((before, after),) yields same before and after statistic lengths for each axis. (stat_length,) or int is a shortcut for before = after = statistic length for all axes. Default is None, to use the entire axis.

  • constant_values (Union[tuple, list, int], optional) – Used in constant mode. The values to set the padded values for each axis. ((before_1, after_1), ... (before_N, after_N)) creates unique pad constants for each axis. ((before, after),) yields same before and after constants for each axis. (constant,) or constant is a shortcut for before = after = constant for all axes. Default is 0.

  • end_values (Union[tuple, list, int], optional) – Used in ‘linear_ramp’. The values used for the ending value of the linear_ramp and that will form the edge of the padded arr. ((before_1, after_1), ... (before_N, after_N)) unique end values for each axis. ((before, after),) yields same before and after end values for each axis. (constant,) or constant is a shortcut for before = after = constant for all axes. Default is 0.

  • reflect_type (string, optional) – ‘reflect’, and ‘symmetric’. The ‘even’ style is the default with an unaltered reflection around the edge value. For the ‘odd’ style, the extended part of the arr is created by subtracting the reflected values from two times the edge value.

Returns

Padded tensor of rank equal to arr with shape increased according to pad_width.

Raises
  • TypeError – if arr, pad_width, stat_length, constant_values or end_values have types not specified above.

  • ValueError – if mode cannot be recognized, or if pad_width, stat_length, constant_values, end_values cannot broadcast to (arr.ndim, 2), or if keyword arguments got unexpected inputs.

  • NotImplementedError – if mode is function or ‘/median’/.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> tensor = np.array([1., 2., 3., 4., 5.])
>>> print(np.pad(tensor, (3, 4)))
[0. 0. 0. 1. 2. 3. 4. 5. 0. 0. 0. 0.]
>>> print(np.pad(tensor, (3, 4), mode="wrap"))
[3. 4. 5. 1. 2. 3. 4. 5. 1. 2. 3. 4.]
>>> print(np.pad(tensor, (3, 4), mode="linear_ramp", end_values=(10, 10)))
[10.    7.    4.    1.    2.    3.    4.    5.    6.25  7.5   8.75 10.  ]
tinyms.piecewise(x, condlist, funclist, *args, **kw)[source]

Evaluates a piecewise-defined function. Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its condition is true.

Parameters
  • x (Union[int, float, bool, list, tuple, Tensor]) – The input domain.

  • condlist (Union[bool, list of bool Tensor]) – Each boolean array corresponds to a function in funclist. Wherever condlist[i] is True, funclist[i](x) is used as the output value. Each boolean array in condlist selects a piece of x, and should therefore be of the same shape as x. The length of condlist must correspond to that of funclist. If one extra function is given, i.e. if len(funclist) == len(condlist) + 1, then that extra function is the default value, used wherever all conditions are false.

  • funclist (Union[list of callables, list of scalars]) – Each function is evaluated over x wherever its corresponding condition is True. It should take a 1d array as input and give an 1d array or a scalar value as output. If, instead of a callable, a scalar is provided then a constant function (lambda x: scalar) is assumed.

  • args (any) – Any further arguments given to piecewise are passed to the functions upon execution, i.e., if called piecewise(..., ..., 1, 'a'), then each function is called as f(x, 1, 'a').

  • kw (any) – Keyword arguments used in calling piecewise are passed to the functions upon execution, i.e., if called piecewise(..., ..., alpha=1), then each function is called as f(x, alpha=1).

Returns

Tensor, the output is the same shape and type as x and is found by calling the functions in funclist on the appropriate portions of x, as defined by the boolean arrays in condlist. Portions not covered by any condition have a default value of 0.

Supported Platforms:

Ascend GPU CPU

Raises

ValueError – if length of funclist is not in (len(condlist), len(condlist) + 1)

Examples

>>> import mindspore.numpy as np
>>> x = np.linspace(-2.5, 2.5, 6)
>>> print(np.piecewise(x, [x < 0, x >= 0], [-1, 1]))
[-1 -1 -1  1  1  1]
tinyms.polyadd(a1, a2)[source]

Finds the sum of two polynomials. Returns the polynomial resulting from the sum of two input polynomials.

Note

Numpy object poly1d is currently not supported.

Parameters
Returns

Tensor, the sum of the inputs.

Raises

ValueError – if the input array has more than 1 dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.polyadd([1, 2], [9, 5, 4]))
[9 6 6]
tinyms.polyder(p, m=1)[source]

Returns the derivative of the specified order of a polynomial.

Note

Numpy object poly1d is currently not supported.

Parameters
  • p (Union[int, float, bool, list, tuple, Tensor) – Polynomial to differentiate. A sequence is interpreted as polynomial coefficients.

  • m (int, optional) – Defaults to 1, order of differentiation.

Returns

Tensor, a new polynomial representing the derivative.

Raises

ValueError – if p has more than 1 dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.polyder([1, 1, 1, 1]))
[3 2 1]
tinyms.polyint(p, m=1, k=None)[source]

Returns an antiderivative (indefinite integral) of a polynomial.

Note

Numpy object poly1d is currently not supported.

Parameters
  • p (Union[int, float, bool, list, tuple, Tensor) – Polynomial to integrate. A sequence is interpreted as polynomial coefficients.

  • m (int, optional) – Defaults to 1, Order of the antiderivative.

  • k (Union[int, list of int]y, optinoal) – Integration constants. They are given in the order of integration: those corresponding to highest-order terms come first. If None (default), all constants are assumed to be zero. If m = 1, a single scalar can be given instead of a list.

Returns

Tensor, a new polynomial representing the antiderivative.

Raises

ValueError – if p has more than 1 dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.polyint([1, 1, 1]))
[0.33333334 0.5        1.         0.        ]
tinyms.polymul(a1, a2)[source]

Finds the product of two polynomials.

Note

Numpy object poly1d is currently not supported.

Parameters
Returns

Tensor, a new polynomial representing the derivative.

Raises

ValueError – if the input array has more than 1 dimensions.

Supported Platforms:

GPU

Examples

>>> import mindspore.numpy as np
>>> print(np.polymul([3, 1, 2], [2, 5]))
[ 6 17  9 10]
tinyms.polysub(a1, a2)[source]

Difference (subtraction) of two polynomials. Given two polynomials a1 and a2, returns a1 - a2.

Note

Numpy object poly1d is currently not supported.

Parameters
Returns

Tensor, the difference of the inputs.

Raises

ValueError – if the input array has more than 1 dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.polysub([2, 10, -2], [3, 10, -4]))
[-1  0  2]
tinyms.polyval(p, x)[source]

Evaluates a polynomial at specific values. If p is of length N, this function returns the value: p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1] If x is a sequence, then p(x) is returned for each element of x. If x is another polynomial then the composite polynomial p(x(t)) is returned.

Note

Numpy object poly1d is currently not supported.

Parameters
  • p (Union[int, float, bool, list, tuple, Tensor) – 1D array of polynomial coefficients (including coefficients equal to zero) from highest degree to the constant term.

  • x (Union[int, float, bool, list, tuple, Tensor) – A number, an array of numbers, at which to evaluate p.

Returns

Tensor.

Raises

ValueError – if p has more than 1 dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.polyval([3.,0.,1.], 5.))
76.0
tinyms.positive(a, dtype=None)[source]

Numerical positive, element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • a (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.asarray([1, -1]).astype('float32')
>>> output = np.positive(a)
>>> print(output)
[1. -1.]
tinyms.power(x1, x2, dtype=None)[source]

First array elements raised to powers from second array, element-wise.

Raises each base in x1 to the positionally-corresponding power in x2.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. On GPU, the supported dtypes are np.float16, and np.float32.

Parameters
  • x1 (Tensor) – the bases.

  • x2 (Tensor) – the exponents.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the bases in x1 raised to the exponents in x2. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.full((3, 2), [1, 2]).astype('float32')
>>> x2 = np.full((3, 2), [3, 4]).astype('float32')
>>> output = np.power(x1, x2)
>>> print(output)
[[ 1. 16.]
[ 1. 16.]
[ 1. 16.]]
tinyms.promote_types(type1, type2)[source]

Returns the data type with the smallest size and smallest scalar kind.

Note

The promotion rule is slightly different from original Numpy, but more like jax, due to the preference on 32-bit over 64-bit data types.

Parameters
  • type1 (Union[mindspore.dtype, str]) – First data type.

  • type2 (Union[mindspore.dtype, str]) – Second data type.

Returns

The promoted data type.

Raises

TypeError – if the input are not valid mindspore.dtype input.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.promote_types(np.float32, np.float64)
>>> print(output)
Float64
tinyms.ptp(x, axis=None, keepdims=False)[source]

Range of values (maximum - minimum) along an axis. The name of the function comes from the acronym for ‘peak to peak’.

Note

Numpy arguments dtype and out are not supported.

Parameters
  • x (Tensor) – Input tensor.

  • axis (Union[None, int, tuple(int)]) – Axis or axes along which the range is computed. The default is to compute the variance of the flattened array. Default: None.

  • keepdims (bool) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input tensor. If the default value is passed, then keepdims will not be passed through to the ptp method of sub-classes of tensor, however any non-default value will be. Default is False.

Returns

Tensor.

Raises

TypeError – if inputs have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([[4.0, 9.0, 2.0, 10.0], [6.0, 9.0, 7.0, 12.0]])
>>> print(np.ptp(x, axis=1))
[8. 6.]
>>> print(np.ptp(x, axis=0))
[2. 0. 5. 2.]
tinyms.rad2deg(x, dtype=None)[source]

Converts angles from radians to degrees.

Parameters
  • x (Tensor) – Angles in radians.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor, the corresponding angle in degrees. This is a tensor scalar if x is a tensor scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.asarray([1, 2, 3, -4, -5])
>>> output = np.rad2deg(x)
>>> print(output)
[  57.295776  114.59155   171.88733  -229.1831   -286.47888 ]
tinyms.radians(x, dtype=None)[source]

Converts angles from degrees to radians.

Parameters
  • x (Tensor) – Angles in degrees.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor, the corresponding radian values. This is a tensor scalar if x is a tensor scalar.

Raises

TypeError – if x is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.asarray([1, 2, 3, -4, -5])
>>> output = np.radians(x)
>>> print(output)
[ 0.01745329  0.03490658  0.05235988 -0.06981317 -0.08726647]
tinyms.ravel(x)[source]

Returns a contiguous flattened tensor.

A 1-D tensor, containing the elements of the input, is returned.

Parameters

x (Tensor) – A tensor to be flattened.

Returns

Flattened tensor, has the same data type as the original tensor x.

Raises

TypeError – If x is not tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.ones((2,3,4))
>>> output = np.ravel(x)
>>> print(output.shape)
(24,)
tinyms.ravel_multi_index(multi_index, dims, mode='clip', order='C')[source]

Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index.

Note

raise mode is not supported. Default mode is clip.

Parameters
  • multi_index (tuple of array_like) – A tuple of integer arrays, one array for each dimension.

  • dims (Union[int, tuple of integers]) – The shape of array into which the indices from multi_index apply.

  • mode ({wrap, clip}) –

    Specifies how out-of-bounds indices are handled. Default: clip.

    • wrap: wrap around

    • clip: clip to the range

    In clip mode, a negative index which would normally wrap will clip to 0 instead.

  • order ({C, F}) – Determines whether the multi-index should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order.

Returns

Raveled_indices array. An array of indices into the flattened version of an array of dimensions dims.

Raises
  • TypeError – If multi_index or dims can not be converted to tensor or dims is not a sequence of integer values.

  • ValueError – If the length of multi_index and that of dims are not equal.

Supported Platforms:

GPU

Examples

>>> import mindspore.numpy as np
>>> arr = np.array([[3, 6, 6], [4, 5, 1]])
>>> output = np.ravel_multi_index(arr, (7, 6))
>>> print(output)
[22. 41. 37.]
>>> output = np.ravel_multi_index((3, 1, 4, 1), (6, 7, 8, 9))
>>> print(output)
1621.0
tinyms.reciprocal(x, dtype=None)[source]

Returns the reciprocal of the argument, element-wise.

Calculates 1/x.

Note

Numpy arguments casting, order, subok, signature, and extobj are not supported. When where is provided, out must have a tensor value. out is not supported for storing the result, however it can be used in combination with where to set the value at indices for which where is set to False.

Parameters
  • x (Tensor) – Input array. For integer arguments with absolute value larger than 1 the result is always zero because of the way Python handles integer division. For integer zero the result is an overflow.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, this is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.arange(1, 7).reshape(2, 3).astype('float32')
>>> output = np.reciprocal(x)
>>> print(output)
[[1.         0.5        0.33333334]
[0.25       0.2        0.16666667]]
tinyms.remainder(x1, x2, dtype=None)[source]

Returns element-wise remainder of division.

Computes the remainder complementary to the floor_divide function. It is equivalent to the Python modulus operator x1 % x2 and has the same sign as the divisor x2. The MATLAB function equivalent to np.remainder is mod.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – input array.

  • x2 (Tensor) – input array.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the element-wise remainder of the quotient floor_divide(x1, x2). This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.remainder(np.array([4, 7]), np.array([2, 3]))
>>> print(output)
[0 1]
>>> output = np.remainder(np.arange(7), np.array(5))
>>> print(output)
[0 1 2 3 4 0 1]
tinyms.repeat(a, repeats, axis=None)[source]

Repeats elements of an array.

Parameters
  • a (Tensor) – Input array.

  • repeats (int or sequence of ints) – The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.

  • axis (int, optional) – The axis along which to repeat values. By default, use the flattened input array, and return a flat output array.

Returns

Tensor, output array which has the same shape as a, except along the given axis.

Raises
Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.repeat(np.array(3), 4)
>>> print(output)
[3 3 3 3]
>>> x = np.array([[1,2],[3,4]])
>>> output = np.repeat(x, 2)
>>> print(output)
[1 1 2 2 3 3 4 4]
>>> output = np.repeat(x, 3, axis=1)
>>> print(output)
[[1 1 1 2 2 2]
[3 3 3 4 4 4]]
>>> output = np.repeat(x, [1, 2], axis=0)
>>> print(output)
[[1 2]
[3 4]
[3 4]]
tinyms.reshape(x, new_shape)[source]

Reshapes a tensor without changing its data.

Parameters
  • x (Tensor) – A tensor to be reshaped.

  • new_shape (Union[int, list(int), tuple(int)]) – The new shape should be compatible with the original shape. If the tuple has only one element, the result will be a 1-D tensor of that length. One shape dimension can be \(-1\). In this case, the value is inferred from the length of the tensor and remaining dimensions.

Returns

Reshaped Tensor. Has the same data type as the original tensor x.

Raises
  • TypeError – If new_shape is not integer, list or tuple, or x is not tensor.

  • ValueError – If new_shape is not compatible with the original shape.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.asarray([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]])
>>> output = np.reshape(x, (3, 2))
>>> print(output)
[[-0.1  0.3]
 [ 3.6  0.4]
 [ 0.5 -3.2]]
>>> output = np.reshape(x, (3, -1))
>>> print(output)
[[-0.1  0.3]
 [ 3.6  0.4]
 [ 0.5 -3.2]]
>>> output = np.reshape(x, (6, ))
>>> print(output)
[-0.1  0.3  3.6  0.4  0.5 -3.2]
tinyms.result_type(*arrays_and_dtypes)[source]

Returns the type that results from applying the type promotion rules to the arguments.

Note

The promotion rule is slightly different from original Numpy, but more like jax, due to the preference on 32-bit over 64-bit data types. Complex dtypes are not supported.

Parameters

*arrays_and_dtypes (Union[int, float, bool, list, tuple, Tensor, mindspore.dtype, str]) – The operands of some operation whose result type is needed.

Returns

mindspore.dtype, the result type.

Raises

TypeError – if the input is not a valid data type.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.result_type('i2', np.float32, True))
Float32
tinyms.rint(x, dtype=None)[source]

Rounds elements of the array to the nearest integer.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. Ascend does not support dtype float64 currently.

Parameters
  • x (Union[float, list, tuple, Tensor]) – Input tensor.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Output tensor is same shape and type as x. This is a scalar if x is a scalar.

Raises

TypeError – If x can not be converted to tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([-1.7, -1.5, 0.2, 1.5, 1.7, 2.0])
>>> print(np.rint(x))
[-2. -2. 0. 2. 2. 2.]
tinyms.roll(a, shift, axis=None)[source]

Rolls a tensor along given axes.

Elements that rolls beyond the last position are re-introduced at the first.

Parameters
  • a (Tensor) – Input tensor.

  • shift (Union[int, tuple(int) – The number of places by which elements are shifted. If a tuple, then axis must be a tuple of the same size, and each of the given axes is shifted by the corresponding number. If shift is an int while axis is a tuple of integers, then the same value is used for all given axes.

  • axis (Union[int, tuple(int)], optional) – Axis or axes along which elements are shifted. By default, the array is flattened before shifting, after which the original shape is restored.

Returns

Tensor, with the same shape as a.

Supported Platforms:

Ascend GPU CPU

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If axis exceeds a.ndim, or shift and axis cannot broadcast.

Examples

>>> import mindspore.numpy as np
>>> a = np.reshape(np.arange(12), (3, 4))
>>> print(np.roll(a, [2,-3], [0,-1]))
    [[ 7  4  5  6]
     [11  8  9 10]
     [ 3  0  1  2]]
tinyms.rollaxis(x, axis, start=0)[source]

Rolls the specified axis backwards, until it lies in the given position. The positions of the other axes do not change relative to one another.

Parameters
  • x (Tensor) – A Tensor to be transposed.

  • axis (int) – The axis to be rolled.

  • start (int) –

    Default: 0. If \(start <= axis\), the axis is rolled back until it lies in this position (start). If \(start > axis\): the axis is rolled until it lies before this position (start). If \(start < 0\), the start will be normalized as a non-negative number (more details can be seen in the source code.)

Returns

Transposed Tensor. Has the same data type as the original tensor x.

Supported Platforms:

Ascend GPU CPU

Raises
  • TypeError – If axis or start is not integer, or x is not tensor.

  • ValueError – If axis is not in the range of \([-ndim, ndim-1]\) or start is not in the range of \([-ndim, ndim]\).

Examples

>>> import mindspore.numpy as np
>>> x = np.ones((2,3,4))
>>> output = np.rollaxis(x, 0, 2)
>>> print(output.shape)
(3, 2, 4)
tinyms.rot90(a, k=1, axes=(0, 1))[source]

Rotates a tensor by 90 degrees in the plane specified by axes. Rotation direction is from the first towards the second axis.

Parameters
  • a (Tensor) – Input tensor of two or more dimensions.

  • k (int) – Number of times the tensor is rotated by 90 degrees. Default: 1.

  • axes (Union[tuple(int), list(int)]) – The tensor is rotated in the plane defined by the axes. Default: (0, 1). Axes must be different and with the shape of (2,).

Returns

Tensor.

Raises
  • TypeError – if input a is not a Tensor or the argument k is not integer or the argument axes is not tuple of integers or list of ints.

  • ValueError – if any axis is out of range or the length of axes is not 2.

Supported Platforms:

GPU

Examples

>>> import mindspore.numpy as np
>>> a = np.arange(24).reshape((2, 3, 4))
>>> output = np.rot90(a)
>>> print(output)
[[[ 8  9 10 11]
  [20 21 22 23]]
 [[ 4  5  6  7]
  [16 17 18 19]]
 [[ 0  1  2  3]
  [12 13 14 15]]]
>>> output = np.rot90(a, 3, (1, 2))
>>> print(output)
[[[ 8  4  0]
  [ 9  5  1]
  [10  6  2]
  [11  7  3]]
 [[20 16 12]
  [21 17 13]
  [22 18 14]
  [23 19 15]]]
tinyms.searchsorted(a, v, side='left', sorter=None)[source]

Finds indices where elements should be inserted to maintain order. Finds the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved.

Parameters
  • a (Union[list, tuple, Tensor]) – 1-D input array. If sorter is None, then it must be sorted in ascending order, otherwise sorter must be an array of indices that sort it.

  • v (Union[int, float, bool, list, tuple, Tensor]) – Values to insert into a.

  • side ('left', 'right', optional) – If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a).

  • sorter (Union[int, float, bool, list, tuple, Tensor]) – 1-D optional array of integer indices that sort array a into ascending order. They are typically the result of argsort.

Returns

Tensor, array of insertion points with the same shape as v.

Raises

ValueError – if argument for side or sorter is invalid.

Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import numpy as np
>>> print(np.searchsorted([1,2,3,4,5], 3))
2
>>> print(np.searchsorted([1,2,3,4,5], 3, side='right'))
3
>>> print(np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3]))
[0 5 1 2]
tinyms.select(condlist, choicelist, default=0)[source]

Returns an array drawn from elements in choicelist, depending on conditions.

Parameters
  • condlist (Union[int, float, bool, list, tuple, Tensor]) – The list of conditions which determine from which array in choicelist the output elements are taken. When multiple conditions are satisfied, the first one encountered in condlist is used.

  • choicelist (Union[int, float, bool, list, tuple, Tensor]) – The list of arrays from which the output elements are taken. It has to be of the same length as condlist.

  • default (scalar, optional) – The element inserted in output when all conditions evaluate to False. Defaults to 0.

Returns

Tensor, the output at position m is the m-th element of the array in choicelist where the m-th element of the corresponding array in condlist is True.

Raises

ValueError – if len(condlist) != len(choicelist).

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> condlist = [[True, True, True, False, False], [False, False, True, False, True]]
>>> choicelist = [[0, 1, 2, 3, 4], [0, 1, 4, 9, 16]]
>>> output = np.select(condlist, choicelist)
>>> print(output)
[ 0  1  2  0 16]
tinyms.sign(x, dtype=None)[source]

Returns an element-wise indication of the sign of a number.

The sign function returns -1 if x < 0, 0 if x == 0, 1 if x > 0. nan is returned for nan inputs.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. Complex inputs are not supported now. On Ascend, integer inputs are not supported.

Parameters
  • x (Union[int, float, list, tuple, Tensor]) – Input values.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

The sign of x. This is a tensor or a scalar when x is a scalar.

Raises

TypeError – if dtype of the input is not in the given types or the input can not be converted to tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.sign(np.array([-1., 0., 1., 1.2]))
>>> print(output)
[-1.  0.  1.  1.]
tinyms.signbit(x, dtype=None)[source]

Returns element-wise True where signbit is set (less than zero).

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Union[int, float, bool, list, tuple, Tensor]) – The input value(s).

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor.

Raises

TypeError – If input is not array_like or dtype is not None or bool.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([1, -2.3, 2.1]).astype('float32')
>>> output = np.signbit(x)
>>> print(output)
[False  True False]
tinyms.sin(x, dtype=None)[source]

Trigonometric sine, element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([-5, -1, 0, 2, 4, 100]).astype('float32')
>>> output = np.sin(x)
>>> print(output)
[ 0.9589243  -0.84147096  0.   0.9092974  -0.7568025  -0.50636566]
tinyms.sinh(x, dtype=None)[source]

Hyperbolic sine, element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if x is a scalar.

Supported Platforms:

Ascend CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.arange(5).astype('float32')
>>> print(np.sinh(x))
[ 0.         1.1752012  3.6268604 10.017875  27.289917 ]
tinyms.size(a, axis=None)[source]

Returns the number of elements along a given axis.

Parameters
  • a (Union[int, float, bool, list, tuple, Tensor]) – Input data.

  • axis (int) – Axis along which the elements are counted. Default: None. If None, give the total number of elements.

Returns

Number of elements along the specified axis.

Supported Platforms:

Ascend GPU CPU

Raises
  • TypeError – If input is not array_like or axis is not int.

  • ValueError – If any axis is out of range or duplicate axes exist.

Examples

>>> import mindspore.numpy as np
>>> x = np.arange(10).reshape(2, 5).astype('float32')
>>> print(np.size(x))
10
>>> print(np.size(x, axis=1))
5
tinyms.sometrue(a, axis=None, keepdims=False)[source]

Tests whether any array element along a given axis evaluates to True.

Returns single boolean unless axis is not None

Parameters
  • a (Union[int, float, bool, list, tuple, Tensor]) – Input tensor or object that can be converted to an array.

  • axis (Union[None, int, tuple(int)]) – Axis or axes along which a logical OR reduction is performed. Default: None. If None, perform a logical OR over all the dimensions of the input array. If negative, it counts from the last to the first axis. If tuple of integers, a reduction is performed on multiple axes, instead of a single axis or all the axes as before.

  • keepdims (bool) – Default: False. If True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the any method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

Returns

Returns single boolean unless axis is not None

Raises
  • TypeError – If input is not array_like or axis is not int or tuple of integers or keepdims is not integer or initial is not scalar.

  • ValueError – If any axis is out of range or duplicate axes exist.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([1, -2.3, 2.1]).astype('float32')
>>> output = np.sometrue(x)
>>> print(output)
True
tinyms.split(x, indices_or_sections, axis=0)[source]

Splits a tensor into multiple sub-tensors along the given axis.

Parameters
  • x (Tensor) – A Tensor to be divided.

  • indices_or_sections (Union[int, tuple(int), list(int)]) – If integer, \(N\), the tensor will be divided into \(N\) equal tensors along axis. If tuple(int), list(int) or of sorted integers, the entries indicate where along axis the array is split. For example, \([2, 3]\) would, for \(axis=0\), result in three sub-tensors \(x[:2]\), \(x[2:3]\). If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.

  • axis (int) – The axis along which to split. Default: 0.

Returns

A list of sub-tensors.

Raises
  • TypeError – If argument indices_or_sections is not integer, tuple(int) or list(int) or argument axis is not integer.

  • ValueError – If argument axis is out of range of \([-x.ndim, x.ndim)\).

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> input_x = np.arange(9).astype("float32")
>>> output = np.split(input_x, 3)
>>> print(output)
(Tensor(shape=[3], dtype=Float32,
  value= [ 0.00000000e+00,  1.00000000e+00,  2.00000000e+00]),
 Tensor(shape=[3], dtype=Float32,
  value= [ 3.00000000e+00,  4.00000000e+00,  5.00000000e+00]),
 Tensor(shape=[3], dtype=Float32,
  value= [ 6.00000000e+00,  7.00000000e+00,  8.00000000e+00]))
tinyms.sqrt(x, dtype=None)[source]

Returns the non-negative square-root of an array, element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. On GPU, the supported dtypes are np.float16 and np.float32.

Parameters
  • x (Tensor) – The values whose square-roots are required.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, an array of the same shape as x, containing the positive square-root of each element in x. For negative elements, nan is returned. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.arange(6).reshape(2, 3).astype('float32')
>>> x_squared = np.square(x)
>>> output = np.sqrt(x_squared)
>>> print(output)
[[ 0. 1. 2.]
[ 3. 4. 5.]]
tinyms.square(x, dtype=None)[source]

Returns the element-wise square of the input.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. On GPU, the supported dtypes are np.float16 and np.float32.

Parameters
  • x (Tensor) – Input data.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, element-wise x*x, of the same shape and dtype as x. This is a scalar if x is a scalar..

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.square(np.arange(6).reshape(2, 3).astype('float32'))
>>> print(x)
[[ 0.  1.  4.]
[ 9. 16. 25.]]
tinyms.squeeze(a, axis=None)[source]

Removes single-dimensional entries from the shape of a tensor.

Parameters
Returns

Tensor, with all or a subset of the dimensions of length \(1\) removed.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If specified axis has shape entry \(> 1\).

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.ones((1,2,2,1))
>>> x = np.squeeze(x)
>>> print(x.shape)
(2, 2)
tinyms.stack(arrays, axis=0)[source]

Joins a sequence of arrays along a new axis.

The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.

Note

Numpy argument out is not supported.

Parameters
  • arrays (sequence of Tensor) – Each array must have the same shape.

  • axis (int, optional) – The axis in the result array along which the input arrays are stacked. Default: 0.

Returns

Tensor, The stacked array has one more dimension than the input arrays.

Raises

ValueError – if input is not Tensor, tuple, or list.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> arrays = [np.ones((3, 4)) for _ in range(10)]
>>> output = np.stack(arrays, axis=0)
>>> print(output.shape)
(10, 3, 4)
>>> output = np.stack(arrays, axis=1)
>>> print(output.shape)
(3, 10, 4)
>>> output = np.stack(arrays, axis=2)
>>> print(output.shape)
(3, 4, 10)
tinyms.std(x, axis=None, ddof=0, keepdims=False)[source]

Computes the standard deviation along the specified axis. The standard deviation is the square root of the average of the squared deviations from the mean, i.e., \(std = sqrt(mean(abs(x - x.mean())**2))\).

Returns the standard deviation, which is computed for the flattened array by default, otherwise over the specified axis.

Note

Numpy arguments dtype, out and where are not supported.

Parameters
  • x (Tensor) – A Tensor to be calculated.

  • axis (Union[None, int, tuple(int)]) –

    Axis or axes along which the standard deviation is computed. Default: None.

    If None, compute the standard deviation of the flattened array.

  • ddof (int) – Means Delta Degrees of Freedom. The divisor used in calculations is \(N - ddof\), where \(N\) represents the number of elements. Default: 0.

  • keepdims – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input tensor. If the default value is passed, then keepdims will not be passed through to the std method of sub-classes of tensor, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised. Default: False.

Returns

Standard deviation tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> input_x = np.array([1., 2., 3., 4.])
>>> output = np.std(input_x)
>>> print(output)
1.118034
tinyms.subtract(x1, x2, dtype=None)[source]

Subtracts arguments, element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – the input to be subtracted from.

  • x2 (Tensor) – the input to be subtracted by.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the difference of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.full((3, 2), [1, 2])
>>> x2 = np.full((3, 2), [3, 4])
>>> output = np.subtract(x1, x2)
>>> print(output)
[[-2 -2]
[-2 -2]
[-2 -2]]
tinyms.sum(a, axis=None, dtype=None, keepdims=False, initial=None)

Returns sum of array elements over a given axis.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Union[int, float, bool, list, tuple, Tensor]) – Elements to sum.

  • axis (Union[None, int, tuple(int)]) – Axis or axes along which a sum is performed. Default: None. If None, sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. If axis is a tuple of integers, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

  • keepdims (bool) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised. Default: False.

  • initial (scalar) – Starting value for the sum, if None, which refers to the first element of the reduction. Default: None.

Returns

Tensor. An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

Raises
  • TypeError – If input is not array_like or axis is not int or tuple of integers or keepdims is not integer or initial is not scalar.

  • ValueError – If any axis is out of range or duplicate axes exist.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.sum([0.5, 1.5]))
2.0
>>> x = np.arange(10).reshape(2, 5).astype('float32')
>>> print(np.sum(x, axis=1))
[10. 35.]
tinyms.swapaxes(x, axis1, axis2)[source]

Interchanges two axes of a tensor.

Parameters
  • x (Tensor) – A tensor to be transposed.

  • axis1 (int) – First axis.

  • axis2 (int) – Second axis.

Returns

Transposed tensor, has the same data type as the original tensor x.

Raises
  • TypeError – If axis1 or axis2 is not integer, or x is not tensor.

  • ValueError – If axis1 or axis2 is not in the range of \([-ndim, ndim-1]\).

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.ones((2,3,4))
>>> output = np.swapaxes(x, 0, 2)
>>> print(output.shape)
(4,3,2)
tinyms.take(a, indices, axis=None, mode='clip')[source]

Takes elements from an array along an axis.

When axis is not None, this function does the same thing as “fancy” indexing (indexing arrays using arrays); however, it can be easier to use if you need elements along a given axis. A call such as np.take(arr, indices, axis=3) is equivalent to arr[:,:,:,indices,...].

Note

Numpy argument out is not supported. mode = 'raise' is not supported, and the default mode is ‘clip’ instead.

Parameters
  • a (Tensor) – Source array with shape (Ni…, M, Nk…).

  • indices (Tensor) – The indices with shape (Nj…) of the values to extract.

  • axis (int, optional) – The axis over which to select values. By default, the flattened input array is used.

  • mode (‘raise’, ‘wrap’, ‘clip’, optional) –

    Specifies how out-of-bounds indices will behave.

    ‘raise’ – raise an error;

    ‘wrap’ – wrap around;

    ‘clip’ – clip to the range. ‘clip’ mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers.

Returns

Tensor, the indexed result.

Raises
Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.array([4, 3, 5, 7, 6, 8])
>>> indices = np.array([0, 1, 4])
>>> output = np.take(a, indices)
>>> print(output)
[4 3 6]
>>> indices = np.array([[0, 1], [2, 3]])
>>> output = np.take(a, indices)
>>> print(output)
[[4 3]
[5 7]]
tinyms.take_along_axis(arr, indices, axis)[source]

Takes values from the input array by matching 1d index and data slices.

This iterates over matching 1d slices oriented along the specified axis in the index and data arrays, and uses the former to look up values in the latter. These slices can be different lengths.

Parameters
  • arr (Tensor) – Source array with shape (Ni…, M, Nk…).

  • indices (Tensor) – Indices with shape (Ni…, J, Nk…) to take along each 1d slice of arr. This must match the dimension of arr, but dimensions Ni and Nj only need to broadcast against arr.

  • axis (int) – The axis to take 1d slices along. If axis is None, the input array is treated as if it had first been flattened to 1d.

Returns

Tensor, the indexed result, with shape (Ni…, J, Nk…).

Raises
  • ValueError – if input array and indices have different number of dimensions.

  • TypeError – if the input is not a Tensor.

Supported Platforms:

Ascend GPU CPU

Example

>>> import mindspore.numpy as np
>>> x = np.arange(12).reshape(3, 4)
>>> indices = np.arange(3).reshape(1, 3)
>>> output = np.take_along_axis(x, indices, 1)
>>> print(output)
[[ 0  1  2]
[ 4  5  6]
[ 8  9 10]]
tinyms.tan(x, dtype=None)[source]

Computes tangent element-wise.

Equivalent to \(np.sin(x)/np.cos(x)\) element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if x is a scalar.

Raises

TypeError – If the input is not a tensor or is tensor.dtype is mindspore.float64.

Supported Platforms:

Ascend CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.array([-5, -1, 0, 2, 4, 100]).astype('float32')
>>> print(np.tan(x))
[ 3.380515   -1.5574077   0.         -2.1850398   1.1578213  -0.58721393]
tinyms.tanh(x, dtype=None)[source]

Computes hyperbolic tangent element-wise.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – Input tensor.

  • dtype (mindspore.dtype, optional) – Default: None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.arange(5).astype('float32')
>>> print(np.tanh(x))
[0.        0.7615942 0.9640276 0.9950548 0.9993293]
tinyms.tensordot(a, b, axes=2)[source]

Computes tensor dot product along specified axes.

Given two tensors, a and b, and an array_like object containing two array_like objects, (a_axes, b_axes), sum the products of a’s and b’s elements (components) over the axes specified by a_axes and b_axes. The third argument can be a single non-negative integer_like scalar, N; if it is such, then the last N dimensions of a and the first N dimensions of b are summed over. Three common use cases are:

  • axes = 0 : tensor product

  • axes = 1 : tensor dot product

  • axes = 2 : (default) tensor double contraction

When axes is integer_like, the sequence for evaluation will be: first the -Nth axis in a and 0th axis in b, and the -1th axis in a and Nth axis in b last. When there is more than one axis to sum over - and they are not the last (first) axes of a (b) - the argument axes should consist of two sequences of the same length, with the first axis to sum over given first in both sequences, the second axis second, and so forth. The shape of the result consists of the non-contracted axes of the first tensor, followed by the non-contracted axes of the second.

Note

On CPU, the supported dypes are np.float16 and np.float32. On GPU, the supported dypes are np.float16 and np.float32.

Parameters
  • a (Tensor) – Tensor to “dot”.

  • b (Tensor) – Tensor to “dot”.

  • axes (int or sequence of ints) –

    integer_like: If an int N, sum over the last N axes of a and the first N axes of b in order. The sizes of the corresponding axes must match.

    sequence of ints: Or, a list of axes to be summed over, first sequence applying to a, second to b. Both elements array_like must be of the same length.

Returns

Tensor, or list of tensors, the tensor dot product of the input.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.ones((3, 4, 5))
>>> b = np.ones((4, 3, 2))
>>> output = np.tensordot(a, b, axes=([1,0],[0,1]))
>>> print(output.shape)
(5, 2)
tinyms.tile(a, reps)[source]

Constructs an array by repeating a the number of times given by reps.

If reps has length d, the result will have dimension of max(d, a.ndim). If a.ndim < d, a is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote a to d-dimensions manually before calling this function. If a.ndim > d, reps is promoted to a.ndim by pre-pending 1’s to it. Thus for an a of shape (2, 3, 4, 5), a reps of (2, 2) is treated as (1, 1, 2, 2).

Parameters
  • a (Tensor) – The input array.

  • reps (int or sequence of ints) – The number of repetitions of a along each axis.

Returns

Tensor, the tiled output array.

Raises

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.array([0, 1, 2])
>>> output = np.tile(a, 2)
>>> print(output)
[0 1 2 0 1 2]
>>> output = np.tile(a, (2, 2))
>>> print(output)
[[0 1 2 0 1 2]
[0 1 2 0 1 2]]
>>> output = np.tile(a, (2, 1, 2))
>>> print(output)
[[[0 1 2 0 1 2]]
[[0 1 2 0 1 2]]]
tinyms.trace(a, offset=0, axis1=0, axis2=1, dtype=None)[source]

Returns the sum along diagonals of the array.

If a is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements a[i,i+offset] for all i. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-arrays whose traces are returned. The shape of the resulting array is the same as that of a with axis1 and axis2 removed.

Note

On GPU, the supported dtypes are np.float16, and np.float32. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.

Parameters
  • a (Tensor) – Array from which the diagonals are taken.

  • offset (int, optional) – Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal.

  • axis1 (int, optional) – Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0).

  • axis2 (int, optional) – Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor, sum_along_diagonals. If a is 2-D, the sum along the diagonal is returned. If a has larger dimensions, then an array of sums along diagonals is returned.

Raises

ValueError – if the input tensor has less than two dimensions.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.trace(np.eye(3))
>>> print(output)
3.0
>>> a = np.arange(8).reshape((2,2,2))
>>> output = np.trace(a)
>>> print(output)
[6 8]
>>> a = np.arange(24).reshape((2,2,2,3))
>>> output = np.trace(a).shape
>>> print(output)
(2, 3)
tinyms.transpose(a, axes=None)[source]

Reverses or permutes the axes of a tensor; returns the modified tensor.

Parameters
  • a (Tensor) – a tensor to be transposed

  • axes (Union[None, tuple, list]) – the axes order, if axes is None, transpose the entire tensor. Default is None.

Returns

Tensor, the transposed tensor array.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If the number of axes is not euqal to a.ndim.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.ones((1,2,3))
>>> x = np.transpose(x)
>>> print(x.shape)
(3, 2, 1)
tinyms.trapz(y, x=None, dx=1.0, axis=-1)[source]

Integrates along the given axis using the composite trapezoidal rule.

Integrates y (x) along given axis.

Parameters
  • y (Tensor) – Input array to integrate.

  • x (Union[int, float, bool, list, tuple, Tensor], optional) – The sample points corresponding to the y values. If x is None, the sample points are assumed to be evenly spaced dx apart. The default is None.

  • dx (scalar, optional) – The spacing between sample points when x is None. The default is 1.0.

  • axis (int, optional) – The axis along which to integrate. Defaults to -1.

Returns

Tensor of float, definite integral as approximated by trapezoidal rule.

Raises

ValueError – If axis is out of range of [-y.ndim, y.ndim).

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.arange(6).reshape(2, 3)
>>> output = np.trapz(a,  x=[-2, 1, 2], axis=1)
>>> print(output)
[ 3. 15.]
>>> output = np.trapz(a,  dx=3, axis=0)
>>> print(output)
[ 4.5  7.5 10.5]
tinyms.tri(N, M=None, k=0, dtype=mindspore.float32)[source]

Returns a tensor with ones at and below the given diagonal and zeros elsewhere.

Parameters
  • N (int) – Number of rows in the array.

  • M (int, optional) – Number of columns in the array. By default, M is taken equal to N.

  • k (int, optional) – The sub-diagonal at and below which the array is filled. \(k = 0\) is the main diagonal, while \(k < 0\) is below it, and \(k > 0\) is above. The default is 0.

  • dtype (mindspore.dtype, optional) – Data type of the returned array. The default is mstype.float32.

Returns

Tensor with shape (N, M), with its lower triangle filled with ones and zeros elsewhere; in other words \(T[i,j] = 1\) for \(j <= i + k\), 0 otherwise.

Raises

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.tri(3, 3, 1)
>>> print(output)
[[1. 1. 0.]
[1. 1. 1.]
[1. 1. 1.]]
tinyms.tril(m, k=0)[source]

Returns a lower triangle of a tensor.

Returns a copy of a tensor with elements above the k-th diagonal zeroed.

Parameters
  • m (Union[Tensor, list, tuple]) – The shape and data-type of m define these same attributes of the returned tensor.

  • k (int, optional) – Diagonal above which to zero elements. \(k = 0\) (the default) is the main diagonal, \(k < 0\) is below it and \(k > 0\) is above.

Returns

Lower triangle of m, of same shape and data-type as m.

Supported Platforms:

Ascend GPU CPU

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If input m’s rank \(< 1\).

Examples

>>> import mindspore.numpy as np
>>> output = np.tril(np.ones((3, 3)))
>>> print(output)
[[1. 0. 0.]
[1. 1. 0.]
[1. 1. 1.]]
tinyms.tril_indices(n, k=0, m=None)[source]

Returns the indices for the lower-triangle of an (n, m) array.

Parameters
  • n (int) – The size of the arrays for which the returned indices will be valid.

  • k (int, optional) – Diagonal offset, default is 0.

  • m (int, optional) – The column dimension of the arrays for which the returned arrays will be valid. By default m is taken equal to n.

Returns

The indices for the triangle. The returned tuple contains two tensors, each with the indices along one dimension of the tensor.

Raises

TypeError – if n, k, m are not numbers.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.tril_indices(3))
(Tensor(shape=[6], dtype=Int32, value= [0, 1, 1, 2, 2, 2]),
Tensor(shape=[6], dtype=Int32, value= [0, 0, 1, 0, 1, 2]))
tinyms.tril_indices_from(arr, k=0)[source]

Returns the indices for the lower-triangle of arr.

Parameters
  • arr (Union[Tensor, list, tuple]) – 2-dimensional array.

  • k (int, optional) – Diagonal offset, default is 0.

Returns

triu_indices_from, tuple of 2 tensor, shape(N) Indices for the upper-triangle of arr.

Raises
  • TypeError – if arr cannot be converted to tensor, or k is not a number.

  • ValueError – if arr cannot be converted to a 2-dimensional tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> tensor = np.ones((3,3))
>>> print(np.tril_indices_from(tensor))
(Tensor(shape=[6], dtype=Int32, value= [0, 1, 1, 2, 2, 2]),
 Tensor(shape=[6], dtype=Int32, value= [0, 0, 1, 0, 1, 2]))
tinyms.triu(m, k=0)[source]

Returns an upper triangle of a tensor.

Returns a copy of a tensor with elements below the k-th diagonal zeroed.

Parameters
  • m (Union[Tensor, list, tuple]) – The shape and data-type of m define these same attributes of the returned tensor.

  • k (int, optional) – Diagonal below which to zero elements. \(k = 0\) (the default) is the main diagonal, \(k < 0\) is below it and \(k > 0\) is above.

Returns

Upper triangle of m, of same shape and data-type as m.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If input m’s rank < 1.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.triu(np.ones((3, 3)))
>>> print(output)
[[1. 1. 1.]
[0. 1. 1.]
[0. 0. 1.]]
tinyms.triu_indices(n, k=0, m=None)[source]

Returns the indices for the upper-triangle of an (n, m) array.

Parameters
  • n (int) – The size of the arrays for which the returned indices will be valid.

  • k (int, optional) – Diagonal offset, default is 0.

  • m (int, optional) – The column dimension of the arrays for which the returned arrays will be valid. By default m is taken equal to n.

Returns

The indices for the triangle. The returned tuple contains two tensors, each with the indices along one dimension of the tensor.

Raises

TypeError – if n, k, m are not numbers.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.triu_indices(3))
(Tensor(shape=[6], dtype=Int32, value= [0, 0, 0, 1, 1, 2]),
 Tensor(shape=[6], dtype=Int32, value= [0, 1, 2, 1, 2, 2]))
tinyms.triu_indices_from(arr, k=0)[source]

Returns the indices for the upper-triangle of arr.

Parameters
  • arr (Union[Tensor, list, tuple]) – 2-dimensional array.

  • k (int, optional) – Diagonal offset, default is 0.

Returns

triu_indices_from, tuple of 2 tensor, shape(N) Indices for the upper-triangle of arr.

Raises
  • TypeError – if arr cannot be converted to tensor, or k is not a number.

  • ValueError – if arr cannot be converted to a 2-dimensional tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> tensor = np.ones((3,3))
>>> print(np.triu_indices_from(tensor))
(Tensor(shape=[6], dtype=Int32, value= [0, 0, 0, 1, 1, 2]),
Tensor(shape=[6], dtype=Int32, value= [0, 1, 2, 1, 2, 2]))
tinyms.true_divide(x1, x2, dtype=None)[source]

Returns a true division of the inputs, element-wise.

Instead of the Python traditional ‘floor division’, this returns a true division.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x1 (Tensor) – the divident.

  • x2 (Tensor) – the divisor.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, this is a scalar if both x1 and x2 are scalars.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x1 = np.full((3, 2), [1, 2])
>>> x2 = np.full((3, 2), [3, 4])
>>> output = np.true_divide(x1, x2)
>>> print(output)
[[0.33333334 0.5       ]
[0.33333334 0.5       ]
[0.33333334 0.5       ]]
tinyms.trunc(x, dtype=None)[source]

Returns the truncated value of the input, element-wise.

The truncated value of the scalar x is the nearest integer i which is closer to zero than x is. In short, the fractional part of the signed number x is discarded.

Note

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported.

Parameters
  • x (Tensor) – input data.

  • dtype (mindspore.dtype, optional) – defaults to None. Overrides the dtype of the output Tensor.

Returns

Tensor or scalar, the truncated value of each element in x. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> output = np.trunc(np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]))
>>> print(output)
[-1. -1. -0.  0.  1.  1.  2.]
tinyms.unique(x, return_inverse=False)[source]

Finds the unique elements of a tensor. The input tensor will be flattened first when it has more than one dimension.

Note

Numpy arguments axis, return_index and return_counts are not supported. On CPU, this operator must be executed in graph mode.

Parameters
  • x (Tensor) – The input tensor to be processed.

  • return_inverse (bool) – If True, also return the indices of the unique tensor. Default: False.

Returns

Tensor or tuple of Tensors. - If return_inverse is False, just return the unique tensor. - If return_inverse is True, return tuple of tensors.

Supported Platforms:

Ascend GPU CPU

Raises

TypeError – If x is not tensor.

Examples

>>> import mindspore.numpy as np
>>> from mindspore import context
>>> context.set_context(mode=context.GRAPH_MODE)
>>> input_x = np.asarray([1, 2, 2, 2, 3, 4, 5]).astype('int32')
>>> output_x = np.unique(input_x)
>>> print(output_x)
[1 2 3 4 5]
>>> output_x = np.unique(input_x, return_inverse=True)
>>> print(output_x)
(Tensor(shape=[5], dtype=Int32, value= [ 1, 2, 3, 4, 5]), Tensor(shape=[7], dtype=Int32,
    value= [0, 1, 1, 1, 2, 3, 4]))
tinyms.unravel_index(indices, shape, order='C')[source]

Converts a flat index or array of flat indices into a tuple of coordinate arrays.

Note

Out-of-bound indices are clipped by the boundaries of shape instead of raising an error.

Parameters
  • indices (Union[int, float, bool, list, tuple, Tensor]) – An integer array whose elements are indices into the flattened version of an array of dimensions shape.

  • shape (tuple of integers) – The shape of the array to use for unraveling indices.

  • order (Union['C', 'F'], optional) – Determines whether the indices should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order.

Returns

Tensor, each array in the tuple has the same shape as the indices array.

Supported Platforms:

Ascend GPU CPU

Raises

ValueError – if order is not ‘C’ or ‘F’.

Examples

>>> import mindspore.numpy as np
>>> print(np.unravel_index([22, 41, 37], (7,6)))
(Tensor(shape=[3], dtype=Int32, value= [3, 6, 6]),
Tensor(shape=[3], dtype=Int32, value= [4, 5, 1]))
>>> print(np.unravel_index([31, 41, 13], (7,6), order='F'))
(Tensor(shape=[3], dtype=Int32, value= [3, 6, 6]),
Tensor(shape=[3], dtype=Int32, value= [4, 5, 1]))
tinyms.unwrap(p, discont=3.141592653589793, axis=-1)[source]

Unwraps by changing deltas between values to 2*pi complement. Unwraps radian phase p by changing absolute jumps greater than discont to their 2*pi complement along the given axis.

Note

For absolute jumps that are within a very close range to pi, unwrapping may be done differently than numpy due to differences in round-off.

Parameters
  • p (Union[int, float, bool, list, tuple, Tensor) – Input array.

  • discont (float, optional) – Maximum discontinuity between values, default is pi.

  • axis (int, optional) – Axis along which unwrap will operate, default is -1.

Returns

Tensor.

Raises

ValueError – if the axis is out of range.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> phase = np.add(np.linspace(0, np.pi, num=5), [0, 0, 0, np.pi, np.pi])
>>> print(phase)
[0.        0.7853982 1.5707964 5.4977875 6.2831855]
>>> print(np.unwrap(phase))
[ 0.0000000e+00  7.8539819e-01  1.5707964e+00 -7.8539848e-01 -4.7683716e-07]
tinyms.vander(x, N=None, increasing=False)[source]

Generates a Vandermonde matrix.

The columns of the output matrix are powers of the input vector. The order of the powers is determined by the increasing boolean argument. Specifically, when increasing is False, the i-th output column is the input vector raised element-wise to the power of \(N - i - 1\). Such a matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde.

Parameters
  • x (Union[list, tuple, Tensor]) – 1-D input array.

  • N (int, optional) – Number of columns in the output. If N is not specified, a square array is returned (N = len(x)).

  • increasing (bool, optional) – Order of the powers of the columns. If True, the powers increase from left to right, if False (the default) they are reversed.

Returns

Vandermonde matrix. If increasing is False, the first column is \(x^{(N-1)}\), the second \(x^{(N-2)}\) and so forth. If increasing is True, the columns are \(x^0, x^1, ..., x^{(N-1)}\).

Raises
  • TypeError – If inputs have types not specified above.

  • ValueError – If x is not 1-D, or N < 0.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.vander([1., 2., 3., 4., 5.]))
[[  1.   1.   1.   1.   1.]
 [ 16.   8.   4.   2.   1.]
 [ 81.  27.   9.   3.   1.]
 [256.  64.  16.   4.   1.]
 [625. 125.  25.   5.   1.]]
tinyms.var(x, axis=None, ddof=0, keepdims=False)[source]

Computes the variance along the specified axis. The variance is the average of the squared deviations from the mean, i.e., \(var = mean(abs(x - x.mean())**2)\).

Returns the variance, which is computed for the flattened array by default, otherwise over the specified axis.

Note

Numpy arguments dtype, out and where are not supported.

Parameters
  • x (Tensor) – A Tensor to be calculated.

  • axis (Union[None, int, tuple(int)]) – Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array. Default: None.

  • ddof (int) – Means Delta Degrees of Freedom. Default: 0. The divisor used in calculations is \(N - ddof\), where \(N\) represents the number of elements.

  • keepdims (bool) – If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input tensor. If the default value is passed, then keepdims will not be passed through to the var method of sub-classes of tensor, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised. Default: False.

Supported Platforms:

Ascend GPU CPU

Returns

Standard deviation tensor.

Examples

>>> import mindspore.numpy as np
>>> input_x = np.array([1., 2., 3., 4.])
>>> output = np.var(input_x)
>>> print(output)
1.25
tinyms.vsplit(x, indices_or_sections)[source]

Splits a tensor into multiple sub-tensors vertically (row-wise). It is equivalent to split with \(axis=0\) (default), the array is always split along the first axis regardless of the array dimension.

Parameters
  • x (Tensor) – A Tensor to be divided.

  • indices_or_sections (Union[int, tuple(int), list(int)]) – If integer, \(N\), the tensor will be divided into \(N\) equal tensors along axis. If tuple(int), list(int) or of sorted integers, the entries indicate where along axis the array is split. For example, \([2, 3]\) would, for \(axis=0\), result in three sub-tensors \(x[:2]\), \(x[2:3]\). If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.

Returns

A list of sub-tensors.

Raises

TypeError – If argument indices_or_sections is not integer.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> input_x = np.arange(9).reshape((3, 3)).astype('float32')
>>> output = np.vsplit(input_x, 3)
>>> print(output)
(Tensor(shape=[1, 3], dtype=Float32,
  value=[[ 0.00000000e+00,  1.00000000e+00,  2.00000000e+00]]),
 Tensor(shape=[1, 3], dtype=Float32,
  value=[[ 3.00000000e+00,  4.00000000e+00,  5.00000000e+00]]),
 Tensor(shape=[1, 3], dtype=Float32,
  value=[[ 6.00000000e+00,  7.00000000e+00,  8.00000000e+00]]))
tinyms.vstack(tup)[source]

Stacks tensors in sequence vertically. This is equivalent to concatenation along the first axis. 1-D tensors should firstly be reshaped to (1, N), and then be concatenated along the first axis.

Parameters

tup (Union[Tensor, tuple, list]) – A sequence of 1-D or 2-D tensors. The tensors must have the same shape along all but the first axis. 1-D tensors must have the same shape.

Returns

Stacked Tensor, formed by stacking the given tensors.

Supported Platforms:

Ascend GPU CPU

Raises

Examples

>>> import mindspore.numpy as np
>>> x1 = np.array([1, 2, 3]).astype('int32')
>>> x2 = np.array([4, 5, 6]).astype('int32')
>>> output = np.vstack((x1, x2))
>>> print(output)
[[1 2 3]
 [4 5 6]]
tinyms.where(condition, x=None, y=None)[source]

Returns elements chosen from x or y depending on condition.

Note

As nonzero is not supported, both x and y must be provided Tensor

input.

Parameters
  • condition (Tensor) – where True, yield x, otherwise yield y.

  • x (Tensor) – Values from which to choose. Defaults to None.

  • y (Tensor) – Values from which to choose. x, y and condition need to be broadcastable to some shape. Defaults to None.

Returns

Tensor or scalar, with elements from x where condition is True, and elements from y elsewhere.

Raises

ValueError – if operands cannot be broadcast.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> condition = np.full((1, 1, 2), [False, True])
>>> x = np.full((1, 3, 2), 5)
>>> y = np.full((2, 1, 1), 7)
>>> output = np.where(condition, x, y)
>>> print(output)
[[[7 5]
[7 5]
[7 5]]
[[7 5]
[7 5]
[7 5]]]
tinyms.zeros(shape, dtype=mindspore.float32)[source]

Returns a new tensor of given shape and type, filled with zeros.

Parameters
  • shape (Union[int, tuple, list]) – the shape of the new tensor.

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype. Default is mstype.float32.

Returns

Tensor, with the designated shape and dtype, filled with zeros.

Raises
  • TypeError – If input arguments have types not specified above.

  • ValueError – If shape entries have values \(< 0\).

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> print(np.zeros((2,2)))
[[0. 0.]
[0. 0.]]
tinyms.zeros_like(a, dtype=None, shape=None)[source]

Returns an array of zeros with the same shape and type as a given array.

Note

Input array must have the same size across a dimension. If a is not a Tensor, dtype is float32 by default if not provided.

Parameters
  • a (Union[Tensor, list, tuple]) – The shape and data-type of a define these same attributes of the returned array.

  • dtype (mindspore.dtype, optional) – Overrides the data type of the result.

  • shape (int or sequence of ints, optional) – Overrides the shape of the result.

Returns

Tensor, array of zeros with the same shape and type as a.

Raises

ValueError – if a is not a Tensor, list or tuple.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> a = np.ones((4,1,2))
>>> output = np.zeros_like(a)
>>> print(output)
[[[0. 0.]]
[[0. 0.]]
[[0. 0.]]
[[0. 0.]]]