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.]]
class tinyms.QuantDtype[source]

An enum for quant datatype, contains INT1 ~ INT16, UINT1 ~ UINT16.

QuantDtype is defined in mindspore/common/dtype.py, use command below to import:

from mindspore import QuantDtype
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.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.

Raises:

NotImplementedError – If the python type cannot be converted to 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, internal=False, const_arg=False)[source]

Tensor is a data structure that stores an n-dimensional array.

Parameters:
  • input_data (Union[Tensor, float, int, bool, tuple, list, numpy.ndarray]) – The data to be stored. It can be another Tensor, Python number or NumPy ndarray. Default: None.

  • dtype (mindspore.dtype) – Used to indicate the data type of the output Tensor. The argument should be defined in mindspore.dtype. 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]) – Used to indicate the shape of the output Tensor. The argument should be a list of integers, a tuple of integers or an integer. If input_data is available, shape doesn’t need to be set. If None in shape, a tensor of dynamic shape is created, input_data doesn’t need to be set; if None not in shape, a tensor of static shape is created, input_data or init must 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 Tensor in the other conditions. If ‘init’ interface is used to initialize Tensor, the Tensor.init_data API needs to be called to convert Tensor to the actual data. Default: None.

  • internal (bool) – Whether it is created by the framework. ‘True’ means that the tensor is created by framework. ‘False’ means that the tensor is created by user. Default: False

  • const_arg (bool) – Whether the tensor is a constant when it is used for the argument of a network. Default: False.

Outputs:

Tensor.

Note

The default value None of input_data works as a placeholder, it does not mean that we can create a NoneType Tensor.

Examples

>>> import numpy as np
>>> import mindspore as ms
>>> from mindspore import Tensor
>>> from mindspore.common.initializer import One
>>> # initialize a tensor with numpy.ndarray
>>> t1 = Tensor(np.zeros([1, 2, 3]), ms.float32)
>>> print(t1)
[[[0. 0. 0.]
[0. 0. 0.]]]
>>> print(type(t1))
<class 'mindspore.common.tensor.Tensor'>
>>> print(t1.shape)
(1, 2, 3)
>>> print(t1.dtype)
Float32
>>>
>>> # initialize a tensor with a float scalar
>>> t2 = Tensor(0.1)
>>> print(t2)
0.1
>>> print(type(t2))
<class 'mindspore.common.tensor.Tensor'>
>>> print(t2.shape)
()
>>> print(t2.dtype)
Float32
>>>
>>> # initialize a tensor with a tuple
>>> t3 = Tensor((1, 2))
>>> print(t3)
[1 2]
>>> print(type(t3))
<class 'mindspore.common.tensor.Tensor'>
>>> print(t3.shape)
(2,)
>>> print(t3.dtype)
Int64
...
>>> # initialize a tensor with init
>>> t4 = Tensor(shape = (1, 3), dtype=ms.float32, init=One())
>>> print(t4)
[[1. 1. 1.]]
>>> print(type(t4))
<class 'mindspore.common.tensor.Tensor'>
>>> print(t4.shape)
(1, 3)
>>> print(t4.dtype)
Float32
property H

Returns a view of a matrix (2-D tensor) conjugated and transposed. x.H is equivalent to mindspore.Tensor.swapaxes(0, 1).conj() for complex matrices and mindspore.Tensor.swapaxes(0, 1) for real matrices.

property T

Return the transposed tensor.

abs()[source]

For details, please refer to mindspore.ops.abs().

absolute()[source]

Alias for mindspore.Tensor.abs().

acos()[source]

For details, please refer to mindspore.ops.acos().

acosh()[source]

For details, please refer to mindspore.ops.acosh().

add(other)[source]

For details, please refer to mindspore.ops.add().

addbmm(batch1, batch2, *, beta=1, alpha=1)[source]

For details, please refer to mindspore.ops.addbmm().

addcdiv(tensor1, tensor2, value=1)[source]

For details, please refer to mindspore.ops.addcdiv().

addcmul(tensor1, tensor2, value=1)[source]

For details, please refer to mindspore.ops.addcmul().

addmm(mat1, mat2, *, beta=1, alpha=1)[source]

For details, please refer to mindspore.ops.addmm().

addmv(mat, vec, beta=1, alpha=1)[source]

For details, please refer to mindspore.ops.addmv().

addr(vec1, vec2, beta=1, alpha=1)[source]

For details, please refer to mindspore.ops.addr().

adjoint()[source]

For details, please refer to mindspore.ops.adjoint().

all(axis=None, keep_dims=False)[source]

For details, please refer to mindspore.ops.all().

amax(axis=None, keepdims=False, *, initial=None, where=None)[source]

For details, please refer to mindspore.ops.amax().

amin(axis=None, keepdims=False, *, initial=None, where=None)[source]

For details, please refer to mindspore.ops.amin().

angle()[source]

For details, please refer to mindspore.ops.angle().

any(axis=None, keep_dims=False)[source]

For details, please refer to mindspore.ops.any().

approximate_equal(other, tolerance=1e-05)[source]

For details, please refer to mindspore.ops.approximate_equal().

arccos()[source]

Alias for mindspore.Tensor.acos().

arccosh()[source]

For details, please refer to mindspore.ops.arccosh().

arcsin()[source]

For details, please refer to mindspore.ops.arcsin().

arcsinh()[source]

Alias for mindspore.Tensor.asinh().

arctan()[source]

For details, please refer to mindspore.ops.arctan().

arctan2(other)[source]

For details, please refer to mindspore.ops.arctan2().

arctanh()[source]

Alias for mindspore.Tensor.atanh().

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

For details, please refer to mindspore.ops.argmax().

argmax_with_value(axis=0, keep_dims=False)[source]

Returns the maximum value with corresponding index.

Compute the max value of input Tensor on the specified axis, and return the max value and index.

Note

In auto_parallel and semi_auto_parallel mode, the first output index can not be used.

Warning

  • If there are multiple maximum values, the index of the first maximum value is used.

  • The value range of axis is [-dims, dims - 1]. dims is the dimension length of this tensor.

Parameters:
  • axis (int) – The dimension to reduce. Default: 0.

  • keep_dims (bool) – Whether to reduce dimension, if true the output will keep the same dimension as the input, the output will reduce dimension if false. Default: False.

Returns:

tuple (Tensor), tuple of 2 tensors, containing the corresponding index and the maximum value of the input tensor.

  • index (Tensor) - The index for the maximum value of the input tensor. If keep_dims is true, the shape of output tensors is \((x_1, x_2, ..., x_{axis-1}, 1, x_{axis+1}, ..., x_N)\). Otherwise, the shape is \((x_1, x_2, ..., x_{axis-1}, x_{axis+1}, ..., x_N)\) .

  • value (Tensor) - The maximum value of input tensor, with the same shape as index.

Raises:
Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.array([0.0, 0.4, 0.6, 0.7, 0.1]), mindspore.float32)
>>> output, index = x.argmax_with_value()
>>> print(output, index)
0.7 3
>>> output, index = x.argmax_with_value(keep_dims=True)
>>> print(output, index)
[0.7] [3]
argmin(axis=None, keepdims=False)[source]

For details, please refer to mindspore.ops.argmin().

argmin_with_value(axis=0, keep_dims=False)[source]

Returns the minimum value with corresponding index.

Note

In auto_parallel and semi_auto_parallel mode, the first output index can not be used.

Warning

  • If there are multiple minimum values, the index of the first minimum value is used.

  • The value range of axis is [-dims, dims - 1]. dims is the dimension length of this tensor.

Parameters:
  • axis (int) – The dimension to reduce. Default: 0.

  • keep_dims (bool) – Whether to reduce dimension, if true the output will keep the same dimension as the input, the output will reduce dimension if false. Default: False.

Returns:

tuple (Tensor), tuple of 2 tensors, containing the corresponding index and the minimum value of the input tensor.

  • index (Tensor) - The index for the minimum value of the input tensor. If keep_dims is true, the shape of output tensors is \((x_1, x_2, ..., x_{axis-1}, 1, x_{axis+1}, ..., x_N)\). Otherwise, the shape is \((x_1, x_2, ..., x_{axis-1}, x_{axis+1}, ..., x_N)\) .

  • value (Tensor) - The minimum value of input tensor, with the same shape as index.

Raises:
Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.array([0.0, 0.4, 0.6, 0.7, 0.1]), mindspore.float32)
>>> output, index = x.argmin_with_value()
>>> print(output, index
0.0 0
>>> output, index = x.argmin_with_value(keep_dims=True)
>>> print(output, index)
[0.0] [0]
argsort(axis=-1, descending=False)[source]

For details, please refer to mindspore.ops.argsort().

argwhere()[source]

For details, please refer to mindspore.ops.argwhere().

asin()[source]

For details, please refer to mindspore.ops.asin().

asinh()[source]

For details, please refer to mindspore.ops.asinh().

asnumpy()[source]

Convert tensor to numpy array. Returns self tensor as a NumPy ndarray. This tensor and the returned ndarray share the same underlying storage. Changes to self tensor will be reflected in the ndarray.

Returns:

A numpy ndarray which shares the same underlying storage with the tensor.

Examples

>>> from mindspore import Tensor
>>> import numpy as np
>>> x = Tensor(np.array([1, 2], dtype=np.float32))
>>> y = x.asnumpy()
>>> y[0] = 11
>>> print(x)
[11.  2.]
>>> print(y)
[11.  2.]
asnumpy_of_slice_persistent_data(param_key, slice_index)[source]

Convert a slice of tensor data to numpy array. A slice is part of tensor data. Returns as a NumPy ndarray. This slice tensor data and the returned ndarray share the same underlying storage. Changes to self tensor will be reflected in the ndarray.

Returns:

A numpy ndarray which shares the same underlying storage with the slice of tensor data.

assign_value(value)[source]

Assign another tensor value to this tensor.

Parameters:

value (Tensor) – Tensor for assignment.

Returns:

Tensor, Tensor that’s been assigned.

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, numpy.dtype, str]) – Designated tensor dtype, can be in format of mindspore.dtype.float32 or numpy.float32 or 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. Default: True.

Returns:

Tensor, with the designated dtype.

Raises:

TypeError – If the specified dtype 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
atan()[source]

For details, please refer to mindspore.ops.atan().

atan2(other)[source]

For details, please refer to mindspore.ops.atan2().

atanh()[source]

For details, please refer to mindspore.ops.atanh().

baddbmm(batch1, batch2, beta=1, alpha=1)[source]

For details, please refer to mindspore.ops.baddbmm().

bernoulli(p=0.5, seed=None)[source]

For details, please refer to mindspore.ops.bernoulli().

bincount(weights=None, minlength=0)[source]

For details, please refer to mindspore.ops.bincount().

bitwise_and(other)[source]

For details, please refer to mindspore.ops.bitwise_and().

bitwise_left_shift(other)[source]

For details, please refer to mindspore.ops.bitwise_left_shift().

bitwise_or(other)[source]

For details, please refer to mindspore.ops.bitwise_or().

bitwise_right_shift(other)[source]

For details, please refer to mindspore.ops.bitwise_right_shift().

bitwise_xor(other)[source]

For details, please refer to mindspore.ops.bitwise_xor().

