tinyms

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

实际案例

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

Convert MindSpore dtype to numpy data type.

参数

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

返回

The data type of numpy.

tinyms.issubclass_(type_, dtype)[源代码]

Determine whether type_ is a subclass of dtype.

参数
  • type_ (mindspore.dtype) – Target MindSpore dtype.

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

返回

bool, True or False.

tinyms.dtype_to_pytype(type_)[源代码]

Convert MindSpore dtype to python data type.

参数

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

返回

Type of python.

tinyms.pytype_to_dtype(obj)[源代码]

Convert python type to MindSpore type.

参数

obj (type) – A python type object.

返回

Type of MindSpore type.

tinyms.get_py_obj_dtype(obj)[源代码]

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

参数

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

返回

Type of MindSpore type.

class tinyms.Tensor(input_data=None, dtype=None, shape=None, init=None)[源代码]

Tensor is used for data storage.

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

参数
  • input_data (Tensor, float, int, bool, tuple, list, numpy.ndarray) – Input data of the tensor.

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

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

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

Outputs:

Tensor, with the same shape as input_data.

实际案例

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

Return the transposed tensor.

abs()[源代码]

Return absolute value element-wisely.

返回

Tensor, has the same data type as x.

all(axis=(), keep_dims=False)[源代码]

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

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

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

返回

Tensor, has the same data type as x.

any(axis=(), keep_dims=False)[源代码]

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

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

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

返回

Tensor, has the same data type as x.

asnumpy()[源代码]

Convert tensor to numpy array.

assign_value(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.

实际案例

>>> 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)[源代码]

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

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

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

返回

Tensor, with the designated dtype.

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

Get tensor’s data dimension.

返回

int, the dimension of tensor.

实际案例

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

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

expand_as(x)[源代码]

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

参数

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

返回

Tensor, has the same dimension as input tensor.

flatten(order='C')[源代码]

Return a copy of the tensor collapsed into one dimension.

参数

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

返回

Tensor, has the same data type as input.

flush_from_cache()[源代码]

Flush cache data to host if tensor is cache enable.

static from_numpy(array)[源代码]

Convert numpy array to Tensor without copy data.

property has_init

tensor is inited.

init_data(slice_index=None, shape=None, opt_shard_group=None)[源代码]

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

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

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

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

is_init(self: mindspore._c_expression.Tensor) → bool

Get tensor init_flag.

返回

bool, whether the tensor init.

实际案例

>>> data = mindspore.Tensor(np.ones((2, 3)))
>>> data.is_init()
False
property itemsize

Return the length of one tensor element in bytes.

mean(axis=(), keep_dims=False)[源代码]

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

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

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

返回

Tensor, has the same data type as x.

property nbytes

Return the total number of bytes taken by the tensor.

property ndim

Return the number of tensor dimensions.

ravel()[源代码]

Return a contiguous flattened tensor.

返回

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

reshape(*shape)[源代码]

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

参数

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

返回

Tensor, with new specified shape.

set_cast_dtype(self: mindspore._c_expression.Tensor, dtype: mindspore::Type = None) → None
set_dtype(self: mindspore._c_expression.Tensor, arg0: mindspore::Type) → mindspore::Type

Set the tensor’s data type.

Arg:

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

实际案例

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

实际案例

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

Returns the shape of the tensor as a tuple.

property size

Returns the total number of elements in tensor.

squeeze(axis=None)[源代码]

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

参数

axis (Union[None, int, list(int), tuple(int)], optional) – Default is None.

返回

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

property strides

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

swapaxes(axis1, axis2)[源代码]

Interchange two axes of a tensor.

参数
  • axis1 (int) – First axis.

  • axis2 (int) – Second axis.

返回

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

to_tensor(slice_index=None, shape=None, opt_shard_group=None)[源代码]

Return init_data().

transpose(*axes)[源代码]

Return a view of the tensor with axes transposed.

For a 1-D tensor this has no effect, as a transposed vector is simply the same vector. For a 2-D tensor, this is a standard matrix transpose. For a n-D tensor, if axes are given, their order indicates how the axes are permuted. If axes are not provided and tensor.shape = (i[0], i[1],…i[n-2], i[n-1]), then tensor.transpose().shape = (i[n-1], i[n-2], … i[1], i[0]).

参数

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

返回

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

view(*shape)[源代码]

Reshape the tensor according to the input shape.

参数

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

返回

Tensor, has the same dimension as the input shape.

property virtual_flag

Mark tensor is virtual.

class tinyms.RowTensor(indices, values, dense_shape)[源代码]

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

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

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

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

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

It is not supported in pynative mode at the moment.

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

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

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

返回

RowTensor, composed of indices, values, and dense_shape.

实际案例

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

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

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

Pynative mode not supported at the moment.

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

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

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

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

返回

SparseTensor, composed of indices, values, and dense_shape.

实际案例

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

Create a callable MindSpore graph from a python function.

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

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

  • obj (Object) – The Python Object that provides the information for identifying the compiled function.Default: None.

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

返回

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.

实际案例

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

Parameter types of cell models.

After initialized Parameter is a subtype of Tensor.

In auto_parallel mode of “semi_auto_parallel” and “auto_parallel”, if init Parameter by an 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.

注解

Each parameter of Cell is represented by Parameter class. A Parameter has to belong to a Cell. If there is an operator in the network that requires part of the inputs to be Parameter, then the Parameters as this part of the inputs are not allowed to be cast. It is recommended to use the default value of name when initialize a parameter as one attribute of a cell, otherwise, the parameter name may be different than expected.

参数
  • default_input (Union[Tensor, int, float, numpy.ndarray, list]) – Parameter data, to be set initialized.

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

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

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

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

实际案例

>>> from mindspore import Parameter, Tensor
>>> from mindspore.common import initializer as init
>>> from mindspore.ops import operations as P
>>> from mindspore.nn import Cell
>>> import mindspore
>>> import numpy as np
>>> from mindspore import context
>>>
>>> class Net(Cell):
...     def __init__(self):
...         super(Net, self).__init__()
...         self.matmul = P.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.

返回

numpy.ndarray.

实际案例