bmm(mat2)[source]

For details, please refer to mindspore.ops.bmm().

bool()[source]

Converts input tensor dtype to bool. If the value in tensor is zero, it will be False, otherwise it will be True.

Returns:

Tensor, converted to the bool dtype.

Supported Platforms:

Ascend GPU CPU

Examples

>>> input_x = Tensor(np.ones([2,2]), mindspore.float32)
>>> output = input_x.bool()
>>> print(output.dtype)
Bool
broadcast_to(shape)[source]

For details, please refer to mindspore.ops.broadcast_to().

ceil()[source]

For details, please refer to mindspore.ops.ceil().

cholesky(upper=False)[source]

For details, please refer to mindspore.ops.cholesky().

cholesky_inverse(upper=False)[source]

For details, please refer to mindspore.ops.cholesky_inverse().

choose(choices, mode='clip')[source]

Construct a tensor from an index tensor and a list of tensors to choose from.

Parameters:
  • choices (Union[tuple, list, Tensor]) – Choice tensors. The input tensor and all of the choices must be broadcasted to the same shape. If choices is itself a tensor, 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: Raises an error;

    • wrap: Wraps around;

    • clip: Clips to the range. ‘clip’ mode means that values greater than n-1 are mapped to n-1. Note that this disables indexing with negative numbers.

    Default: ‘clip’.

Returns:

Tensor, the merged result.

Raises:

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

Supported Platforms:

Ascend GPU CPU

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]
chunk(chunks, axis=0)[source]

For details, please refer to mindspore.ops.chunk().

clamp(min=None, max=None)[source]

For details, please refer to mindspore.ops.clamp().

clip(min=None, max=None)[source]

Alias for mindspore.Tensor.clamp().

col2im(output_size, kernel_size, dilation, padding_value, stride)[source]

For details, please refer to mindspore.ops.col2im().

conj()[source]

For details, please refer to mindspore.ops.conj().

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.]]
copysign(other)[source]

For details, please refer to mindspore.ops.copysign().

cos()[source]

For details, please refer to mindspore.ops.cos().

cosh()[source]

For details, please refer to mindspore.ops.cosh().

cov(*, correction=1, fweights=None, aweights=None)[source]

For details, please refer to mindspore.ops.cov().

cross(other, dim=None)[source]

For details, please refer to mindspore.ops.cross().

cummax(axis)[source]

For details, please refer to mindspore.ops.cummax().

cummin(axis)[source]

For details, please refer to mindspore.ops.cummin().

cumprod(dim, dtype=None)[source]

For details, please refer to mindspore.ops.cumprod().

cumsum(axis=None, dtype=None)[source]

For details, please refer to mindspore.ops.cumsum().

data_sync(self: mindspore._c_expression.Tensor, arg0: bool) → None
deg2rad()[source]

For details, please refer to mindspore.ops.deg2rad().

det()[source]

For details, please refer to mindspore.ops.det().

diag()[source]

For details, please refer to mindspore.ops.diag().

diagflat(offset=0)[source]

For details, please refer to mindspore.ops.diagflat().

diagonal(offset=0, axis1=0, axis2=1)[source]

For details, please refer to mindspore.ops.diagonal().

diff(n=1, axis=-1, prepend=None, append=None)[source]

For details, please refer to mindspore.ops.diff().

digamma()[source]

For details, please refer to mindspore.ops.digamma().

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
div(value, *, rounding_mode=None)[source]

For details, please refer to mindspore.ops.div().

divide(value, *, rounding_mode=None)[source]

Alias for mindspore.Tensor.div().

dot(other)[source]

For details, please refer to mindspore.ops.dot().

dsplit(indices_or_sections)[source]

For details, please refer to mindspore.ops.dsplit().

property dtype

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

equal(other)[source]

For details, please refer to mindspore.ops.equal().

erf()[source]

For details, please refer to mindspore.ops.erf().

erfc()[source]

For details, please refer to mindspore.ops.erfc().

erfinv()[source]

For details, please refer to mindspore.ops.erfinv().

exp()[source]

For details, please refer to mindspore.ops.exp().

expand(size)[source]

For details, please refer to mindspore.ops.expand().

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 the input tensor must obey the broadcasting rule.

Returns:

Tensor, has the same dimension as input tensor.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> from mindspore import dtype as mstype
>>> x = Tensor([1, 2, 3], dtype=mstype.float32)
>>> y = Tensor(np.ones((2, 3)), dtype=mstype.float32)
>>> output = x.expand_as(y)
>>> print(output)
[[1. 2. 3.]
[1. 2. 3.]]
expand_dims(axis)[source]

For details, please refer to mindspore.ops.expand_dims().

expm1()[source]

For details, please refer to mindspore.ops.expm1().

fill(value)[source]

Tensor.fill is deprecated, please use ops.fill instead.

fills(value)[source]

Tensor.fills is deprecated, please use ops.fill instead.

flatten(order='C', *, start_dim=0, end_dim=-1)[source]

For details, please refer to mindspore.ops.flatten().

flip(dims)[source]

For details, please refer to mindspore.ops.flip().

fliplr()[source]

For details, please refer to mindspore.ops.fliplr().

flipud()[source]

For details, please refer to mindspore.ops.flipud().

float()[source]

Converts input tensor dtype to float32.

Returns:

Tensor, converted to the float32 dtype.

Supported Platforms:

Ascend GPU CPU

Examples

>>> input_x = Tensor(np.ones([2,2]), mindspore.int32)
>>> output = input_x.float()
>>> print(output.dtype)
Float32
float_power(other)[source]

For details, please refer to mindspore.ops.float_power().

floor()[source]

For details, please refer to mindspore.ops.floor().

flush_from_cache()[source]

Flush cache data to host if tensor is cache enable.

Examples

>>> from mindspore import Tensor
>>> import numpy as np
>>> x = Tensor(np.array([1, 2], dtype=np.float32))
>>> y = x.flush_from_cache()
>>> print(y)
None
fmod(other)[source]

For details, please refer to mindspore.ops.fmod().

fold(output_size, kernel_size, dilation=1, padding=0, stride=1)[source]

For details, please refer to mindspore.ops.fold().

frac()[source]

For details, please refer to mindspore.ops.frac().

static from_numpy(array)[source]

Convert numpy array to Tensor. If the data is not C contiguous, the data will be copied to C contiguous to construct the tensor. Otherwise, The tensor will be constructed using this numpy array without copy.

Parameters:

array (numpy.array) – The input array.

Returns:

Tensor, has the same data type as input array.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = np.array([1, 2])
>>> output = Tensor.from_numpy(x)
>>> print(output)
[1 2]
gather(input_indices, axis, batch_dims=0)[source]

For details, please refer to mindspore.ops.gather().

gather_elements(dim, index)[source]

For details, please refer to mindspore.ops.gather_elements().

gather_nd(indices)[source]

For details, please refer to mindspore.ops.gather_nd().

ge(x)[source]

For details, please refer to mindspore.ops.ge().

geqrf()[source]

For details, please refer to mindspore.ops.geqrf().

ger(vec2)[source]

For details, please refer to mindspore.ops.ger().

getitem_index_info(self: object, arg0: object, arg1: bool_) → object
greater(other)[source]

For details, please refer to mindspore.ops.greater().

greater_equal(other)[source]

For details, please refer to mindspore.ops.greater_equal().

gt(x)[source]

For details, please refer to mindspore.ops.gt().

half()[source]

Converts input tensor dtype to float16.

Returns:

Tensor, converted to the float16 dtype.

Supported Platforms:

Ascend GPU CPU

Examples

>>> input_x = Tensor(np.ones([2,2]), mindspore.int32)
>>> output = input_x.half()
>>> print(output.dtype)
Float16
hardshrink(lambd=0.5)[source]

For details, please refer to mindspore.ops.hardshrink().

property has_init

Whether tensor is initialized.

heaviside(values)[source]

For details, please refer to mindspore.ops.heaviside().

histc(bins=100, min=0.0, max=0.0)[source]

For details, please refer to mindspore.ops.histc().

hsplit(indices_or_sections)[source]

For details, please refer to mindspore.ops.hsplit().

hypot(other)[source]

For details, please refer to mindspore.ops.hypot().

i0()[source]

For details, please refer to mindspore.ops.i0().

igamma(other)[source]

For details, please refer to mindspore.ops.igamma().

igammac(other)[source]

For details, please refer to mindspore.ops.igammac().

imag()[source]

Returns a new tensor containing imaginary value of the input tensor. If input tensor is real, it will return zeros.

Returns:

Tensor, the shape is the same as the input tensor.

Supported Platforms:

GPU CPU

Examples

>>> x = Tensor(np.asarray(np.complex(1.3 + 0.4j)), mindspore.complex64)
>>> output = x.imag()
>>> print(output)
0.4
index_add(dim, index, source, *, alpha=1)[source]

For details, please refer to mindspore.ops.index_add().

index_fill(axis, index, value)[source]

For details, please refer to mindspore.ops.index_fill().

index_select(axis, index)[source]

For details, please refer to mindspore.ops.index_select().

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

Get the tensor format data of this Tensor.

Note

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
>>> from mindspore.common.initializer import initializer, Constant
>>> x = initializer(Constant(1), [2, 2], ms.float32)
>>> out = x.init_data()
>>> print(out)
[[1. 1.]
 [1. 1.]]
inner(other)[source]

For details, please refer to mindspore.ops.inner().

inplace_update(v, indices)[source]

For details, please refer to mindspore.ops.inplace_update().

int()[source]

Converts input tensor dtype to int32. If the value in tensor is float or half, the decimal will be discarded.

Returns:

Tensor, converted to the int32 dtype.

Supported Platforms:

Ascend GPU CPU

Examples

>>> input_x = Tensor(np.ones([2,2]), mindspore.float32)
>>> output = input_x.int()
>>> print(output.dtype)
Int32
inv()[source]

For details, please refer to mindspore.ops.inv().

inverse()[source]

For details, please refer to mindspore.ops.inverse().

invert()[source]

For details, please refer to mindspore.ops.invert().

is_complex()[source]

For details, please refer to mindspore.ops.is_complex().

is_floating_point()[source]

For details, please refer to mindspore.ops.is_floating_point().

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
is_persistent_data()[source]

Check if size of tensor is huge, and need save data to persistent storage. If size of tensor is bigger then MS_EMBEDDING_REMOTE_CACHE_MEMORY_SIZE, it will use persistent storage to save tensor data. And will spilt data to some slice.

Returns:

True or False

is_signed()[source]

Judge whether the data type of tensor is a signed data type.

Returns:

Bool. If the dtype of self is a signed data type, return True. Otherwise, return False.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore as ms
>>> from mindspore import Tensor
>>> x = ms.Tensor([1, 2, 3], ms.int64)
>>> y = ms.Tensor([1, 2, 3], ms.uint64)
>>> output = x.is_signed()
>>> output2 = y.is_signed()
>>> print(output)
True
>>> print(output2)
False
isclose(x2, rtol=1e-05, atol=1e-08, equal_nan=False)[source]

For details, please refer to mindspore.ops.isclose().

isfinite()[source]

For details, please refer to mindspore.ops.isfinite().

isinf()[source]

For details, please refer to mindspore.ops.isinf().

isnan()[source]

For details, please refer to mindspore.ops.isnan().

isneginf()[source]

For details, please refer to mindspore.ops.isneginf().

isposinf()[source]

For details, please refer to mindspore.ops.isposinf().

isreal()[source]

For details, please refer to mindspore.ops.isreal().

item(index=None)[source]

Get the item at the specified index of the tensor.

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 equal to self.ndim.

Supported Platforms:

Ascend GPU CPU

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 that doesn’t affect the original tensor, with value set by \(Tensor[args] = item\).

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

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

Supported Platforms:

Ascend GPU CPU

Examples

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

Return the length of one tensor element in bytes.

lcm(other)[source]

For details, please refer to mindspore.ops.lcm().

ldexp(other)[source]

For details, please refer to mindspore.ops.ldexp().

le(other)[source]

For details, please refer to mindspore.ops.le().

lerp(end, weight)[source]

For details, please refer to mindspore.ops.lerp().

less(other)[source]

For details, please refer to mindspore.ops.less().

less_equal(other)[source]

For details, please refer to mindspore.ops.less_equal().

lgamma()[source]

For details, please refer to mindspore.ops.lgamma().

log()[source]

For details, please refer to mindspore.ops.log().

log10()[source]

For details, please refer to mindspore.ops.log10().

log1p()[source]

For details, please refer to mindspore.ops.log1p().

log2()[source]

For details, please refer to mindspore.ops.log2().

log_matrix_determinant()[source]

For details, please refer to mindspore.ops.log_matrix_determinant().

logaddexp(other)[source]

For details, please refer to mindspore.ops.logaddexp().

logaddexp2(other)[source]

For details, please refer to mindspore.ops.logaddexp2().

logdet()[source]

For details, please refer to mindspore.ops.logdet().

logical_and(other)[source]

For details, please refer to mindspore.ops.logical_and().

logical_not()[source]

For details, please refer to mindspore.ops.logical_not().

logical_or(other)[source]

For details, please refer to mindspore.ops.logical_or().

logical_xor(other)[source]

For details, please refer to mindspore.ops.logical_xor().

logit(eps=None)[source]

For details, please refer to mindspore.ops.logit().

logsumexp(axis, keepdims=False)[source]

For details, please refer to mindspore.ops.logsumexp().

long()[source]

Converts input tensor dtype to int64. If the value in tensor is float or half, the decimal will be discarded.

Returns:

Tensor, converted to the int64 dtype.

Supported Platforms:

Ascend GPU CPU

Examples

>>> input_x = Tensor(np.ones([2,2]), mindspore.int32)
>>> output = input_x.long()
>>> print(output.dtype)
Int64
lstsq(A)[source]

For details, please refer to mindspore.ops.lstsq().

lt(other)[source]

Alias for mindspore.Tensor.less().

property mH

Accessing this property is equivalent to Calling self.adjoint(). For details, please refer to mindspore.ops.adjoint().

property mT

Returns the Tensor that exchanges the last two dimensions. Accessing the attribute, x.mT, is equal to calling the method, x.swapaxes(-2, -1). For details, please refer to mindspore.Tensor.swapaxes().

masked_fill(mask, value)[source]

For details, please refer to mindspore.ops.masked_fill().

masked_select(mask)[source]

For details, please refer to mindspore.ops.masked_select().

matmul(tensor2)[source]

For details, please refer to mindspore.ops.matmul().

matrix_determinant()[source]

For details, please refer to mindspore.ops.matrix_determinant().

matrix_power(n)[source]

For details, please refer to mindspore.ops.matrix_power().

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

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

Parameters:
  • axis (Union[None, int, list, 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.

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

  • where (Tensor[bool], optional) – A boolean tensor 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.

  • return_indices (bool, optional) – Whether to return the index of the maximum value. Default: False. If axis is a list or tuple of ints, it must be False.

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 a tensor of dimension self.ndim - 1.

Raises:

TypeError – If arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.argmin(): Return the indices of the minimum values along an axis.

mindspore.Tensor.argmax(): Return the indices of the maximum values along an axis.

mindspore.Tensor.min(): Return the minimum of a tensor or minimum along an axis.

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
>>> value, indices = a.max(axis=0, return_indices=True)
>>> print(value)
[2. 3.]
>>> print(indices)
[1 1]
maximum(other)[source]

For details, please refer to mindspore.ops.maximum().

mean(axis=None, keep_dims=False)[source]

For details, please refer to mindspore.ops.mean().

median(axis=-1, keepdims=False)[source]

For details, please refer to mindspore.ops.median().

min(axis=None, keepdims=False, *, initial=None, where=True, return_indices=False)[source]

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

Parameters:
  • axis (Union[None, int, list, tuple of ints], optional) – An axis or axes along which to operate. By default, flattened input is used. If axis 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 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.

Keyword Arguments:
  • 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 tensor 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.

  • return_indices (bool, optional) – Whether to return the index of the minimum value. Default: False. If axis is a list or tuple of ints, it must be False.

Returns:

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

Raises:

TypeError – If arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.argmin(): Return the indices of the minimum values along an axis.

mindspore.Tensor.argmax(): Return the indices of the maximum values along an axis.

mindspore.Tensor.max(): Return the minimum of a tensor or minimum along an axis.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(4).reshape((2, 2)).astype('float32'))
>>> output = a.min()
>>> print(output)
0.0
>>> output = a.min(axis=0)
>>> print(output)
[0. 1.]
>>> output = a.min(axis=0, initial=9, where=Tensor([False]))
>>> print(output)
[9. 9.]
>>> output = a.min(axis=0, initial=9, where=Tensor([False, True]))
>>> print(output)
[9. 1.]
>>> value, indices = a.min(axis=0, return_indices=True)
>>> print(value)
[0. 1.]
>>> print(indices)
[0 0]
minimum(other)[source]

For details, please refer to mindspore.ops.minimum().

mm(mat2)[source]

For details, please refer to mindspore.ops.mm().

moveaxis(source, destination)[source]

For details, please refer to mindspore.ops.moveaxis().

movedim(source, destination)[source]

For details, please refer to mindspore.ops.movedim().

msort()[source]

For details, please refer to mindspore.ops.msort().

mul(value)[source]

For details, please refer to mindspore.ops.mul().

multinomial(num_samples, replacement=True, seed=None)[source]

For details, please refer to mindspore.ops.multinomial().

multiply(value)[source]

For details, please refer to mindspore.ops.multiply().

mvlgamma(p)[source]

For details, please refer to mindspore.ops.mvlgamma().

nan_to_num(nan=0.0, posinf=None, neginf=None)[source]

For details, please refer to mindspore.ops.nan_to_num().

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

For details, please refer to mindspore.ops.nansum().

narrow(axis, start, length)[source]

For details, please refer to mindspore.ops.narrow().

property nbytes

Return the total number of bytes taken by the tensor.

property ndim

Return the number of tensor dimensions.

ndimension()[source]

Alias for mindspore.Tensor.ndim().

ne(other)[source]

For details, please refer to mindspore.ops.ne().

neg()[source]

For details, please refer to mindspore.ops.neg().

negative()[source]

For details, please refer to mindspore.ops.negative().

nelement()[source]

Alias for mindspore.Tensor.numel().

new_ones(size, *, dtype=None)[source]

Return a tensor of size filled with ones.

Parameters:

size (Union[int, tuple, list]) – An int, list or tuple of integers defining the output shape.

Keyword Arguments:

dtype (mindspore.dtype, optional) – The desired dtype of the output tensor. If None, the returned tensor has the same dtype as self. Default: None.

Returns:

Tensor, the shape and dtype is defined above and filled with ones.

Raises:

TypeError – If size is not an int, list or tuple of integers.

Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.array([1, 2, 3]), mindspore.float32)
>>> output = x.new_ones((2, 2))
>>> print(output)
[[1. 1.]
 [1. 1.]]
new_zeros(size, *, dtype=None)[source]

Return a tensor of size filled with zeros.

Parameters:

size (Union[int, tuple, list]) – An int, list or tuple of integers defining the output shape.

Keyword Arguments:

dtype (mindspore.dtype, optional) – The desired dtype of the output tensor. If None, the returned tensor has thesame dtype as self. Default: None.

Returns:

Tensor, the shape and dtype is defined above and filled with zeros.

Raises:

TypeError – If size is not an int, list or tuple of integers.

Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.array([1, 2, 3]), mindspore.float32)
>>> output = x.new_zeros((2, 2))
>>> print(output)
[[0. 0.]
 [0. 0.]]
nextafter(other)[source]

For details, please refer to mindspore.ops.nextafter().

nonzero()[source]

For details, please refer to mindspore.ops.nonzero().

norm(ord=None, dim=None, keepdim=False, *, dtype=None)[source]

For details, please refer to mindspore.ops.norm().

not_equal(other)[source]

For details, please refer to mindspore.ops.not_equal().

numel()[source]

For details, please refer to mindspore.ops.numel().

numpy()[source]

Alias for mindspore.Tensor.asnumpy().

permute(*axis)[source]

For details, please refer to mindspore.ops.permute().

persistent_data_from_numpy(self: array, arg0: int_) → mindspore._c_expression.Tensor

Creates a Tensor from a numpy.ndarray without copy. Use persistent data tensor.

Arg:

array (numpy.ndarray): The input ndarray. slice_num (int): The slice num of persistent data tensor.

Returns:

Tensor, tensor with shared data to input ndarray.

Examples

>>> a = np.ones((2, 3))
>>> t = mindspore.Tensor.persistent_data_from_numpy(a, 1)
positive()[source]

For details, please refer to mindspore.ops.positive().

pow(exponent)[source]

For details, please refer to mindspore.ops.pow().

prod(axis=None, keep_dims=False)[source]

For details, please refer to mindspore.ops.prod().

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

The name of the function comes from the acronym for “peak to peak”. Calculate the difference between the maximum value and the minimum value along the axis.

Note

Numpy argument out is 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 tensor. 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 tensor. 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.]
qr(some=True)[source]

For details, please refer to mindspore.ops.qr().

rad2deg()[source]

For details, please refer to mindspore.ops.rad2deg().

random_categorical(num_sample, seed=0, dtype=mindspore.int64)[source]

For details, please refer to mindspore.ops.random_categorical().

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

See also

mindspore.Tensor.reshape(): Give a new shape to a tensor without changing its data.

mindspore.Tensor.flatten(): Return a copy of the tensor collapsed into one dimension.

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,)
real()[source]

For details, please refer to mindspore.ops.real().

reciprocal()[source]

For details, please refer to mindspore.ops.reciprocal().

remainder(divisor)[source]

For details, please refer to mindspore.ops.remainder().

renorm(p, axis, maxnorm)[source]

For details, please refer to mindspore.ops.renorm().

repeat(repeats, axis=None)[source]

Repeat elements of a tensor.

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. Default: None.

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

See also

mindspore.Tensor.reshape(): Give a new shape to a tensor without changing its data.

mindspore.Tensor.resize(): Changes shape and size of tensor in-place.

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]]
repeat_interleave(repeats, dim=None)[source]

For details, please refer to mindspore.ops.repeat_interleave().

reshape(*shape)[source]