>>> data = mindspore.Tensor(np.ones((2, 3)))
>>> array = data.asnumpy()
>>> array
array([[1., 1., 1.],
       [1., 1., 1.]])
assign_value(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.

实际案例

>>> 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')[源代码]

Clone the parameter.

参数

init (Union[Tensor, str, numbers.Number]) – Initialize the shape of the parameter. Default: ‘same’.

返回

Parameter, a new parameter.

property comm_fusion

Get the fusion type for communication operators corresponding to this parameter.

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

Get tensor’s data dimension.

返回

int, the dimension of tensor.

实际案例

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

返回

Tensor, tensor with shared data to input ndarray.

实际案例

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

Initialize the parameter data.

参数
  • layout (Union[None, list(list(int))]) –

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

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

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

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

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

引发

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

返回

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

property inited_param

Get the new parameter after call the init_data.

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

property is_init

Get the initialization status of the parameter.

In GE backend, the Parameter need a “init graph” to sync the data from host to device. This flag indicates whether the data as been sync to the device.

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

property name

Get the name of the parameter.

property parallel_optimizer

Return whether the parameter requires weight shard for parallel optimizer.

property requires_grad

Return whether the parameter requires gradient.

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

Set set_data of current Parameter.

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

返回

Parameter, the parameter after set data.

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

Set the tensor’s data type.

Arg:

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

实际案例

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

实际案例

>>> data = mindspore.Tensor(np.ones((2, 3)))
>>> data.set_init_flag(True)
set_param_ps(init_in_server=False)[源代码]

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

注解

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

参数

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

property shape

Get the MetaTensor’s shape.

property sliced

Get slice status of the parameter.

property unique

whether the parameter is already unique or not.

class tinyms.ParameterTuple[源代码]

Class for storing tuple of parameters.

注解

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

clone(prefix, init='same')[源代码]

Clone the parameter.

参数
  • prefix (str) – Namespace of parameter.

  • init (str) – Initialize the shape of the parameter. Default: ‘same’.

返回

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)[源代码]

Set global random seed.

注解

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

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

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

参数

seed (int) – The seed to be set.

引发

实际案例

>>> from mindspore.ops import composite as C
>>> from mindspore import Tensor
>>>
>>> # 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 C.uniform operator, minval and maxval are initialised as:
>>> minval = Tensor(1.0, ms.float32)
>>> maxval = Tensor(2.0, ms.float32)
>>>
>>> # 1. If global seed is not set, numpy.random and initializer will choose a random seed:
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A1
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A2
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W1
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W2
>>> # Rerun the program will get different results:
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A3
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A4
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W3
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W4
>>>
>>> # 2. If global seed is set, numpy.random and initializer will use it:
>>> set_seed(1234)
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A1
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A2
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W1
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W2
>>> # Rerun the program will get the same results:
>>> set_seed(1234)
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A1
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A2
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W1
>>> w1 = Parameter(initializer("uniform", [2, 2], ms.float32), name="w1") # W2
>>>
>>> # 3. If neither global seed nor op seed is set, mindspore.ops.composite.random_ops and
>>> # mindspore.nn.probability.distribution will choose a random seed:
>>> c1 = C.uniform((1, 4), minval, maxval) # C1
>>> c2 = C.uniform((1, 4), minval, maxval) # C2
>>> # Rerun the program will get different results:
>>> c1 = C.uniform((1, 4), minval, maxval) # C3
>>> c2 = C.uniform((1, 4), minval, maxval) # C4
>>>
>>> # 4. If global seed is set, but op seed is not set, mindspore.ops.composite.random_ops and
>>> # mindspore.nn.probability.distribution will calculate a seed according to global seed and
>>> # default op seed. Each call will change the default op seed, thus each call get different
>>> # results.
>>> set_seed(1234)
>>> c1 = C.uniform((1, 4), minval, maxval) # C1
>>> c2 = C.uniform((1, 4), minval, maxval) # C2
>>> # Rerun the program will get the same results:
>>> set_seed(1234)
>>> c1 = C.uniform((1, 4), minval, maxval) # C1
>>> c2 = C.uniform((1, 4), minval, maxval) # C2
>>>
>>> # 5. If both global seed and op seed are set, mindspore.ops.composite.random_ops and
>>> # mindspore.nn.probability.distribution will calculate a seed according to global seed and
>>> # op seed counter. Each call will change the op seed counter, thus each call get different
>>> # results.
>>> set_seed(1234)
>>> c1 = C.uniform((1, 4), minval, maxval, seed=2) # C1
>>> c2 = C.uniform((1, 4), minval, maxval, seed=2) # C2
>>> # Rerun the program will get the same results:
>>> set_seed(1234)
>>> c1 = C.uniform((1, 4), minval, maxval, seed=2) # C1
>>> c2 = C.uniform((1, 4), minval, maxval, seed=2) # C2
>>>
>>> # 6. If op seed is set but global seed is not set, 0 will be used as global seed. Then
>>> # mindspore.ops.composite.random_ops and mindspore.nn.probability.distribution act as in
>>> # condition 5.
>>> c1 = C.uniform((1, 4), minval, maxval, seed=2) # C1
>>> c2 = C.uniform((1, 4), minval, maxval, seed=2) # C2
>>> # Rerun the program will get the same results:
>>> c1 = C.uniform((1, 4), minval, maxval, seed=2) # C1
>>> c2 = C.uniform((1, 4), minval, maxval, seed=2) # C2
>>>
>>> # 7. Recall set_seed() in the program will reset numpy seed and op seed counter of
>>> # mindspore.ops.composite.random_ops and mindspore.nn.probability.distribution.
>>> set_seed(1234)
>>> np_1 = np.random.normal(0, 1, [1]).astype(np.float32) # A1
>>> c1 = C.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 = C.uniform((1, 4), minval, maxval, seed=2) # still get C1
tinyms.get_seed()[源代码]

Get global random seed.

tinyms.abs(x, dtype=None)

Calculates the absolute value element-wise.

注解

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.

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

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

返回

Tensor.

引发

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Calculates the absolute value element-wise.

注解

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.

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

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

返回

Tensor.

引发

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Adds arguments element-wise.

注解

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

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

返回

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

实际案例

>>> 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)[源代码]

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

注解

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

参数
  • a (Tensor) – Input data.

  • axis (None or int or tuple of ints, optional) – defaults to None. 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.

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

返回

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.

引发

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

注解

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

参数
  • a (Tensor) – Input data.

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

  • 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) – The maximum 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.

返回

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.

引发

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Appends values to the end of a tensor.

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

返回

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

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

  • ValueError – If specified axis exceeds arr.ndim.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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.arange(start, stop=None, step=None, dtype=None)[源代码]

Returns evenly spaced values within a given interval.

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

返回

Tensor with evenly spaced values.

引发

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

Supported Platforms:

Ascend GPU CPU

实际案例

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

Trigonometric inverse cosine, element-wise.

注解

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

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

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

返回

Tensor.

引发

TypeError – If the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

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

Inverse hyperbolic cosine, element-wise.

注解

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

参数
  • x (Tensor) – Input tensor.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Inverse sine, element-wise.

注解

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

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

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

返回

Tensor.

引发

TypeError – If the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Inverse hyperbolic sine element-wise.

注解

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

参数
  • x (Tensor) – Input tensor.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

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

Trigonometric inverse tangent, element-wise.

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

注解

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

参数
  • x (Tensor) – Input tensor.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> import mindspore.numpy as np
>>> x = np.arange(5).astype('float32')
>>> print(np.tan(x))
[ 0.          1.5574077  -2.1850398  -0.14254655  1.1578213 ]
tinyms.arctan2(x1, x2, dtype=None)[源代码]

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

注解

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

参数
  • x1 (Tensor) – input tensor.

  • x2 (Tensor) – input tensor.

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

返回

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

Supported Platforms:

Ascend CPU

实际案例

>>> 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)[源代码]

Inverse hyperbolic tangent element-wise.

注解

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

参数
  • x (Tensor) – Input tensor.

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

返回

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

Supported Platforms:

Ascend CPU

实际案例

>>> 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.array(obj, dtype=None, copy=True, ndmin=0)[源代码]

Creates a tensor.

This function creates tensors from an array-like object.

参数
  • 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

返回

Tensor, generated tensor with the specified dtype.

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

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> import mindspore.numpy as np
>>> print(np.array([1,2,3]))
[1 2 3]
tinyms.array_split(x, indices_or_sections, axis=0)[源代码]

Splits a tensor into multiple sub-tensors.

注解

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\).

参数
  • x (Tensor) – A Tensor to be divided.

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

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

返回

A list of sub-tensors.

引发
  • 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

实际案例

>>> 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.asarray(a, dtype=None)[源代码]

Converts the input to tensor.

This function converts tensors from an array-like object.

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

返回

Tensor, generated tensor with the specified dtype.

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

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

Supported Platforms:

Ascend GPU CPU

实际案例

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

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

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

参数

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.

返回

Tensor, generated tensor with the specified float dtype.

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

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

Supported Platforms:

Ascend GPU CPU

实际案例

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

Converts inputs to arrays with at least one dimension.

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

注解

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

参数

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

返回

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

引发

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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+000, 1.00000000e+000, 1.00000000e+000],
    [1.00000000e+000, 1.00000000e+000, 1.00000000e+000]]),
    Tensor(shape=[1], dtype=Float32, value= [1.00000000e+000]),
    Tensor(shape=[5], dtype=Float32,
    value= [1.00000000e+000, 1.00000000e+000, 1.00000000e+000,
    1.00000000e+000, 1.00000000e+000])]
tinyms.atleast_2d(*arys)[源代码]

Reshapes inputs as arrays with at least two dimensions.

注解

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

参数

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

返回

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

引发

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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+000, 1.00000000e+000, 1.00000000e+000],
    [1.00000000e+000, 1.00000000e+000, 1.00000000e+000]]),
    Tensor(shape=[1, 1], dtype=Float32, value= [[1.00000000e+000]]),
    Tensor(shape=[1, 5], dtype=Float32,
    value= [[1.00000000e+000, 1.00000000e+000, 1.00000000e+000,
    1.00000000e+000, 1.00000000e+000]])]
tinyms.atleast_3d(*arys)[源代码]

Reshapes inputs as arrays with at least three dimensions.

注解

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

参数

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

返回

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

引发

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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+000], [1.00000000e+000], [1.00000000e+000]],
    [[1.00000000e+000], [1.00000000e+000], [1.00000000e+000]]]),
    Tensor(shape=[1, 1, 1], dtype=Float32, value= [[[1.00000000e+000]]]),
    Tensor(shape=[1, 5, 1], dtype=Float32,
    value= [[[1.00000000e+000], [1.00000000e+000], [1.00000000e+000],
    [1.00000000e+000], [1.00000000e+000]]])]
tinyms.average(x, axis=None, weights=None, returned=False)[源代码]

Computes the weighted average along the specified axis.

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

返回

Averaged Tensor. If returned is True, return tuple.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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.broadcast_arrays(*args)[源代码]

Broadcasts any number of arrays against each other.

注解

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

参数

*args (Tensor) – The arrays to broadcast.

返回

List of Tensor.

引发

ValueError – if arrays cannot be broadcast.

Supported Platforms:

Ascend GPU CPU

示例

>>> 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)[源代码]

Broadcasts an array to a new shape.

参数
  • array (Tensor) – The array to broadcast.

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

返回

Tensor, original array broadcast to the given shape.

引发

ValueError – if array cannot be broadcast to shape.

Supported Platforms:

Ascend GPU CPU

示例

>>> 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)[源代码]

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

注解

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

参数
  • x (Tensor) – Input tensor.

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

返回

Tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Returns the ceiling of the input, element-wise.

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

注解

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

参数
  • x (Tensor) – input values.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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.clip(x, xmin, xmax, dtype=None)[源代码]

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.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

参数

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.

返回

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

Supported Platforms:

Ascend GPU CPU

引发

实际案例

>>> 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)[源代码]

Joins a sequence of tensors along an existing axis.

注解

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

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

返回

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

引发
  • 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

实际案例

>>> 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')[源代码]

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

注解

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

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

返回