For details, please refer to mindspore.ops.reshape().

reshape_as(other)[source]

Change the shape of the Tensor to the shape of other without changing the data.

Parameters:

other (Tensor) – The result tensor has the same shape as other.

Returns:

Tensor, has the same shape as other.

Supported Platforms:

Ascend GPU CPU

Examples

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

Changes shape and size of tensor in-place.

If the shape of the new tensor is larger than the shape of the original tensor, the new tensor will be filled with 0. And if the shape of the new tensor is smaller than the shape of the original tensor, the new tensor is filled with the elements of the original tensor in order.

Note

Instead of changing the size of the input tensor 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 tensor.

Returns:

Tensor.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.reshape(): Give a new shape to a tensor without changing its data.

mindspore.Tensor.repeat(): Repeat elements of a tensor.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32))
>>> y = x.resize(3, 3)
>>> print(y)
[[1. 2. 3.]
[4. 5. 6.]
[0. 0. 0.]]
>>> y = x.resize(2, 2)
>>> print(y)
[[1. 2.]
[3. 4.]]
reverse(axis)[source]

For details, please refer to mindspore.ops.reverse().

reverse_sequence(seq_lengths, seq_dim=0, batch_dim=0)[source]

For details, please refer to mindspore.ops.reverse_sequence().

roll(shifts, dims)[source]

For details, please refer to mindspore.ops.roll().

rot90(k, dims)[source]

For details, please refer to mindspore.ops.rot90().

round()[source]

For details, please refer to mindspore.ops.round().

rsqrt()[source]

For details, please refer to mindspore.ops.rsqrt().

scatter(axis, index, src)[source]

For details, please refer to mindspore.ops.scatter().

scatter_add(indices, updates)[source]

For details, please refer to mindspore.ops.scatter_add().

scatter_div(indices, updates)[source]

For details, please refer to mindspore.ops.scatter_div().

scatter_max(indices, updates)[source]

For details, please refer to mindspore.ops.scatter_max().

scatter_min(indices, updates)[source]

For details, please refer to mindspore.ops.scatter_min().

scatter_mul(indices, updates)[source]

For details, please refer to mindspore.ops.scatter_mul().

scatter_sub(indices, updates)[source]

Creates a new tensor by subtracting the values from the positions in self tensor indicated by indices, with values from updates. When multiple values are provided for the same index, the result of the update will be to subtract these values respectively. This operation is almost equivalent to using mindspore.ops.ScatterNdSub , except that the updates are applied on output Tensor instead of input Parameter.

The last axis of indices is the depth of each index vectors. For each index vector, there must be a corresponding value in updates. The shape of updates should be equal to the shape of self[indices]. For more details, see use cases.

Note

On GPU, if some values of the indices are out of bound, instead of raising an index error, the corresponding updates will not be updated to self tensor. On CPU, if some values of the indices are out of bound, raising an index error. On Ascend, out of bound checking is not supported, if some values of the indices are out of bound, unknown errors may be caused.

Parameters:
  • indices (Tensor) – The index of input tensor whose data type is int32 or int64. The rank must be at least 2.

  • updates (Tensor) – The tensor to update the input tensor, has the same type as input, and updates.shape should be equal to indices.shape[:-1] + self.shape[indices.shape[-1]:].

Returns:

Tensor, has the same shape and type as self tensor.

Raises:
  • TypeError – If dtype of indices is neither int32 nor int64.

  • ValueError – If length of shape of self tensor is less than the last dimension of shape of indices.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]).astype('float32'))
>>> indices = Tensor(np.array([[0, 0], [0, 0]]).astype('int32'))
>>> updates = Tensor(np.array([1.0, 2.2]).astype('float32'))
>>> output = x.scatter_sub(indices, updates)
>>> print(output)
[[-3.3000002  0.3        3.6      ]
[ 0.4        0.5       -3.2      ]]
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 the tensor.

  • side (str, 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 the tensor). Default: ‘left’.

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

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
select(condition, y)[source]

For details, please refer to mindspore.ops.select().

set_cast_dtype(self: mindspore._c_expression.Tensor, dtype: mindspore._c_expression.typing.Type = None) → None
set_const_arg(const_arg=True)[source]

Specify whether the tensor is a constant when it is used for the argument of a network.

Parameters:

const_arg (bool) – Whether the tensor is a constant when it is used for the argument of a network. Default: True.

Returns:

Tensor, has been specified whether to be a const network argument.

Raises:

TypeError – If const_arg is not a bool.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1,2,3],[4,5,6]], dtype=np.float32))
>>> x.set_const_arg(True)
set_dtype(self: mindspore._c_expression.Tensor, arg0: mindspore._c_expression.typing.Type) → mindspore._c_expression.typing.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)
setitem_index_info(self: object, arg0: object, arg1: object, arg2: bool_) → object
sgn()[source]

For details, please refer to mindspore.ops.sgn().

property shape

For details, please refer to mindspore.ops.shape().

short()[source]

Return a copy of the tensor, cast to int16 type, equivalent to self.astype(mstype.int16). If the value in tensor is float or half, the decimal will be discarded. For details, please refer to mindspore.Tensor.astype().

Returns:

Tensor, converted to the int16 dtype.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore as ms
>>> import numpy as np
>>> x = ms.Tensor(np.array([1,2,3,4,5]), ms.int32)
>>> output = x.short()
>>> output
Tensor(shape=[5], dtype=Int16, value= [1, 2, 3, 4, 5])
sigmoid()[source]

For details, please refer to mindspore.ops.sigmoid().

sign()[source]

For details, please refer to mindspore.ops.sign().

signbit()[source]

For details, please refer to mindspore.ops.signbit().

sin()[source]

For details, please refer to mindspore.ops.sin().

sinc()[source]

For details, please refer to mindspore.ops.sinc().

sinh()[source]

For details, please refer to mindspore.ops.sinh().

property size

For details, please refer to mindspore.ops.size().

slice_num_of_persistent_data()[source]

Get slice num of a tensor which use persistent storage.

Returns:

Num of slice.

slice_shape_of_persistent_data()[source]

Get slice shape of tensor after cut to slice size.

Returns:

The slice shape of tensor.

slogdet()[source]

For details, please refer to mindspore.ops.slogdet().

soft_shrink(lambd=0.5)[source]

For details, please refer to mindspore.ops.soft_shrink().

sort(axis=-1, descending=False)[source]

For details, please refer to mindspore.ops.sort().

split(split_size_or_sections, axis=0)[source]

For details, please refer to mindspore.ops.split().

sqrt()[source]

For details, please refer to mindspore.ops.sqrt().

square()[source]

For details, please refer to mindspore.ops.square().

squeeze(axis=None)[source]

For details, please refer to mindspore.ops.squeeze().

std(axis=None, ddof=0, keepdims=False)[source]

For details, please refer to mindspore.ops.std().

property strides

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

sub(y)[source]

For details, please refer to mindspore.ops.sub().

subtract(other, *, alpha=1)[source]

For details, please refer to mindspore.ops.subtract().

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

Return sum of tensor 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 the elements of the input tensor. 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 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 the 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

See also

mindspore.Tensor.cumsum(): Return the cumulative sum of the elements along a given axis.

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.]
sum_to_size(*size)[source]

Sum self Tensor to the size. size must be expandable to the Tensor size.

Parameters:

size (Union[tuple(int), int]) – The expected shape of output Tensor.

Returns:

Tensor, the sum result of self Tensor according to the size.

Raises:

ValueError – If size is not expandable to the size of self Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.random.randn(3, 3, 3, 3, 3, 3), mindspore.float32)
>>> output = x.sum_to_size((1, 3, 1, 3))
>>> print(output.shape)
(1, 3, 1, 3)
svd(full_matrices=False, compute_uv=True)[source]

For details, please refer to mindspore.ops.svd().

swapaxes(axis0, axis1)[source]

For details, please refer to mindspore.ops.swapaxes().

swapdims(dim0, dim1)[source]

For details, please refer to mindspore.ops.swapdims().

t()[source]

For details, please refer to mindspore.ops.t().

take(indices, axis=None, mode='clip')[source]

Takes elements from a tensor 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 tensor is used. Default: None.

  • mode ('raise', 'wrap', 'clip', optional) –

    • 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]
tan()[source]

For details, please refer to mindspore.ops.tan().

tanh()[source]

For details, please refer to mindspore.ops.tanh().

tensor_split(indices_or_sections, axis=0)[source]

For details, please refer to mindspore.ops.tensor_split().

tile(multiples)[source]

For details, please refer to mindspore.ops.tile().

to(dtype)[source]

Performs tensor dtype conversion.

Parameters:

dtype (Number) – The valid data type of the output tensor. Only constant value is allowed.

Returns:

Tensor, converted to the specified dtype.

Raises:

TypeError – If dtype is not a Number.

Supported Platforms:

Ascend GPU CPU

Examples

>>> input_np = np.random.randn(2, 3, 4, 5).astype(np.float32)
>>> input_x = Tensor(input_np)
>>> dtype = mindspore.int32
>>> output = input_x.to(dtype)
>>> print(output.dtype)
Int32
to_coo()[source]

Convert a Tensor to COOTensor.

Note

Only 2-D tensor is supported for now.

Returns:

COOTensor, a sparse representation of the original dense tensor, containing the following parts.

  • indices (Tensor): 2-D integer tensor, indicates the positions of values of the dense tensor.

  • values (Tensor): 1-D tensor, indicates the non-zero values of the dense tensor.

  • shape (tuple(int)): the shape of the COOTensor, is the same as the original dense tensor.

Raises:

ValueError – If input tensor is not 2-D.

Supported Platforms:

GPU

Examples

>>> import numpy as np
>>> import mindspore
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1,  0], [-5, 0]]), mindspore.float32)
>>> output = x.to_coo()
>>> print(output.indices, output.values, output.shape)
[[0 0]
 [1 0]] [ 1. -5.] (2, 2)
to_csr()[source]

Convert a Tensor to CSRTensor.

Note

Only 2-D tensor is supported for now.

Returns:

CSRTensor, a sparse representation of the original dense tensor, containing the following parts.

  • indptr (Tensor): 1-D integer tensor, indicates the start and end point for values in each row.

  • indices (Tensor): 1-D integer tensor, indicates the column positions of all non-zero values of the input.

  • values (Tensor): 1-D tensor, indicates the non-zero values of the dense tensor.

  • shape (tuple(int)): the shape of the CSRTensor, is the same as the original dense tensor.

Raises:

ValueError – If input tensor is not 2-D.

Supported Platforms:

GPU

Examples

>>> import numpy as np
>>> import mindspore
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1,  0], [-5, 0]]), mindspore.float32)
>>> output = x.to_csr()
>>> print(output.indptr, output.indices, output.values, output.shape)
[0 1 2] [0 0] [ 1. -5.] (2, 2)
top_k(k, sorted=True)[source]

Tensor.top_k is deprecated, please use Tensor.topk instead.

topk(k, dim=None, largest=True, sorted=True)[source]

For details, please refer to mindspore.ops.topk().

trace(offset=0, axis1=0, axis2=1, dtype=None)[source]

Return the sum along diagonals of the tensor.

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, the sum along diagonals.

Raises:

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

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.diagonal(): Return specified diagonals.

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]

For details, please refer to mindspore.ops.transpose().

tril(diagonal=0)[source]

For details, please refer to mindspore.ops.tril().

triu(diagonal=0)[source]

For details, please refer to mindspore.ops.triu().

true_divide(value)[source]

Alias for Tensor.div() with \(rounding\_mode=None\). For details, please refer to mindspore.ops.div().

trunc()[source]

For details, please refer to mindspore.ops.trunc().

unbind(dim=0)[source]

For details, please refer to mindspore.ops.unbind().

unfold(kernel_size, dilation=1, padding=0, stride=1)[source]

For details, please refer to mindspore.ops.unfold().

unique_consecutive(return_idx=False, return_counts=False, axis=None)[source]

For details, please refer to mindspore.ops.unique_consecutive().

unique_with_pad(pad_num)[source]

For details, please refer to mindspore.ops.unique_with_pad().

unsorted_segment_max(segment_ids, num_segments)[source]

For details, please refer to mindspore.ops.unsorted_segment_max().

unsorted_segment_min(segment_ids, num_segments)[source]

For details, please refer to mindspore.ops.unsorted_segment_min().

unsorted_segment_prod(segment_ids, num_segments)[source]

For details, please refer to mindspore.ops.unsorted_segment_prod().

unsqueeze(dim)[source]

For details, please refer to mindspore.ops.unsqueeze().

value()[source]

Get the value of the tensor or the parameter.

Returns:

The value of the tensor or the parameter.

Examples

>>> from mindspore import Tensor
>>> import numpy as np
>>> x = Tensor(np.array([1, 2], dtype=np.float32))
>>> x_value = x.value()
>>> print(x_value)
[1.  2.]
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.

Returns:

Variance tensor.

Supported Platforms:

Ascend GPU CPU

See also

mindspore.Tensor.mean(): Reduce a dimension of a tensor by averaging all elements in the dimension.

mindspore.Tensor.std(): Compute the standard deviation along the specified axis.

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. It’s the same as mindspore.Tensor.reshape(), implemented by the underlying reshape operator.

Parameters:

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

Returns:

Tensor, which dimension is the input shape’s value.

Examples

>>> from mindspore import Tensor
>>> import numpy as np
>>> a = Tensor(np.array([[1, 2, 3], [2, 3, 4]], dtype=np.float32))
>>> output = a.view((3, 2))
>>> print(output)
[[1. 2.]
[3. 2.]
[3. 4.]]
view_as(other)[source]

View self Tensor as the same shape as other .

Parameters:

other (Tensor) – The returned Tensor has the same shape as other.

Returns:

Tensor, has the same shape as other.

Raises:

TypeError – If other is not a Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> a = Tensor([[1, 2, 3], [2, 3, 4]], mstype.float32)
>>> b = Tensor([1, 1, 1, 1, 1, 1], mstype.float32)
>>> output = a.view_as(b)
>>> print(output)
[1. 2. 3. 2. 3. 4.]
vsplit(indices_or_sections)[source]

For details, please refer to mindspore.ops.vsplit().

where(condition, y)[source]

For details, please refer to mindspore.ops.where().

xdivy(y)[source]

For details, please refer to mindspore.ops.xdivy().

xlogy(y)[source]

For details, please refer to mindspore.ops.xlogy().

class tinyms.RowTensor(indices=None, values=None, shape=None, row_tensor=None)[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, :, :, :, …].

For example, if indices is [0], values is [[1, 2]], shape is

\((3, 2)\) , then the dense representation of the row tensor will be:

[[1, 2],
 [0, 0],
 [0, 0]]

Warning

This is an experimental API that is subjected to change or deletion.

Parameters:
  • indices (Tensor) – A 1-D integer Tensor of shape \((D0)\) . Default: None.

  • values (Tensor) – A Tensor of any dtype of shape \((D0, D1, ..., Dn)\) . Default: None.

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

  • row_tensor (RowTensor) – A RowTensor object. Default: None.

Returns:

RowTensor, composed of indices, values, and shape.

Examples

>>> import mindspore as ms
>>> from mindspore import Tensor, RowTensor
>>> indices = Tensor([0])
>>> values = Tensor([[1, 2]], dtype=ms.float32)
>>> shape = (3, 2)
>>> x = RowTensor(indices, values, shape)
>>> print(x.values)
[[1. 2.]]
>>> print(x.indices)
[0]
>>> print(x.dense_shape)
(3, 2)
property dense_shape

Return RowTensor’s shape.

property indices

Return RowTensor’s indices.

property values

Return RowTensor’s non-zero values.

class tinyms.SparseTensor(indices, values, shape)[source]

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

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

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

For example, if indices is [[0, 1], [1, 2]], values is [1, 2], dense_shape is (3, 4), then the dense representation of the sparse tensor will be:

[[0, 1, 0, 0],
 [0, 0, 2, 0],
 [0, 0, 0, 0]]

Note

The interface is deprecated from version 1.7 and will be removed in a future version. Please use ‘COOTensor’ instead.

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.

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

Returns:

SparseTensor, composed of indices, values, and shape.

Examples

>>> import mindspore as ms
>>> import mindspore.nn as nn
>>> from mindspore import Tensor, SparseTensor
>>> indices = Tensor([[0, 1], [1, 2]])
>>> values = Tensor([1, 2], dtype=ms.float32)
>>> shape = (3, 4)
>>> x = SparseTensor(indices, values, shape)
>>> print(x.values)
[1. 2.]
>>> print(x.indices)
[[0 1]
 [1 2]]
>>> print(x.shape)
(3, 4)
property indices

Return SparseTensor’s indices.

property shape

Return SparseTensor’s shape.

property values

Return SparseTensor’s non-zero values.

class tinyms.COOTensor(indices=None, values=None, shape=None, coo_tensor=None)[source]

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

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

For example, if indices is [[0, 1], [1, 2]], values is [1, 2], shape is (3, 4), then the dense representation of the sparse tensor will be:

[[0, 1, 0, 0],
 [0, 0, 2, 0],
 [0, 0, 0, 0]]

Common arithmetic operations include: addition (+), subtraction (-), multiplication (*), and division (/). For details about operations supported by COOTensor, see operators.

Warning

  • This is an experimental API that is subject to change or deletion.

  • Currently, duplicate coordinates in the indices will not be coalesced. If the indices contain out-of-bound values, the result will be undefined.

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 COOTensor, respectively. Currently, ndims must be 2. Please make sure that the indices are in range of the given shape.

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

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

  • coo_tensor (COOTensor) – A COOTensor object.

Returns:

COOTensor, composed of indices, values, and shape.

Examples

>>> import mindspore as ms
>>> import mindspore.nn as nn
>>> from mindspore import Tensor, COOTensor
>>> indices = Tensor([[0, 1], [1, 2]], dtype=ms.int32)
>>> values = Tensor([1, 2], dtype=ms.float32)
>>> shape = (3, 4)
>>> x = COOTensor(indices, values, shape)
>>> print(x.values)
[1. 2.]
>>> print(x.indices)
[[0 1]
 [1 2]]
>>> print(x.shape)
(3, 4)
abs() → mindspore.common.sparse_tensor.COOTensor[source]

Return absolute value element-wisely.

Returns:

COOTensor.

Supported Platforms:

Ascend GPU CPU

add(other: mindspore.common.sparse_tensor.COOTensor, thresh: mindspore.common.tensor.Tensor) → mindspore.common.sparse_tensor.COOTensor[source]

Return the sum with another COOTensor.

Parameters:
  • other (COOTensor) – the second SparseTensor to sum.

  • thresh (Tensor) – A 0-D Tensor, represents the magnitude threshold that determines if an output value/index pair take space, Its dtype should match that of the values if they are real. If output’s value is less than the thresh, it will vanish.

Returns:

COOTensor, representing the sum.

Raises:
  • ValueError – If any input(self/other)’s indices’s dim is not equal to 2.

  • ValueError – If any input(self/other)’s values’s dim is not equal to 1.

  • ValueError – If any input(self/other)’s shape’s dim is not equal to 1.

  • ValueError – If thresh’s dim is not equal to 0.

  • TypeError – If any input(self/other)’s indices’s type is not equal to int64.

  • TypeError – If any input(self/other)’s shape’s type is not equal to int64.

  • ValueError – If any input(self/other)’s indices’s length is not equal to its values’s length.

  • TypeError – If any input(self/other)’s values’s type is not equal to anf of (int8/int16/int32/int64/float32/float64/complex64/complex128)

  • TypeError – If thresh’s type is not equal to anf of (int8/int16/int32/int64/float32/float64)

  • TypeError – If self’s indices’s type is not equal to other’s indices’s type

  • TypeError – If self’s values’s type is not equal to other’s values’s type

  • TypeError – If self’s shape’s type is not equal to other’s shape’s type

  • TypeError – If (self/other)’s value’s type is not matched with thresh’s type

Supported Platforms:

GPU CPU

Examples

>>> from mindspore import Tensor, COOTensor
>>> from mindspore import dtype as mstype
>>> indics0 = Tensor([[0, 1], [1, 2]], dtype=mstype.int64)
>>> values0 = Tensor([1, 2], dtype=mstype.int32)
>>> shape0 = (3, 4)
>>> input0 = COOTensor(indics0, values0, shape0)
>>> indics1 = Tensor([[0, 0], [1, 1]], dtype=mstype.int64)
>>> values1 = Tensor([3, 4], dtype=mstype.int32)
>>> shape1 = (3, 4)
>>> input1 = COOTensor(indics1, values1, shape1)
>>> thres = Tensor(0, dtype=mstype.int32)
>>> out = input0.add(input1, thres)
>>> print(out)
COOTensor(shape=[3, 4], dtype=Int32, indices=Tensor(shape=[4, 2], dtype=Int64, value=
[[0 0]
 [0 1]
 [1 1]
 [1 2]]), values=Tensor(shape=[4], dtype=Int32, value=[3 1 4 2]))
astype(dtype: mstype) → COOTensor[source]

Return a copy of the COOTensor, cast its values to a specified type.

Parameters:

dtype (Union[mindspore.dtype, numpy.dtype, str]) – Designated tensor dtype.

Returns:

COOTensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore as ms
>>> from mindspore import Tensor, COOTensor
>>> indices = Tensor([[0, 1], [1, 2]], dtype=ms.int32)
>>> values = Tensor([1, 2], dtype=ms.float32)
>>> shape = (3, 4)
>>> coo_tensor = COOTensor(indices, values, shape)
>>> print(coo_tensor.astype(ms.float64).dtype)
Float64
coalesce() → mindspore.common.sparse_tensor.COOTensor[source]

Returns a coalesced copy of an uncoalesced sparse tensor.

Returns:

A COOTensor.

Supported Platforms:

GPU

Examples

>>> import mindspore as ms
>>> import mindspore.ops as ops
>>> from mindspore import Tensor, COOTensor
>>> x_indices = Tensor([[0, 0, 1], [1, 1, 2]], dtype=ms.int64)
>>> x_values = Tensor([1, 5, 4], dtype=ms.float32)
>>> x_shape = (3, 3)
>>> coo_tensor = COOTensor(x_indices.transpose(), x_values, x_shape)
>>> res = coo_tensor.coalesce()
>>> print(res)
COOTensor(shape=[3, 3], dtype=Float32, indices=Tensor(shape=[2, 2], dtype=Int64,
    value=[[0 1] [1 2]]), values=Tensor(shape=[2], dtype=Float32, value=[6.00000000e+00 4.00000000e+00]))