Tensor, discrete, linear convolution of a and v.

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

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

Supported Platforms:

GPU

实际案例

>>> import mindspore.numpy as np
>>> output = np.convolve([1., 2., 3., 4., 5.], [2., 3.], mode="valid")
>>> print(output)
[ 3.  6.  9. 12.]
tinyms.cos(x, dtype=None)[源代码]

Cosine element-wise.

注解

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

参数
  • x (Tensor) – Input tensor.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Hyperbolic cosine, element-wise.

注解

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

参数
  • x (Tensor) – Input tensor.

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

返回

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

Supported Platforms:

Ascend CPU

实际案例

>>> 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)[源代码]

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

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

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

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

返回

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.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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\).

注解

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.

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

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

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

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

返回

Tensor, the covariance matrix of the variables.

引发
  • 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

实际案例

>>> 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)[源代码]

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.

参数
  • a (Union[int, float, bool, list, tuple, Tensor]) – Components of the first vector(s).

  • b (Union[int, float, bool, 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.

返回

Tensor, vector cross product(s).

引发

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)
[[-3  3]
[ 6 -6]
[-3  3]]
tinyms.cumsum(a, axis=None, dtype=None)[源代码]

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

注解

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

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

返回

Tensor.

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

  • ValueError – If axis is out of range.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Converts angles from degrees to radians.

参数
  • x (Tensor) – Angles in degrees.

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

返回

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

引发

TypeError – if x is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Extracts a diagonal or construct a diagonal array.

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

返回

Tensor, the extracted diagonal or constructed diagonal array.

引发

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

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

返回

Tuple of Tensor.

引发

TypeError – if input are not integers.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

注解

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

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

返回

Tensor, The 2-D output array.

引发

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

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

返回

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.

引发

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> import mindspore.numpy as np
>>> a = np.arange(4).reshape(2,2)
>>> 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)
>>> 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)[源代码]

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.

参数
  • a (Tensor) – Input tensor.

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

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

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

返回

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.

引发
Supported Platforms:

Ascend GPU CPU

实际案例

>>> import mindspore.numpy as np
>>> arr = np.array([1, 3, -1, 0, 4])
>>> print(np.diff(arr, n=2))
[-6  5  3]
tinyms.divide(x1, x2, dtype=None)[源代码]

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

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

注解

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

参数
  • x1 (Tensor) – the divident.

  • x2 (Tensor) – the divisor.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

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

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

返回

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

引发

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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])

注解

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.

参数
返回

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

引发

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

实际案例

>>> 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)[源代码]

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.

参数
  • x (Tensor) – A Tensor to be divided.

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

返回

A list of sub-tensors.

引发

TypeError – If argument indices_or_sections is not integer.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

参数

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.

返回

Stacked Tensor, formed by stacking the given tensors.

Supported Platforms:

Ascend GPU CPU

引发

实际案例

>>> 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)[源代码]

The differences between consecutive elements of a tensor.

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

返回

The differences.

引发

TypeError – If inputs have types not specified above.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

注解

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

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

返回

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

引发

TypeError – if the input shape or dtype is invalid.

Supported Platforms:

Ascend GPU CPU

实际案例

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

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

注解

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

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

返回

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

引发

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

Supported Platforms:

Ascend GPU CPU

实际案例

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

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

注解

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

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

返回

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

实际案例

>>> 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)[源代码]

Calculates the exponential of all elements in the input array.

注解

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.

参数
  • x (Tensor) – input data.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

注解

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

参数
  • x (Tensor) – input values.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Expands the shape of a tensor.

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

参数
  • a (Tensor) – Input tensor array.

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

返回

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

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

  • ValueError – If axis exceeds a.ndim.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

注解

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.

参数
  • x (Tensor) – input data.

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

返回

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

实际案例

>>> 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)[源代码]

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

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

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

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

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

返回

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.

引发

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

实际案例

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

注解

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.

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

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

返回

Tensor.

引发

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

注解

Numpy argument out is not supported.

参数

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

返回

Tensor.

引发

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

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

注解

On CPU, the supported dtypes are np.float16, np.float32, and np.float64.

参数
  • m (Tensor) – Input array.

  • axis (None or int or tuple of ints, 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 ints, flipping is performed on all of the axes specified in the tuple.

返回

Tensor, with the entries of axis reversed.

引发

TypeError – if the input is not a tensor.

Supported Platforms:

GPU

示例

>>> 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)[源代码]

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

注解

On CPU, the supported dtypes are np.float16, np.float32, and np.float64.

参数

m (Tensor) – Input array.

返回

Tensor.

引发

TypeError – if the input is not a tensor.

Supported Platforms:

GPU

示例

>>> 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)[源代码]

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

注解

On CPU, the supported dtypes are np.float16, np.float32, and np.float64.

参数

m (Tensor) – Input array.

返回

Tensor.

引发

TypeError – if the input is not a tensor.

Supported Platforms:

GPU

示例

>>> 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)[源代码]

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.

注解

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

参数
  • x1 (Tensor) – the bases.

  • x2 (Tensor) – the exponenets.

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

返回

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

实际案例

>>> 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)[源代码]

Returns the floor of the input, element-wise.

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

注解

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.

参数
  • x (Tensor) – input data.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

注解

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

参数
  • x1 (Tensor) – Input array.

  • x2 (Tensor) – Input array.

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

返回

Tensor or scalar.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

注解

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

参数
  • x1 (Tensor) –

  • x2 (Tensor) – input arrays.

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

返回

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

实际案例

>>> 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)[源代码]

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

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

返回

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

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

  • ValueError – If shape has entries < 0.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

注解

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

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

返回

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

引发

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

注解

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

参数
  • x1 (Tensor) – input data.

  • x2 (Tensor) – input data.

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

返回

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

实际案例

>>> 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)[源代码]

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.

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

返回

Tensor, with samples equally spaced on a log scale.

引发

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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.greater(x1, x2, dtype=None)[源代码]

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

注解

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

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

返回

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

实际案例

>>> 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)[源代码]

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

注解

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

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

返回

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

实际案例

>>> 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.heaviside(x1, x2, dtype=None)[源代码]

Computes the Heaviside step function.

注解

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

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

返回

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

实际案例

>>> 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.hsplit(x, indices_or_sections)[源代码]

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.

参数
  • x (Tensor) – A Tensor to be divided.

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

返回

A list of sub-tensors.

引发

TypeError – If argument indices_or_sections is not integer.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

参数

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.

返回

Stacked Tensor, formed by stacking the given tensors.

Supported Platforms:

Ascend GPU CPU

引发

实际案例

>>> 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)[源代码]

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)

注解

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.

参数
  • x1 (Tensor) – Leg of the traingle(s).

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

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

返回

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

实际案例

>>> 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)[源代码]

Returns the identity tensor.

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

返回

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

引发

TypeError – If input arguments have types not specified above.

实际案例

>>> import mindspore.numpy as np
>>> print(np.identity(2))
[[1. 0.]
[0. 1.]]
tinyms.in1d(ar1, ar2, invert=False)[源代码]

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.

注解

Numpy argument assume_unique is not supported since the implementation does not rely on the uniqueness of the input arrays.

参数
  • ar1 (array_like) – Input array with shape (M,).

  • ar2 (array_like) – 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.

返回

Tensor, with shape (M,). The values ar1[in1d] are in ar2.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

参数
  • dimensions (tuple or list of ints) – The shape of the grid.

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

  • sparse (boolean, optional) – Defaults to False. Return a sparse representation of the grid instead of a dense representation.

返回

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

引发

TypeError – if input dimensions is not a tuple or list.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

注解

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.

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

返回

Tensor or scalar.

引发

ValueError – if x1.shape[-1] != x2.shape[-1].

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)[源代码]

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.

注解

For finite values, isclose uses the following equation to test whether two floating point values are equivalent. \(absolute(a - b) <= (atol + rtol * absolute(b))\)

参数
  • a (Union[Tensor, list, tuple]) – Input first tensor to compare.

  • b (Union[Tensor, list, tuple]) – Input second tensor to compare.

  • rtol (Number) – The relative tolerance parameter (see Note).

  • atol (Number) – The absolute tolerance parameter (see Note).

  • equal_nan (bool) – Whether to compare NaN as equal. If True, NaN in

  • will be considered equal to NaN in b in the output tensor. (a) –

返回

A bool tensor of where a and b are equal within the given tolerance.

引发

TypeError – If inputs have types not specified above.

Supported Platforms:

GPU CPU

实际案例

>>> 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)[源代码]

Tests element-wise for finiteness (not infinity or not Not a Number).

The result is returned as a boolean array.

注解

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

参数
  • x (Tensor) – Input values.

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

返回

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

实际案例

>>> 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)[源代码]

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.

注解

Numpy argument assume_unique is not supported since the implementation does not rely on the uniqueness of the input arrays.

参数
  • element (array_like) – Input array.

  • test_elements (array_like) – 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.

返回

Tensor, has the same shape as element. The values element[isin] are in test_elements.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Tests element-wise for positive or negative infinity.

Returns a boolean array of the same shape as x, True where x == +/-inf, otherwise False.

注解

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. Only np.float32 is currently supported.

参数
  • x (Tensor) – Input values.

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

返回

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

实际案例

>>> 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)[源代码]

Tests element-wise for NaN and return result as a boolean array.

注解

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. Only np.float32 is currently supported.

参数
  • x (Tensor) – Input values.

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

返回

Tensor or scalar, true where x is NaN, false otherwise. This is a scalar if x is a scalar.

Supported Platforms:

GPU CPU

实际案例

>>> 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)[源代码]

Tests element-wise for negative infinity, returns result as bool array.

注解

Numpy argument out is not supported. Only np.float32 is currently supported.

参数

x (Tensor) – Input values.

返回

Tensor or scalar, true where x is negative infinity, false otherwise. This is a scalar if x is a scalar.

引发

TypeError – if the input is not a tensor.

Supported Platforms:

GPU CPU

实际案例

>>> import mindspore.numpy as np
>>> output = np.isneginf(np.array([-np.inf, 0., np.inf], np.float32))
>>> print(output)
[ True False False]
tinyms.isposinf(x)[源代码]

Tests element-wise for positive infinity, returns result as bool array.

注解

Numpy argument out is not supported. Only np.float32 is currently supported.

参数

x (Tensor) – Input values.

返回

Tensor or scalar, true where x is positive infinity, false otherwise. This is a scalar if x is a scalar.

引发

TypeError – if the input is not a tensor.

Supported Platforms:

GPU CPU

实际案例

>>> import mindspore.numpy as np
>>> output = np.isposinf(np.array([-np.inf, 0., np.inf], np.float32))
>>> print(output)
[False False  True]
tinyms.isscalar(element)[源代码]

Returns True if the type of element is a scalar type.

注解

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.

参数

element (any) – Input argument, can be of any type and shape.

返回

Boolean, True if element is a scalar type, False if it is not.

引发

TypeError – if the type of element is not supported by mindspore parser.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

注解

Boolean masks are not supported.

参数

*args (Tensor) – 1-D sequences.

返回

Tuple of Tensor, N arrays with N dimensions each, with N the number of input sequences. Together these arrays form an open mesh.

引发

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Kronecker product of two arrays.

Computes the Kronecker product, a composite array made of blocks of the second array scaled by the first.

参数
返回

Tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Returns the lowest common multiple of |x1| and |x2|.

注解

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

参数
  • x1 (Tensor) – input data.

  • x2 (Tensor) – input data.

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

返回

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

实际案例

>>> 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)[源代码]

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

注解

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

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

返回

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

实际案例

>>> 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)[源代码]

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

注解

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

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

返回

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

实际案例

>>> 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)[源代码]

Returns evenly spaced values within a given interval.

参数
  • 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 \((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\).

返回

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.

引发

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> import mindspore.numpy as np
>>> print(np.linspace(0, 5, 6))
[0. 1. 2. 3. 4. 5.]
tinyms.log(x, dtype=None)[源代码]

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.

注解

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.

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

返回

Tensor or scalar, the natural logarithm of x, element-wise. This is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Base-10 logarithm of x.

注解

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

参数
  • x (Tensor) – Input tensor.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Returns the natural logarithm of one plus the input array, element-wise.

Calculates log(1 + x).

注解

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

参数
  • x (Tensor) – Input array.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Base-2 logarithm of x.

注解

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

参数
  • x (Tensor) – Input tensor.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

注解

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

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

注解

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

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Computes the truth value of x1 AND x2 element-wise.

注解

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

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

返回

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

实际案例

>>> 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)[源代码]