property dtype

Return the dtype of the values of COOTensor (mindspore.dtype).

property indices

Return COOTensor’s indices.

property itemsize

Return the length of one tensor element in bytes.

property ndim

Return the number of tensor dimensions.

property shape

Return COOTensor’s shape.

property size

Return the number of non-zero values.

to_csr() → mindspore.common.sparse_tensor.CSRTensor[source]

Converts COOTensor to CSRTensor.

Note

Currently only supports CPU backend with LLVM 12.0.1 installed.

Returns:

CSRTensor.

Supported Platforms:

GPU CPU

to_dense() → mindspore.common.tensor.Tensor[source]

Converts COOTensor to Dense Tensor.

Returns:

Tensor.

Supported Platforms:

GPU

to_tuple() → Tuple[mindspore.common.tensor.Tensor, mindspore.common.tensor.Tensor, Tuple[int, ...]][source]

Return indices, values and shape as a tuple.

Returns:

Tuple.

Supported Platforms:

Ascend GPU CPU

property values

Return COOTensor’s non-zero values.

class tinyms.CSRTensor(indptr=None, indices=None, values=None, shape=None, csr_tensor=None)[source]

Constructs a sparse tensor in CSR (Compressed Sparse Row) format, with specified values indicated by values and row and column positions indicated by indptr and indices.

For example, if indptr is [0, 1, 2, 2], indices is [1, 2], values is [1., 2.], shape is (3, 4), then the dense representation of the sparse tensor will be:

[[0., 1., 0., 0.],
 [0., 0., 2., 0.],
 [0., 0., 0., 0.]]

Common arithmetic operations include: addition (+), subtraction (-), multiplication (*), and division (/). For details about operations supported by CSRTensor, see operators.

Warning

  • This is an experimental API that is subjected to change.

  • If the values given by indptr or indices are invalid, the results may be undefined. Invalid values include when the length of values or indices exceeds the range indicated by indptr, and when the columns indicated by indices are repeated on the same row.

Parameters:
  • indptr (Tensor) – 1-D Tensor of shape \((M)\), which equals to shape[0] + 1, which indicates the start and end point for values in each row. Default: None. If provided, must be int16, int32 or int64.

  • indices (Tensor) – 1-D Tensor of shape \((N)\), which has the same length as values. indices indicates the which column values should be placed. Default: None. If provided, must be int16, int32 or int64.

  • values (Tensor) – Tensor, which has the same length as indices (values.shape[0] == indices.shape[0]). values stores the data for CSRTensor. Default: None.

  • shape (tuple(int)) – A tuple indicates the shape of the CSRTensor, and shape[0] must equal to M - 1, which all equal to number of rows of the CSRTensor. Default: None.

  • csr_tensor (CSRTensor) – A CSRTensor object. Values’ feature dimension should match with CSRTensor’s feature dimension (values.shape[1:] == csr_tensor.shape[2:]). Default: None.

Outputs:

CSRTensor, with shape defined by shape, and dtype inferred from value.

Examples

>>> import mindspore as ms
>>> from mindspore import Tensor, CSRTensor
>>> # initialize a csr_tensor with indptr, indices, values and shape
>>> indptr = Tensor([0, 1, 2], dtype=ms.int32)
>>> indices = Tensor([0, 1], dtype=ms.int32)
>>> values = Tensor([1, 2], dtype=ms.float32)
>>> shape = (2, 4)
>>> csr_tensor = CSRTensor(indptr, indices, values, shape)
>>> # access a data member of CSRTensor
>>> print(indptr == csr_tensor.indptr)
[ True  True  True]
abs() → mindspore.common.sparse_tensor.CSRTensor[source]

Return absolute value element-wisely.

Returns:

CSRTensor, with all values being non-negative.

Supported Platforms:

Ascend GPU CPU

add(b: mindspore.common.sparse_tensor.CSRTensor, alpha: mindspore.common.tensor.Tensor, beta: mindspore.common.tensor.Tensor) → mindspore.common.sparse_tensor.CSRTensor[source]

Addition of two CSR Tensors : C = alpha * A + beta * B

Parameters:
  • b (CSRTensor) – Sparse CSR Tensor.

  • alpha (Tensor) – Dense Tensor, its shape must be able to broadcast to self.

  • beta (Tensor) – Dense Tensor, its shape must be able to broadcast to b.

Returns:

CSRTensor.

Supported Platforms:

GPU CPU

Examples

>>> from mindspore import Tensor, CSRTensor
>>> import mindspore.common.dtype as mstype
>>> indptr = Tensor([0, 1, 2], dtype=mstype.int32)
>>> indices = Tensor([0, 1], dtype=mstype.int32)
>>> values_a = Tensor([2, 1], dtype=mstype.float32)
>>> values_b = Tensor([1, 2], dtype=mstype.float32)
>>> dense_shape = (2, 4)
>>> alpha = Tensor(1, mstype.float32)
>>> beta = Tensor(1, mstype.float32)
>>> a = CSRTensor(indptr, indices, values_a, dense_shape)
>>> b = CSRTensor(indptr, indices, values_b, dense_shape)
>>> print(a.add(b, alpha, beta))
    CSRTensor(shape=[2,4], dtype=Float32,
              indptr=Tensor(shape=[3], dtype=Int32, value = [0, 1, 2]),
              indices=Tensor(shape=[2], dtype=Int32, value = [0, 1]),
              values=Tensor(shape=[2], dtype=Float32, value = [3.0, 3.0]))
astype(dtype: mstype) → CSRTensor[source]

Return a copy of the CSRTensor, cast its values to a specified type.

Parameters:

dtype (Union[mindspore.dtype, numpy.dtype, str]) – Designated tensor dtype.

Returns:

CSRTensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore as ms
>>> from mindspore import Tensor, CSRTensor
>>> indptr = Tensor([0, 1, 2], dtype=ms.int32)
>>> indices = Tensor([0, 1], dtype=ms.int32)
>>> values = Tensor([1, 2], dtype=ms.float32)
>>> shape = (2, 4)
>>> csr_tensor = CSRTensor(indptr, indices, values, shape)
>>> print(csr_tensor.astype(ms.float64).dtype)
Float64
property dtype

Return the dtype of the values of CSRTensor (mindspore.dtype).

property indices

Return CSRTensor’s column indices.

property indptr

Return CSRTensor’s row indices pointers.

property itemsize

Return the length of one tensor element in bytes.

mm(matrix: Union[mindspore.common.tensor.Tensor, mindspore.common.sparse_tensor.CSRTensor]) → Union[mindspore.common.tensor.Tensor, mindspore.common.sparse_tensor.CSRTensor][source]

Return the matrix multiplication result of the right-multiply matrix(dense or CSRTensor) of the CSRTensor. The CSRTensor with shape [M, N] needs to adapt the right matrix with shape [N, K] to get the dense matrix or CSRTensor with result [M, K].

Note

If right matrix is CSRTensor, currently only supports GPU backend. if right matrix is Tensor, currently supports CPU backend with LLVM 12.0.1 or GPU backend.

Parameters:

matrix (Tensor or CSRTensor) – A dense Tensor or CSRTensor, its shape[0] should be equal to csr_tensor.shape[1]

Returns:

Tensor or CSRTensor.

Supported Platforms:

GPU CPU

Examples

>>> from mindspore import Tensor, CSRTensor
>>> from mindspore import dtype as mstype
>>> indptr = Tensor([0, 1, 2], dtype=mstype.int32)
>>> indices = Tensor([0, 1], dtype=mstype.int32)
>>> values = Tensor([2, 1], dtype=mstype.float32)
>>> dense_shape = (2, 4)
>>> csr_tensor = CSRTensor(indptr, indices, values, dense_shape)
>>> dense_matrix = Tensor([[1., 2.], [1, 2.], [1, 2.], [1., 2.]], dtype=mstype.float32)
>>> print(csr_tensor.mm(dense_matrix))
[[2. 4.]
[1. 2.]]
mv(dense_vector: mindspore.common.tensor.Tensor) → mindspore.common.tensor.Tensor[source]

Return the matrix multiplication result of the right-multiply dense matrix of the CSRTensor. The CSRTensor with shape [M, N] needs to adapt the dense vector with shape [N, 1] to get the dense vector with result [M, 1].

Note

Currently only supports CPU backend with LLVM 12.0.1 installed.

Parameters:

dense_vector (Tensor) – A dense Tensor, its shape must be (csr_tensor.shape[1], 1)

Returns:

Tensor.

Supported Platforms:

GPU CPU

Examples

>>> from mindspore import Tensor, CSRTensor
>>> from mindspore import dtype as mstype
>>> indptr = Tensor([0, 1, 2], dtype=mstype.int32)
>>> indices = Tensor([0, 1], dtype=mstype.int32)
>>> values = Tensor([2, 1], dtype=mstype.float32)
>>> dense_shape = (2, 4)
>>> csr_tensor = CSRTensor(indptr, indices, values, dense_shape)
>>> dense = Tensor([[1], [1], [1], [1]], dtype=mstype.float32)
>>> print(csr_tensor.mv(dense))
[[2.]
[1.]]
property ndim

Return the number of tensor dimensions.

property shape

Return CSRTensor’s shape.

property size

Return the number of non-zero values.

sum(axis: int) → mindspore.common.tensor.Tensor[source]

Reduces a dimension of a CSRTensor by summing all elements in the dimension.

Note

Currently only supports CPU backend with LLVM 12.0.1 installed.

Parameters:

axis (int) – The dimensions to reduce.

Returns:

Tensor, the dtype is the same as CSRTensor.values.

Supported Platforms:

GPU CPU

Examples

>>> from mindspore import Tensor, CSRTensor
>>> from mindspore import dtype as mstype
>>> indptr = Tensor([0, 1, 2], dtype=mstype.int32)
>>> indices = Tensor([0, 1], dtype=mstype.int32)
>>> values = Tensor([2, 1], dtype=mstype.float32)
>>> dense_shape = (2, 4)
>>> csr_tensor = CSRTensor(indptr, indices, values, dense_shape)
>>> print(csr_tensor.sum(1))
[[2.]
[1.]]
to_coo() → mindspore.common.sparse_tensor.COOTensor[source]

Converts CSRTensor to COOTensor.

Note

Currently only supports CPU backend with LLVM 12.0.1 installed.

Returns:

COOTensor.

Supported Platforms:

GPU CPU

to_dense() → mindspore.common.tensor.Tensor[source]

Converts CSRTensor to Dense Tensor.

Returns:

Tensor.

Supported Platforms:

GPU

to_tuple() → Tuple[mindspore.common.tensor.Tensor, mindspore.common.tensor.Tensor, mindspore.common.tensor.Tensor, Tuple[int, ...]][source]

Return indptr, indices, values and shape as a tuple.

Returns:

Tuple.

Supported Platforms:

Ascend GPU CPU

property values

Return CSRTensor’s non-zero values.

tinyms.ms_function(fn=None, input_signature=None, hash_args=None, jit_config=None)[source]

Create a callable MindSpore graph from a Python function.

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

Note

ms_function will be deprecated and removed in a future version. Please use jit instead. If input_signature is specified, each input of fn must be a Tensor. And the input arguments for fn will not accept **kwargs.

Parameters:
  • fn (Function) – The Python function that will be run as a graph. 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.

  • hash_args (Union[Object, List or Tuple of Objects]) – The local free variables used inside fn, like functions or objects of class defined outside fn. Calling fn again with change of hash_args will trigger recompilation.

  • jit_config (JitConfig) – Jit config for compile. 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 ops
>>> 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)
...
... # Set hash_args as fn, otherwise cache of compiled `closure_fn` will not be reused.
... # While fn differs during calling again, recompilation will be triggered.
>>> def func(x):
...     return ops.exp(x)
...
>>> def closure_fn(x, fn):
...     @ms_function(hash_args=fn)
...     def inner_fn(a):
...         return fn(a)
...     return inner_fn(x)
...
>>> inputs = Tensor(np.ones([10, 10, 10]).astype(np.float32))
>>> for i in range(10):
...     closure_fn(inputs, func)
tinyms.ms_class(cls)[source]

Class decorator for user-defined classes.

This allows MindSpore to identify user-defined classes and thus obtain their attributes and methods.

Note

ms_class will be deprecated and removed in a future version. Please use jit_class instead.

Parameters:

cls (Class) – User-defined class.

Returns:

Class.

Raises:
  • TypeError – If ms_class is used for non-class types or nn.Cell.

  • AttributeError – If the private attributes or magic methods of the class decorated with ms_class is called.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.nn as nn
>>> from mindspore import ms_class
...
>>> @ms_class
... class UserDefinedNet:
...     def __init__(self):
...         self.value = 10
...
...     def func(self, x):
...         return 2 * x
...
>>> class Net(nn.Cell):
...     def __init__(self):
...         super(Net, self).__init__()
...         self.net = UserDefinedNet()
...
...     def construct(self, x):
...         out = self.net.value + self.net.func(x)
...         return out
...
>>> net = Net()
>>> out = net(5)
>>> print(out)
20
tinyms.jit(fn=None, input_signature=None, hash_args=None, jit_config=None)[source]

Create a callable MindSpore graph from a Python function.

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

Note

If input_signature is specified, each input of fn must be a Tensor. And the input arguments for fn will not accept **kwargs.

Parameters:
  • fn (Function) – The Python function that will be run as a graph. 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.

  • hash_args (Union[Object, List or Tuple of Objects]) – The local free variables used inside fn, like functions or objects of class defined outside fn. Calling fn again with change of hash_args will trigger recompilation.

  • jit_config (JitConfig) – Jit config for compile. 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 ops
>>> from mindspore import jit
...
>>> 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 decorator @jit
>>> def tensor_add(x, y):
...     z = x + y
...     return z
...
>>> tensor_add_graph = jit(fn=tensor_add)
>>> out = tensor_add_graph(x, y)
...
>>> # create a callable MindSpore graph through decorator @jit
>>> @jit
... 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 @jit with input_signature parameter
>>> @jit(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)
...
... # Set hash_args as fn, otherwise cache of compiled `closure_fn` will not be reused.
... # While fn differs during calling again, recompilation will be triggered.
>>> def func(x):
...     return ops.exp(x)
...
>>> def closure_fn(x, fn):
...     @jit(hash_args=fn)
...     def inner_fn(a):
...         return fn(a)
...     return inner_fn(x)
...
>>> inputs = Tensor(np.ones([10, 10, 10]).astype(np.float32))
>>> for i in range(10):
...     closure_fn(inputs, func)
tinyms.jit_class(cls)[source]

Class decorator for user-defined classes.

This allows MindSpore to identify user-defined classes and thus obtain their attributes and methods.

Parameters:

cls (Class) – User-defined class.

Returns:

Class.

Raises:
  • TypeError – If jit_class is used for non-class types or nn.Cell.

  • AttributeError – If the private attributes or magic methods of the class decorated with jit_class is called.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.nn as nn
>>> from mindspore import jit_class
...
>>> @jit_class
... class UserDefinedNet:
...     def __init__(self):
...         self.value = 10
...
...     def func(self, x):
...         return 2 * x
...
>>> class Net(nn.Cell):
...     def __init__(self):
...         super(Net, self).__init__()
...         self.net = UserDefinedNet()
...
...     def construct(self, x):
...         out = self.net.value + self.net.func(x)
...         return out
...
>>> net = Net()
>>> out = net(5)
>>> print(out)
20
class tinyms.Parameter(default_input, name=None, requires_grad=True, layerwise_parallel=False, parallel_optimizer=True)[source]

Parameter is a Tensor subclass, when they are assigned as Cell attributes they are automatically added to the list of its parameters, and will appear, e.g. in cell.get_parameters() iterator.

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. Give each Parameter a unique name to facilitate subsequent operations and updates. If there are two or more Parameter objects with the same name in a network, will be prompted to set a unique name when defining.

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

  • name (str) –

    Name of the parameter. Default: None.

    1) If the parameter is not given a name, the default name is its variable name. For example, the name of param_a below is name_a, and the name of param_b is the variable name param_b.

    self.param_a = Parameter(Tensor([1], ms.float32), name="name_a")
    self.param_b = Parameter(Tensor([2], ms.float32))
    

    2) If parameter in list or tuple is not given a name, will give it a unique name. For example, the names of parameters below are Parameter$1 and Parameter$2.

    self.param_list = [Parameter(Tensor([3], ms.float32)),
                       Parameter(Tensor([4], ms.float32))]
    

    3) If the parameter is given a name, and the same name exists between different parameters, an exception will be thrown. For example, “its name ‘name_a’ already exists.” will be thrown.

    self.param_a = Parameter(Tensor([1], ms.float32), name="name_a")
    self.param_tuple = (Parameter(Tensor([5], ms.float32), name="name_a"),
                        Parameter(Tensor([6], ms.float32)))
    

    4) If a parameter appear multiple times in list or tuple, check the name of the object only once. For example, the following example will not throw an exception.

    self.param_a = Parameter(Tensor([1], ms.float32), name="name_a")
    self.param_tuple = (self.param_a, self.param_a)
    

  • 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.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.]])
asnumpy_of_slice_persistent_data(self: mindspore._c_expression.Tensor, arg0: int, arg1: int) → array

Convert tensor to numpy.ndarray of a slice.

Returns:

numpy.ndarray.

Examples

>>> data = mindspore.Tensor(np.ones((2000000000, 256)))
>>> data.asnumpy_of_slice_persistent_data(0, 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 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. 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.

copy()[source]

Copy the parameter.

Returns:

Parameter, a new parameter.

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)
getitem_index_info(self: object, arg0: object, arg1: bool_) → object
init_data(layout=None, set_sliced=False)[source]

Initialize the parameter’s data.

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

    The parameter’s layout info. layout [dev_mat, tensor_map, slice_shape, filed_size, uniform_split, opt_shard_group]. Default: None. It’s not None only in ‘SEMI_AUTO_PARALLEL’ or ‘AUTO_PARALLEL’ mode.

    • dev_mat (list(int)): The parameter’s device matrix.

    • tensor_map (list(int)): The parameter’s tensor map.

    • slice_shape (list(int)): The parameter’s slice shape.

    • filed_size (int): The parameter’s filed size.

    • uniform_split (bool): Whether the parameter is split evenly.

    • opt_shard_group (str): The group of the parameter while running optimizer parallel.

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

Returns:

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

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 6.

  • TypeError – If layout is not tuple.

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.

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
is_persistent_data(self: mindspore._c_expression.Tensor) → bool

Check if tensor have persistent data.

Returns:

Bool.

Examples

>>> data = mindspore.Tensor(np.ones((2, 3)))
>>> data.is_persistent_data()
property key

Return the parameter unique key.

property layerwise_parallel

Get the layerwise parallel status(bool) of the parameter.

When layerwise_parallel is true in DATA_PARALLEL and HYBRID_PARALLEL parallel mode, broadcast and gradients communication would not be applied to parameters.

property name

Get the name of the parameter.

property parallel_optimizer

Get the optimizer parallel status(bool) of the parameter.

It is used to filter the weight shard operation in AUTO_PARALLEL and SEMI_AUTO_PARALLEL mode. It works only when enable parallel optimizer in mindspore.set_auto_parallel_context().

property parallel_optimizer_comm_recompute

Get the communication recompute status(bool) of optimizer parallel for the parameter.

In AUTO_PARALLEL and SEMI_AUTO_PARALLEL mode, when applying parallel optimizer, some mindspore.ops.AllGather operators used for parameters gathering are inserted automatically. It is used to control the recompute attr for those mindspore.ops.AllGather operators.

Note

  • Only Graph mode is supported.

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

persistent_data_from_numpy(self: array, arg0: int_) → mindspore._c_expression.Tensor

Creates a Tensor from a numpy.ndarray without copy. Use persistent data tensor.

Arg:

array (numpy.ndarray): The input ndarray. slice_num (int): The slice num of persistent data tensor.

Returns:

Tensor, tensor with shared data to input ndarray.

Examples

>>> a = np.ones((2, 3))
>>> t = mindspore.Tensor.persistent_data_from_numpy(a, 1)
property requires_grad

Return whether the parameter requires gradient.

set_cast_dtype(self: mindspore._c_expression.Tensor, dtype: mindspore._c_expression.typing.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._c_expression.typing.Type) → mindspore._c_expression.typing.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. It is supported only in graph mode.

Parameters:

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

setitem_index_info(self: object, arg0: object, arg1: object, arg2: bool_) → object
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.

value()[source]

Return the value of parameter object.

Examples

>>> from mindspore import Tensor, Parameter
>>> import numpy as np
>>> x = Parameter(Tensor(np.array([1, 2], dtype=np.float32)), name="param")
>>> x_value = x.value()
>>> print(x_value)
[1.  2.]
class tinyms.ParameterTuple[source]

Inherited from tuple, ParameterTuple is used to save multiple parameter.

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, the prefix string will be added to the names of parameters in parametertuple.

  • init (Union[Tensor, str, numbers.Number]) –

    Clone the shape and dtype of Parameters in ParameterTuple and set data according to init. Default: ‘same’.

    • If init is a Tensor , set the new Parameter data to the input Tensor.

    • If init is numbers.Number , set the new Parameter data to the input number.

    • If init is a str, data will be set according to the initialization method of the same name in the Initializer.

    • If init is ‘same’, the new Parameter has the same value with the original Parameter.

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.function.random_func 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.function.random_func 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.

In semi_auto_parallel/auto_parallel mode, when using set_seed, weights with same shape and same sharding strategy in the same device would be initialized to the same result, otherwise, they would be initialized to the different result.

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
>>> import mindspore as ms
>>> # 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.function.random_func 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.function.random_func 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.function.random_func 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.function.random_func 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 different 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.function.random_func 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.set_dump(target, enabled=True)[source]

Enable or disable dump for the target and its contents.