Computes the truth value of NOT a element-wise.

注解

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

参数
  • a (Tensor) – The input tensor whose dtype is bool.

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

返回

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.

引发

TypeError – if the input is not a tensor or its dtype is not bool.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Computes the truth value of x1 OR x2 element-wise.

注解

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

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

返回

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

实际案例

>>> 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)[源代码]

Computes the truth value of x1 XOR x2, element-wise.

注解

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

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

返回

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

实际案例

>>> 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)[源代码]

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

参数
  • 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 (\(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\).

返回

Tensor, equally spaced on a log scale.

引发

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Returns the matrix product of two arrays.

注解

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.

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

返回

Tensor or scalar, the matrix product of the inputs. This is a scalar only when both x1, x2 are 1-d vectors.

引发

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

实际案例

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

注解

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

参数
  • a (Tensor) – Input data.

  • axis (None or int or tuple of ints, optional) – defaults to None. 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.

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

返回

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.

引发

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Returns the element-wise maximum of array elements.

Compares two arrays and returns a new array containing the element-wise maxima.

注解

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. On Ascend, input arrays containing inf or NaN are not supported.

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

返回

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

实际案例

>>> 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)[源代码]

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.

注解

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

参数
  • 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 ints, 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.

返回

Tensor or scalar, an array containing the mean values.

引发

ValueError – if axes are out of the range of [-a.ndim, a.ndim), or if the axes contain duplicates.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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')[源代码]

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.

注解

Numpy argument copy is not supported, and a copy is always returned.

参数
  • *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.

返回

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.

引发

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

实际案例

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

注解

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

参数
  • a (Tensor) – Input data.

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

  • 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) – The maximum 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.

返回

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.

引发

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Element-wise minimum of tensor elements.

Compares two tensors and returns a new tensor containing the element-wise minima.

注解

Numpy arguments out, where, casting, order, subok, signature, and extobj are not supported. On Ascend, input arrays containing inf or NaN are not supported.

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

返回

Tensor, element-wise minimum of x1 and x2.

引发
  • TypeError – If inputs have types not specified above.

  • ValueError – If the shapes of x1 and x2 cannot be broadcast.

Supported Platforms:

Ascend GPU CPU

实际案例

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

注解

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

参数
  • x1 (Tensor) – input array.

  • x2 (Tensor) – input array.

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

返回

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

实际案例

>>> 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)[源代码]

Moves axes of an array to new positions.

Other axes remain in their original order.

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

返回

Tensor, array with moved axes.

引发

ValueError – if axes are out of the range of [-a.ndim, a.ndim), or if the axes contain duplicates.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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.multiply(x1, x2, dtype=None)[源代码]

Multiplies arguments element-wise.

注解

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

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

返回

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

实际案例

>>> 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)[源代码]

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.

注解

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

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

返回

Tensor.

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

  • ValueError – If axis is out of range.

Supported Platforms:

GPU CPU

实际案例

>>> 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.nanmean(a, axis=None, dtype=None, keepdims=False)[源代码]

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.

注解

Numpy arguments out is not supported.