target should be an instance of mindspore.nn.Cell or mindspore.ops.Primitive . Please note that this API takes effect only when Asynchronous Dump is enabled and the dump_mode field in dump config file is “2”. See the dump document for details. The default enabled status for a mindspore.nn.Cell or mindspore.ops.Primitive is False.

Warning

This is an experimental API that is subject to change or deletion.

Note

  1. This API is only effective for GRAPH_MODE with Ascend backend.

  2. This API only supports being called before training starts. If you call this API during training, it may not be effective.

  3. After using set_dump(Cell, True) , operators in forward and backward computation (computation generated by the grad operations) of the cell will be dumped.

  4. For mindspore.nn.SoftmaxCrossEntropyWithLogits layer, the forward computation and backward computation use the same set of operators. So you can only see dump data from backward computation. Please note that mindspore.nn.SoftmaxCrossEntropyWithLogits layer will also use the above operators internally when initialized with sparse=True and reduction=”mean” .

Parameters:
  • target (Union[Cell, Primitive]) – The Cell instance or Primitive instance to which the dump flag is set.

  • enabled (bool, optional) – True means enable dump, False means disable dump. Default: True.

Supported Platforms:

Ascend

Examples

>>> # Please set the dump config file and environment variable before
>>> # running this example to actually get the dump data.
>>> # See the document of this API for details.
>>> import numpy as np
>>> import mindspore as ms
>>> import mindspore.nn as nn
>>> from mindspore import Tensor, set_dump
>>>
>>> ms.set_context(device_target="Ascend", mode=ms.GRAPH_MODE)
>>>
>>> class MyNet(nn.Cell):
...     def __init__(self):
...         super().__init__()
...         self.conv1 = nn.Conv2d(5, 6, 5, pad_mode='valid')
...         self.relu1 = nn.ReLU()
...
...     def construct(self, x):
...         x = self.conv1(x)
...         x = self.relu1(x)
...         return x
>>>
>>> if __name__ == "__main__":
...     net = MyNet()
...     set_dump(net.conv1)
...     input_tensor = Tensor(np.ones([1, 5, 10, 10], dtype=np.float32))
...     output = net(input_tensor)
tinyms.ms_memory_recycle()[source]

Recycle memory used by MindSpore. When train multi Neural network models in one process, memory used by MindSpore is very large, this is because MindSpore cached runtime memory for every model. To recycle these cached memory, users can call this function after training of one model.

tinyms.mutable(input_data, dynamic_len=False)[source]

Make a constant value mutable.

Currently, all the inputs of Cell except Tensor such as scalar, tuple, list and dict, are regarded as constant values. The constant values are non-differentiable and used to do constant folding in the optimization process.

Besides, currently when the network input is tuple[Tensor], list[Tensor] or dict[Tensor], even without changing the shape and dtype of the Tensors, the network will be re-compiled when calling this network repeatedly because the these inputs are regarded as constant values.

To solve the above problems, we provide api mutable to make the constant inputs of Cell ‘mutable’. A ‘mutable’ input means that it is changed to be a variable input just like Tensor and the most important thing is that it will be differentiable.

When the input_data is tuple or list and dynamic_len is False, mutable will return a constant length tuple or list with all mutable elements. If dynamic_len is True, the length of the return tuple or list will be dynamic.

If a dynamic length tuple or list is used as the input of the network and the network is repeatedly called, and the length of the tuple or list is different for each run, it does not need to be re-compiled.

Parameters:
  • input_data (Union[int, float, Tensor, tuple, list, dict]) – The input data to be made mutable. If ‘input_data’ is list/tuple/dict, the type of each element should also in the valid types.

  • dynamic_len (bool) – Whether to set the whole sequence to be dynamic length. In graph compilation, if dynamic_len is True, the input_data must be list or tuple and the elements of input_data must have the same type and shape. Default: False.

Warning

This is an experimental API that is subject to change or deletion.

Note

Currently this api only works in GRAPH mode.

Returns:

The origin input data which has been set mutable.

Raises:
  • TypeError – If input_data is not one of int, float, Tensor, tuple, list, dict or their nested structure.

  • TypeError – If dynamic_len is True and input_data is not tuple or list.

  • ValueError – If dynamic_len is True, input_data is tuple or list but the elements within input_data do not have the same shape and type.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.nn as nn
>>> import mindspore.ops as ops
>>> from mindspore.common import mutable
>>> from mindspore.common import dtype as mstype
>>> from mindspore import Tensor
>>> from mindspore import context
>>> context.set_context(mode=context.GRAPH_MODE)
>>> class Net(nn.Cell):
...     def __init__(self):
...         super(Net, self).__init__()
...         self.matmul = ops.MatMul()
...
...     def construct(self, z):
...         x = z[0]
...         y = z[1]
...         out = self.matmul(x, y)
...         return out
...
>>> class GradNetWrtX(nn.Cell):
...     def __init__(self, net):
...         super(GradNetWrtX, self).__init__()
...         self.net = net
...         self.grad_op = ops.GradOperation()
...
...     def construct(self, z):
...         gradient_function = self.grad_op(self.net)
...         return gradient_function(z)
...
>>> z = mutable((Tensor([[0.5, 0.6, 0.4], [1.2, 1.3, 1.1]], dtype=mstype.float32),
...              Tensor([[0.01, 0.3, 1.1], [0.1, 0.2, 1.3], [2.1, 1.2, 3.3]], dtype=mstype.float32)))
>>> output = GradNetWrtX(Net())(z)
>>> print(output)
(Tensor(shape=[2, 3], dtype=Float32, value=
[[ 1.41000009e+00,  1.60000002e+00,  6.59999943e+00],
 [ 1.41000009e+00,  1.60000002e+00,  6.59999943e+00]]), Tensor(shape=[3, 3], dtype=Float32, value=
[[ 1.70000005e+00,  1.70000005e+00,  1.70000005e+00],
 [ 1.89999998e+00,  1.89999998e+00,  1.89999998e+00],
 [ 1.50000000e+00,  1.50000000e+00,  1.50000000e+00]]))
class tinyms.JitConfig(jit_level='O1', exc_mode='auto', **kwargs)[source]

Jit config for compile.

Warning

This is an experimental API that is subject to change or deletion.

Parameters:
  • jit_level (str) –

    Option for argument level for Optimization of lift graph. Supports [“O0”, “O1”, “O2”, “O3”]. Default: “O1”.

    • ”O0”: Basic optimization.

    • ”O1”: Manual optimization.

    • ”O2”: Manual optimization and graph computation fusion.

    • ”O3”: Performance optimization, no generalization guaranteed.

  • exc_mode (str) –

    Mode for execute the network. Supports [“auto”, “sink”, “no_sink”]. Default: “auto”.

    • ”auto”: Automatic Policies.

    • ”sink”: Build computational graphs with the sink mode.

    • ”no_sink”: Build computational graphs with no sink mode.

  • **kwargs (dict) – A dictionary of keyword arguments that the class needs.

Examples

>>> from mindspore import JitConfig
>>>
>>> jitconfig = JitConfig(jit_level="O1")
>>> net = LeNet5()
>>>
>>> net.set_jit_config(jitconfig)
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]
tinyms.arccos(input, dtype=None)[source]

Trigonometric inverse cosine, element-wise.

Note

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

Parameters:
  • input (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
>>> input = np.asarray([1, -1], np.float32)
>>> output = np.arccos(input)
>>> 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.array([1., 2., 3., 4.], dtype=np.float32)
>>> print(np.arcsinh(x))
[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 GPU CPU

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. Default: None.

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. Default: None.

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]`and :math:`x[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 CPU

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 CPU

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 CPU

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 CPU

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. Default: 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. Default: True.

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

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. Default: None.

  • 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. Default: False.

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. Default is None.

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. Defaults to None.

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. Default: None.

  • 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. Default: None.

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. Default: 1.

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

  • 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. Default: None.

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]`and :math:`x[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)
[[0. 0. 0.]
 [0. 0. 0.]]
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)
[[[0. 0.]]
 [[0. 0.]]
 [[0. 0.]]
 [[0. 0.]]]
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. Default 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 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.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.

  • 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.

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

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]`and :math:`x[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 triangle(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. Default: False.

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. For more information, refer to the wiki page. 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.

  • kwargs (anytype, optional) – Any keyword arguments that will be used only in <function> mode.

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.rand(*shape, dtype=mindspore.float32)[source]

Returns a new Tensor with given shape and dtype, filled with random numbers from the uniform distribution on the interval \([0, 1)\).

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

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype, it must be float type. Default is mindspore.float32.

Returns:

Tensor, with the designated shape and dtype, filled with random numbers from the uniform distribution on the interval \([0, 1)\).

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

  • ValueError – If dtype is not float type.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> from mindspore import set_seed
>>> set_seed(1)
>>> print(np.rand((2,3)))
[[4.1702199e-01 9.9718481e-01 7.2032452e-01]
[9.3255734e-01 1.1438108e-04 1.2812445e-01]]
tinyms.randint(minval, maxval=None, shape=None, dtype=mindspore.int32)[source]

Return random integers from minval (inclusive) to maxval (exclusive). Return random integers from the discrete uniform distribution of the specified dtype in the “half-open” interval \([minval, maxval)\). If maxval is None (the default), the value range will be \([0, minval)\), in this case, minval must be greater than 0.

Parameters:
  • minval (Union[int]) – Start value of interval. The interval includes this value. When maxval is None, minval must be greater than 0. When maxval is not None, minval must be less than maxval.

  • maxval (Union[int], optional) – End value of interval. The interval does not include this value.

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

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype, it must be int type. Default is mindspore.int32.

Returns:

Tensor, with the designated shape and dtype, filled with random integers from minval (inclusive) to maxval (exclusive).

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

  • ValueError – If input arguments have values not specified above.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> from mindspore import set_seed
>>> set_seed(1)
>>> print(np.randint(1, 10, (2,3)))
[[4 9 7]
[9 1 2]]
tinyms.randn(*shape, dtype=mindspore.float32)[source]

Returns a new Tensor with given shape and dtype, filled with a sample (or samples) from the standard normal distribution.

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

  • dtype (Union[mindspore.dtype, str], optional) – Designated tensor dtype, it must be float type. Default is mindspore.float32.

Returns:

Tensor, with the designated shape and dtype, filled with a sample (or samples) from the “standard normal” distribution.

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

  • ValueError – If dtype is not float type.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> from mindspore import set_seed
>>> set_seed(1)
>>> print(np.randn((2,3)))
[[ 0.30639967 -0.42438635 -0.20454668]
[-0.4287376   1.3054721   0.64747655]]
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. Defaults to None.

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. Default: None.

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]`and :math:`x[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 tuple 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. Defaults to None.

  • mode ('raise', 'wrap', 'clip', optional) –

    Specifies how out-of-bounds indices will behave. Defaults to “clip”.

    ’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
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 equal 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 dividend.

  • 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, return the unique tensor, otherwise return tuple of tensors.

Supported Platforms:

Ascend GPU CPU

Raises:

TypeError – If x is not tensor.

Examples

>>> import mindspore.numpy as np
>>> import mindspore as ms
>>> ms.set_context(mode=ms.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. Defaults to “C”.

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]`and :math:`x[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.]]]