参数
  • a (Union[int, float, bool, 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.

返回

Tensor.

引发

ValueError – if axes are out of the range of [-a.ndim, a.ndim), or if the axes contain duplicates.

Supported Platforms:

GPU CPU

实际案例

>>> 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.nanstd(a, axis=None, dtype=None, ddof=0, keepdims=False)[源代码]

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.

注解

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

参数
  • a (Union[int, float, bool, 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.

返回

Tensor.

引发

ValueError – if axes are out of the range of [-a.ndim, a.ndim), or if the axes contain duplicates.

Supported Platforms:

GPU CPU

实际案例

>>> 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.nansum(a, axis=None, dtype=None, keepdims=False)[源代码]

Returns the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.

注解

Numpy arguments out is not supported.

参数
  • a (Union[int, float, bool, 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.

返回

Tensor.

引发

ValueError – if axes are out of the range of [-a.ndim, a.ndim), or if the axes contain duplicates.

Supported Platforms:

GPU CPU

实际案例

>>> 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)[源代码]

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.

注解

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

参数
  • a (Union[int, float, bool, 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.

返回

Tensor.

引发

ValueError – if axes are out of the range of [-a.ndim, a.ndim), or if the axes contain duplicates.

Supported Platforms:

GPU CPU

实际案例

>>> 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.negative(a, dtype=None)[源代码]

Numerical negative, element-wise.

注解

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

参数
  • a (Tensor) – Input tensor.

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

返回

Tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> import mindspore.numpy as np
>>> a = np.asarray([1, -1]).astype('float32')
>>> output = np.negative(a)
>>> print(output)
[-1. 1.]
tinyms.not_equal(x1, x2, dtype=None)[源代码]

Returns (x1 != x2) element-wise.

注解

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

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

返回

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.

引发

TypeError – If the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Returns (x1 != x2) element-wise.

注解

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

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

返回

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.

引发

TypeError – If the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

参数
  • shape (Union[int, tuple, list]) – the shape of the new tensor.

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

返回

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

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

  • ValueError – If shape entries have values \(< 0\).

Supported Platforms:

Ascend GPU CPU

实际案例

>>> import mindspore.numpy as np
>>> print(np.ones((2,2)))
[[1. 1.]
[1. 1.]]
tinyms.ones_like(a, dtype=None, shape=None)[源代码]

Returns an array of ones with the same shape and type as a given array.

注解

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

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

返回

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

引发

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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 ]]

注解

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.

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

返回

Tensor or scalar, out[i, j] = a[i] * b[j].

引发

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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.positive(a, dtype=None)[源代码]

Numerical positive, element-wise.

注解

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

参数
  • a (Tensor) – Input tensor.

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

返回

Tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

Raises each base in x1 to the positionally-corresponding power in x2.

注解

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

参数
  • x1 (Tensor) – the bases.

  • x2 (Tensor) – the exponents.

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

返回

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

实际案例

>>> 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)[源代码]

Returns the data type with the smallest size and smallest scalar kind.

注解

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.

参数
  • type1 (Union[mindspore.dtype, str]) – First data type.

  • type2 (Union[mindspore.dtype, str]) – Second data type.

返回

The promoted data type.

引发

TypeError – if the input are not valid mindspore.dtype input.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> import mindspore.numpy as np
>>> output = np.promote_types(np.float32, np.float64)
>>> print(output)
Float64
tinyms.ptp(x, axis=None, keepdims=False)[源代码]

Range of values (maximum - minimum) along an axis. The name of the function comes from the acronym for ‘peak to peak’.

注解

Numpy arguments dtype and out are not supported.

参数
  • 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) – Default is False.

返回

Tensor.

引发

TypeError – if inputs have types not specified above.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Converts angles from radians to degrees.

参数
  • x (Tensor) – Angles in radians.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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.ravel(x)[源代码]

Returns a contiguous flattened tensor.

A 1-D tensor, containing the elements of the input, is returned.

参数

x (Tensor) – A tensor to be flattened.

返回

Flattened tensor, has the same data type as the original tensor x.

引发

TypeError – If x is not tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> import mindspore.numpy as np
>>> x = np.ones((2,3,4))
>>> output = np.ravel(x)
>>> print(output.shape)
(24,)
tinyms.reciprocal(x, dtype=None)[源代码]

Returns the reciprocal of the argument, element-wise.

Calculates 1/x.

注解

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.

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

返回

Tensor or scalar, this is a scalar if x is a scalar.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

注解

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

参数
  • x1 (Tensor) – input array.

  • x2 (Tensor) – input array.

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

返回

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

实际案例

>>> 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)[源代码]

Repeats elements of an array.

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

返回

Tensor, output array which has the same shape as a, except along the given axis.

引发
Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Reshapes a tensor without changing its data.

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

返回

Reshaped Tensor. Has the same data type as the original tensor x.

引发
  • 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

实际案例

>>> 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.roll(a, shift, axis=None)[源代码]

Rolls a tensor along given axes.

Elements that rolls beyond the last position are re-introduced at the first.

参数
  • 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 ints, 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.

返回

Tensor, with the same shape as a.

Supported Platforms:

Ascend GPU CPU

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

  • ValueError – If axis exceeds a.ndim, or shift and axis cannot broadcast.

实际案例

>>> 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)[源代码]

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.

参数
  • 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 shown in the table. (Please refer to the source code.)

返回

Transposed Tensor. Has the same data type as the original tensor x.

Supported Platforms:

Ascend GPU CPU

引发
  • 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]\).

实际案例

>>> 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))[源代码]

Rotates a tensor by 90 degrees in the plane specified by axes. Rotation direction is from the first towards the second axis.

参数
  • 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,).

返回

Tensor.

引发
  • TypeError – if input a is not a Tensor or the argument k is not integer or the argument axes is not tuple of ints or list of ints.

  • ValueError – if any axis is out of range or the length of axes is not 2.

Supported Platforms:

GPU

实际案例

>>> 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.select(condlist, choicelist, default=0)[源代码]

Returns an array drawn from elements in choicelist, depending on conditions.

参数
  • condlist (array_like) – 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 (array_like) – 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.

返回

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.

Supported Platforms:

Ascend GPU CPU

引发

ValueError – if len(condlist) != len(choicelist).

实际案例

>>> 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.sin(x, dtype=None)[源代码]

Trigonometric sine, element-wise.

注解

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

参数
  • x (Tensor) – Input tensor.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Hyperbolic sine, element-wise.

注解

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

参数
  • x (Tensor) – Input tensor.

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

返回

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

Supported Platforms:

Ascend CPU

实际案例

>>> 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.split(x, indices_or_sections, axis=0)[源代码]

Splits a tensor into multiple sub-tensors along the given axis.

参数
  • x (Tensor) – A Tensor to be divided.

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

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

返回

A list of sub-tensors.

引发
  • 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

实际案例

>>> 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)[源代码]

Returns the non-negative square-root of an array, element-wise.

注解

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

参数
  • x (Tensor) – The values whose square-roots are required.

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

返回

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

实际案例

>>> 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)[源代码]

Returns the element-wise square of the input.

注解

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

参数
  • x (Tensor) – Input data.

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

返回

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

实际案例

>>> 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)[源代码]

Removes single-dimensional entries from the shape of an tensor.

参数
返回

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

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

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

注解

Numpy argument out is not supported.

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

返回

Tensor, The stacked array has one more dimension than the input arrays.

引发

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

注解

Numpy arguments dtype and out are not supported.

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

返回

Standard deviation tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Subtracts arguments, element-wise.

注解

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

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

返回

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

实际案例

>>> 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.swapaxes(x, axis1, axis2)[源代码]

Interchanges two axes of a tensor.

参数
  • x (Tensor) – A tensor to be transposed.

  • axis1 (int) – First axis.

  • axis2 (int) – Second axis.

返回

Transposed tensor, has the same data type as the original tensor x.

引发
  • 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

实际案例

>>> 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')[源代码]

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,...].

注解

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

参数
  • a (Tensor) – Source array with shape (Ni…, M, Nk…).

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

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

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

    Specifies how out-of-bounds indices will behave.

    ‘raise’ – raise an error (default);

    ‘wrap’ – wrap around;

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

返回

Tensor, the indexed result.

引发
Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

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

返回

Tensor, the indexed result, with shape (Ni…, J, Nk…).

引发
  • ValueError – if input array and indices have different number of dimensions.

  • TypeError – if the input is not a Tensor.

Supported Platforms:

Ascend GPU CPU

示例

>>> 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)[源代码]

Computes tangent element-wise.

Equivalent to \(np.sin(x)/np.cos(x)\) element-wise.

注解

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

参数
  • x (Tensor) – Input tensor.

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

返回

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

引发

TypeError – If the input is not a tensor or is tensor.dtype is mindsproe.float64.

Supported Platforms:

Ascend CPU

实际案例

>>> 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)[源代码]

Computes hyperbolic tangent element-wise.

注解

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

参数
  • x (Tensor) – Input tensor.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

注解

On CPU, the supported dypes are np.float16 and np.float32. On GPU, the supported dypes are np.float16 and np.float32.

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

返回

Tensor, or list of tensors, the tensor dot product of the input.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

参数
  • a (Tensor) – The input array.

  • reps (int or sequence of ints) – The number of repetitions of a along each axis.

返回

Tensor, the tiled output array.

引发

TypeError – if the input is not a tensor.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

注解

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

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

返回

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.

引发

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> import mindspore.numpy as np
>>> output = np.trace(np.eye(3))
>>> print(output)
3.0
>>> a = np.arange(8).reshape((2,2,2))
>>> output = np.trace(a)
>>> print(output)
[6 8]
>>> a = np.arange(24).reshape((2,2,2,3))
>>> output = np.trace(a).shape
>>> print(output)
(2, 3)
tinyms.transpose(a, axes=None)[源代码]

Reverses or permutes the axes of a tensor; returns the modified tensor.

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

返回

Tensor, the transposed tensor array.

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

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Integrates along the given axis using the composite trapezoidal rule.

Integrates y (x) along given axis.

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

  • axis (int, optional) – The axis along which to integrate.

返回

Tensor of float, definite integral as approximated by trapezoidal rule.

引发

ValueError – If axis is out of range of [-y.ndim, y.ndim).

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Returns a tensor with ones at and below the given diagonal and zeros elsewhere.

参数
  • 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 mindspore.dtype.

返回

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.

引发

TypeError – If input arguments have types not specified above.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

Returns a lower triangle of a tensor.

Returns a copy of a tensor with elements above the k-th diagonal zeroed.

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

返回

Lower triangle of m, of same shape and data-type as m.

Supported Platforms:

Ascend GPU CPU

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

  • ValueError – If input m’s rank \(< 1\).

实际案例

>>> import mindspore.numpy as np
>>> output = np.tril(np.ones((3, 3)))
>>> print(output)
[[1. 0. 0.]
[1. 1. 0.]
[1. 1. 1.]]
tinyms.triu(m, k=0)[源代码]

Returns an upper triangle of a tensor.

Returns a copy of a tensor with elements below the k-th diagonal zeroed.

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

返回

Upper triangle of m, of same shape and data-type as m.

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

  • ValueError – If input m’s rank < 1.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> import mindspore.numpy as np
>>> output = np.triu(np.ones((3, 3)))
>>> print(output)
[[1. 1. 1.]
[0. 1. 1.]
[0. 0. 1.]]
tinyms.true_divide(x1, x2, dtype=None)[源代码]

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

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

注解

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

参数
  • x1 (Tensor) – the divident.

  • x2 (Tensor) – the divisor.

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

返回

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

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

注解

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

参数
  • x (Tensor) – input data.

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

返回

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

实际案例

>>> 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)[源代码]

Finds the unique elements of a tensor. The input tensor will be flattened first when it has more than one dimension.

注解

Numpy arguments axis, return_index and return_counts are not supported. On CPU, this operator must be executed in graph mode.

参数
  • x (Tensor) – The input tensor to be processed.

  • return_inverse (bool) – If True, also return the indices of the unique tensor. Default: False.

返回

Tensor or tuple of Tensors. - If return_inverse is False, just return the unique tensor. - If return_inverse is True, return tuple of tensors.

Supported Platforms:

Ascend GPU CPU

引发

TypeError – If x is not tensor.

实际案例

>>> import mindspore.numpy as np
>>> from mindspore import context
>>> context.set_context(mode=context.GRAPH_MODE)
>>> input_x = np.asarray([1, 2, 2, 2, 3, 4, 5]).astype('int32')
>>> output_x = np.unique(input_x)
>>> print(output_x)
[1 2 3 4 5]
>>> output_x = np.unique(input_x, return_inverse=True)
>>> print(output_x)
(Tensor(shape=[5], dtype=Int32, value= [ 1, 2, 3, 4, 5]), Tensor(shape=[7], dtype=Int32,
    value= [0, 1, 1, 1, 2, 3, 4]))
tinyms.vander(x, N=None, increasing=False)[源代码]

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.

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

返回

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)}\).

引发
  • TypeError – If inputs have types not specified above.

  • ValueError – If x is not 1-D, or N < 0.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

注解

Numpy arguments dtype and out are not supported.

参数
  • 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) – Default: False.

Supported Platforms:

Ascend GPU CPU

返回

Standard deviation tensor.

实际案例

>>> 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)[源代码]

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.

参数
  • x (Tensor) – A Tensor to be divided.

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

返回

A list of sub-tensors.

引发

TypeError – If argument indices_or_sections is not integer.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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.

参数

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.

返回

Stacked Tensor, formed by stacking the given tensors.

Supported Platforms:

Ascend GPU CPU

引发

实际案例

>>> 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)[源代码]

Returns elements chosen from x or y depending on condition.

注解

As nonzero is not supported, neither x or y can be None.

参数
  • condition (Tensor) – where True, yield x, otherwise yield y.

  • x (Tensor) –

  • y (Tensor) – Values from which to choose. x, y and condition need to be broadcastable to some shape.

返回

Tensor or scalar, with elements from x where condition is True, and elements from y elsewhere.

引发

ValueError – if operands cannot be broadcast.

Supported Platforms:

Ascend GPU CPU

实际案例

>>> 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)[源代码]

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

参数
  • shape (Union[int, tuple, list]) – the shape of the new tensor.

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

返回

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

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

  • ValueError – If shape entries have values \(< 0\).

Supported Platforms:

Ascend GPU CPU

实际案例

>>> import mindspore.numpy as np
>>> print(np.zeros((2,2)))
[[0. 0.]
[0. 0.]]
tinyms.zeros_like(a, dtype=None, shape=None)[源代码]

Returns an array of zeros with the same shape and type as a given array.

注解

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

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

返回

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

引发

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

Supported Platforms:

Ascend GPU CPU

实际案例

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