# mindspore.ops.operations¶

Primitive operator classes.

A collection of operators to build nerual networks or computing functions.

class mindspore.ops.operations.ACos(*args, **kwargs)[source]

Computes arccosine of input element-wise.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

Outputs:

Tensor, has the same shape as input_x.

Examples

>>> acos = ACos()
>>> X = Tensor(np.array([0.74, 0.04, 0.30, 0.56]), ms.float32)
>>> output = acos(X)

class mindspore.ops.operations.Abs(*args, **kwargs)[source]

Returns absolute value of a tensor element-wise.

Inputs:
• input_x (Tensor) - The input tensor. The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

Outputs:

Tensor, has the same shape as the input_x.

Examples

>>> input_x = Tensor(np.array([-1.0, 1.0, 0.0]), mindspore.float32)
>>> abs = Abs()
>>> abs(input_x)
[1.0, 1.0, 0.0]

class mindspore.ops.operations.Adam(*args, **kwargs)[source]

The Adam algorithm is proposed in Adam: A Method for Stochastic Optimization.

The updating formulas are as follows,

$\begin{split}\begin{array}{ll} \\ m = \beta_1 * m + (1 - \beta_1) * g \\ v = \beta_2 * v + (1 - \beta_2) * g * g \\ l = \alpha * \frac{\sqrt{1-\beta_2^t}}{1-\beta_1^t} \\ w = w - l * \frac{m}{\sqrt{v} + \epsilon} \end{array}\end{split}$

$$m$$ represents the 1st moment vector, $$v$$ represents the 2nd moment vector, $$g$$ represents gradient, $$l$$ represents scaling factor lr, $$\beta_1, \beta_2$$ represent beta1 and beta2, $$t$$ represents updating step while $$beta_1^t$$ and $$beta_2^t$$ represent beta1_power and beta2_power, $$\alpha$$ represents learning_rate, $$w$$ represents var, $$\epsilon$$ represents epsilon.

Parameters
• use_locking (bool) – Whether to enable a lock to protect updating variable tensors. If True, updating of the var, m, and v tensors will be protected by a lock. If False, the result is unpredictable. Default: False.

Inputs:
• var (Tensor) - Weights to be updated.

• m (Tensor) - The 1st moment vector in the updating formula.

• v (Tensor) - the 2nd moment vector in the updating formula.

• beta1_power (float) - $$beta_1^t$$ in the updating formula.

• beta2_power (float) - $$beta_2^t$$ in the updating formula.

• lr (float) - $$l$$ in the updating formula.

• beta1 (float) - The exponential decay rate for the 1st moment estimates.

• beta2 (float) - The exponential decay rate for the 2nd moment estimates.

• epsilon (float) - Term added to the denominator to improve numerical stability.

Outputs:

Tensor, has the same shape and data type as var.

class mindspore.ops.operations.AddN(*args, **kwargs)[source]

Computes addition of all input tensors element-wise.

All input tensors should have the same shape.

Inputs:
• input_x (Union(tuple[Tensor], list[Tensor])) - The input tuple or list is made up of multiple tensors whose dtype is number or bool to be added together.

Outputs:

Tensor, has the same shape and dtype as each entry of the input_x.

Examples

>>> class NetAddN(nn.Cell):
>>>     def __init__(self):
>>>
>>>     def construct(self, *z):
>>>
>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
>>> input_y = Tensor(np.array([4, 5, 6]), mindspore.int32)
>>> net(input_x, input_y, input_x, input_y)
Tensor([10, 14, 18], shape=(3,), dtype=mindspore.int32)

class mindspore.ops.operations.AllGather(*args, **kwargs)[source]

Gathers tensors from the specified communication group.

Note

Tensor must have the same shape and format in all processes participating in the collective.

Parameters

group (str) – The communication group to work on. Default: “hccl_world_group”.

Raises
• TypeError – If group is not a string.

• ValueError – If the local rank id of the calling process in the group is larger than the group’s rank size.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

Outputs:

Tensor. If the number of devices in the group is N, then the shape of output is $$(N, x_1, x_2, ..., x_R)$$.

Examples

>>> from mindspore.communication.management import init
>>> import mindspore.ops.operations as P
>>> init('nccl')
>>> class Net(nn.Cell):
>>>     def __init__(self):
>>>         super(Net, self).__init__()
>>>         self.allgather = P.AllGather(group="nccl_world_group")
>>>
>>>     def construct(self, x):
>>>         return self.allgather(x)
>>>
>>> input_ = Tensor(np.ones([2, 8]).astype(np.float32))
>>> net = Net()
>>> output = net(input_)

class mindspore.ops.operations.AllReduce(*args, **kwargs)[source]

Reduces the tensor data across all devices in such a way that all devices will get the same final result.

Note

The operation of AllReduce does not support “prod” currently. The input of AllReduce does not support dtype “Bool”. Tensor must have same shape and format in all processes participating in the collective.

Parameters
• op (str) – Specifies an operation used for element-wise reductions, like sum, max, min. Default: ReduceOp.SUM.

• group (str) – The communication group to work on. Default: “hccl_world_group”.

Raises
• TypeError – If any of op and group is not a string or fusion is not a integer or the input’s dtype is bool.

• ValueError – If op is “prod”

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

Outputs:

Tensor, has the same shape of the input, i.e., $$(x_1, x_2, ..., x_R)$$. The contents depend on the specified operation.

Examples

>>> from mindspore.communication.management import init
>>> import mindspore.ops.operations as P
>>> init('nccl')
>>> class Net(nn.Cell):
>>>     def __init__(self):
>>>         super(Net, self).__init__()
>>>         self.allreduce_sum = P.AllReduce(ReduceOp.SUM, group="nccl_world_group")
>>>
>>>     def construct(self, x):
>>>         return self.allreduce_sum(x)
>>>
>>> input_ = Tensor(np.ones([2, 8]).astype(np.float32))
>>> net = Net()
>>> output = net(input_)

vm_impl(x)[source]

Implement by vm mode.

class mindspore.ops.operations.ApplyMomentum(*args, **kwargs)[source]

Optimizer that implements the Momentum algorithm.

Refer to the paper On the importance of initialization and momentum in deep learning for more details.

Parameters
• use_locking (bool) – Enable a lock to protect the update of variable and accumlation tensors. Default: False.

• use_nesterov (bool) – Enable Nesterov momentum. Default: False.

Inputs:
• variable (Tensor) - Weights to be updated.

• accumulation (Tensor) - Accumulated gradient value by moment weight.

• learning_rate (float) - Learning rate.

• momentum (float) - Momentum.

Outputs:

Tensor, parameters to be updated.

Examples

>>> net = ResNet50()
>>> loss = SoftmaxCrossEntropyWithLogits()
>>> opt = ApplyMomentum(Tensor(np.array([0.001])), Tensor(np.array([0.9])),
>>> model = Model(net, loss, opt)

class mindspore.ops.operations.ArgMaxWithValue(*args, **kwargs)[source]

Calculates maximum value with corresponding index.

Calculates maximum value along with given axis for the input tensor. Returns the maximum values and indices.

Note

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

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

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

Inputs:
• input_x (Tensor) - The input tensor, can be any dimension. Set the shape of input tensor as $$(x_1, x_2, ..., x_N)$$.

Outputs:

Tensor, corresponding index and maximum value of input tensor. If keep_dims is true, the output tensors shape is $$(x_1, x_2, ..., x_{axis-1}, 1, x_{axis+1}, ..., x_N)$$. Else, the shape is $$(x_1, x_2, ..., x_{axis-1}, x_{axis+1}, ..., x_N)$$.

Examples

>>> input = Tensor(np.random.rand(5))
>>> index, output = ArgMaxWithValue()(input)

class mindspore.ops.operations.ArgMinWithValue(*args, **kwargs)[source]

Calculates minimum value with corresponding index, return indices and values.

Calculates minimum value along with given axis for the input tensor. Returns the minimum values and indices.

Note

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

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

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

Inputs:
• input_x (Tensor) - The input tensor, can be any dimension. Set the shape of input tensor as $$(x_1, x_2, ..., x_N)$$.

Outputs:

Tensor, corresponding index and minimum value of input tensor. If keep_dims is true, the output tensors shape is $$(x_1, x_2, ..., x_{axis-1}, 1, x_{axis+1}, ..., x_N)$$. Else, the shape is $$(x_1, x_2, ..., x_{axis-1}, x_{axis+1}, ..., x_N)$$.

Examples

>>> input = Tensor(np.random.rand(5))
>>> index, output = ArgMinWithValue()(input)

class mindspore.ops.operations.Argmax(*args, **kwargs)[source]

Returns the indices of the max value of a tensor across the axis.

If the shape of input tensor is $$(x_1, ..., x_N)$$, the output tensor shape is $$(x_1, ..., x_{axis-1}, x_{axis+1}, ..., x_N)$$.

Parameters
• axis (int) – Axis on which Argmax operation applies. Default: -1.

• output_type (mindspore.dtype) – An optional data type of mindspore.dtype.int32 and mindspore.dtype.int64. Default: mindspore.dtype.int64.

Inputs:
• input_x (Tensor) - Input tensor.

Outputs:

Tensor, indices of the max value of input tensor across the axis.

Examples

>>> input = Tensor(np.array([2.0, 3.1, 1.2]))
>>> index = Argmax()(input)
>>> assert index == Tensor(1, mindspore.int64)

class mindspore.ops.operations.Argmin(*args, **kwargs)[source]

Returns the indices of the min value of a tensor across the axis.

If the shape of input tensor is $$(x_1, ..., x_N)$$, the output tensor shape is $$(x_1, ..., x_{axis-1}, x_{axis+1}, ..., x_N)$$.

Parameters
• axis (int) – Axis on which Argmin operation applies. Default: -1.

• output_type (mindspore.dtype) – An optional data type from: mindspore.dtype.int32, mindspore.dtype.int64. Default: mindspore.dtype.int64.

Inputs:
• input_x (Tensor) - Input tensor.

Outputs:

Tensor, indices of the min value of input tensor across the axis.

Examples

>>> input = Tensor(np.array([2.0, 3.1, 1.2]))
>>> index = Argmin()(input)
>>> assert index == Tensor(2, mindspore.int64)

class mindspore.ops.operations.Assign(*args, **kwargs)[source]

Assign Parameter with a value.

Inputs:
• variable (Parameter) - The Parameter.

• value (Tensor) - The value to assign.

Outputs:

Tensor, has the same type as original variable.

Examples

>>> class Net(nn.Cell):
>>>     def __init__(self):
>>>         super(Net, self).__init__()
>>>         self.y = mindspore.Parameter(Tensor([1.0], mindspore.float32), name="y")
>>>
>>>     def construct(self, x):
>>>         Assign()(self.y, x)
>>>         return x
>>> x = Tensor([2.0], mindspore.float32)
>>> net = Net()
>>> net(x)

class mindspore.ops.operations.AssignAdd(*args, **kwargs)[source]

Inputs:
• input_x (Parameter) - The Parameter.

• input_y (Union[scalar, Tensor]) - Has the same shape as input_x.

Examples

>>> class Net(Cell):
>>>     def __init__(self):
>>>         self.inputdata = Parameter(initializer(1, [1], mindspore.int64), name="global_step")
>>>
>>>     def construct(self, x):
>>>         return self.inputdata
>>>
>>> net = Net()
>>> x = Tensor(np.ones([1]).astype(np.int64)*100)
>>> net(x)

class mindspore.ops.operations.AssignSub(*args, **kwargs)[source]

Updates a Parameter by subtracting a value from it.

Inputs:
• input_x (Parameter) - The Parameter.

• input_y (Union[scalar, Tensor]) - Has the same shape as input_x.

Examples

>>> class Net(Cell):
>>>     def __init__(self):
>>>         self.AssignSub = P.AssignSub()
>>>         self.inputdata = Parameter(initializer(1, [1], mindspore.int64), name="global_step")
>>>
>>>     def construct(self, x):
>>>         self.AssignSub(self.inputdata, x)
>>>         return self.inputdata
>>>
>>> net = Net()
>>> x = Tensor(np.ones([1]).astype(np.int64)*100)
>>> net(x)

class mindspore.ops.operations.AvgPool(*args, **kwargs)[source]

Average pooling operation.

Applies a 2D average pooling over an input Tensor which can be regarded as a composition of 2D input planes. Typically the input is of shape $$(N_{in}, C_{in}, H_{in}, W_{in})$$, AvgPool2d outputs regional average in the $$(H_{in}, W_{in})$$-dimension. Given kernel size $$ks = (h_{ker}, w_{ker})$$ and stride $$s = (s_0, s_1)$$, the operation is as follows.

$\text{output}(N_i, C_j, h, w) = \frac{1}{h_{ker} * w_{ker}} \sum_{m=0}^{h_{ker}-1} \sum_{n=0}^{w_{ker}-1} \text{input}(N_i, C_j, s_0 \times h + m, s_1 \times w + n)$
Parameters
• ksize (Union[int, tuple[int]]) – The size of the window to take a average over, that should be a tuple of two int for width and height. Default: 1.

• stride (Union[int, tuple[int]]) – The stride of the window, that should be a tuple of two int for width and height. Default: 1.

• padding (str) – The optional values for pad mode “SAME”, “VALID”. Default: “VALID”.

Inputs:
• input (Tensor) - Tensor of shape $$(N, C_{in}, H_{in}, W_{in})$$.

Outputs:

Tensor, with shape $$(N, C_{out}, H_{out}, W_{out})$$.

class mindspore.ops.operations.BatchMatMul(*args, **kwargs)[source]

Computes matrix multiplication between two tensors by batch

result[…, :, :] = tensor(a[…, :, :]) * tensor(b[…, :, :]).

The two input tensors must have same rank and the rank must be 3 at least.

Parameters
• transpose_a (bool) – If True, a is transposed on the last two dimensions before multiplication. Default: False.

• transpose_b (bool) – If True, b is transposed on the last two dimensions before multiplication. Default: False.

Inputs:
• input_x (Tensor) - The first tensor to be multiplied. The shape of the tensor is $$(*B, N, C)$$, where $$*B$$ represents the batch size which can be multidimensional, $$N$$ and $$C$$ are the size of the last two dimensions. If transpose_a is True, its shape should be $$(*B, C, N)$$.

• input_y (Tensor) - The second tensor to be multiplied. The shape of the tensor is $$(*B, C, M)$$. If transpose_b is True, its shape should be $$(*B, M, C)$$.

Outputs:

Tensor, the shape of the output tensor is $$(*B, N, M)$$.

Examples

>>> input_x = Tensor(np.ones(shape=[2, 4, 1, 3]), mindspore.float32)
>>> input_y = Tensor(np.ones(shape=[2, 4, 3, 4]), mindspore.float32)
>>> batmatmul = BatchMatMul()
>>> output = batmatmul(input_x, input_y)
>>>
>>> input_x = Tensor(np.ones(shape=[2, 4, 3, 1]), mindspore.float32)
>>> input_y = Tensor(np.ones(shape=[2, 4, 3, 4]), mindspore.float32)
>>> batmatmul = BatchMatMul(transpose_a=True)
>>> output = batmatmul(input_x, input_y)

class mindspore.ops.operations.BatchNorm(*args, **kwargs)[source]

Batch Normalization for input data and updated parameters.

Batch Normalization is widely used in convolutional neural networks. This operation applies Batch Normalization over input to avoid internal covariate shift as described in the paper Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift. It rescales and recenters the features using a mini-batch of data and the learned parameters which can be described in the following formula,

$y = \frac{x - mean}{\sqrt{variance + \epsilon}} * \gamma + \beta$

where $$\gamma$$ is scale, $$\beta$$ is bias, $$\epsilon$$ is epsilon.

Parameters
• is_training (bool) – If is_training is True, mean and variance are computed during training. If is_training is False, they’re loaded from checkpoint during inference. Default: False.

• epsilon (float) – A small value added for numerical stability. Default: 1e-5.

Inputs:
• input_x (Tensor) - Tensor of shape $$(N, C)$$.

• scale (Tensor) - Tensor of shape $$(C,)$$.

• bias (Tensor) - Tensor of shape $$(C,)$$.

• mean (Tensor) - Tensor of shape $$(C,)$$.

• variance (Tensor) - Tensor of shape $$(C,)$$.

Outputs:

Tuple of 5 Tensor, the normalized inputs and the updated parameters.

• output_x (Tensor) - The same type and shape as the input_x. The shape is $$(N, C)$$.

• updated_scale (Tensor) - Tensor of shape $$(C,)$$.

• updated_bias (Tensor) - Tensor of shape $$(C,)$$.

• reserve_space_1 (Tensor) - Tensor of shape $$(C,)$$.

• reserve_space_2 (Tensor) - Tensor of shape $$(C,)$$.

• reserve_space_3 (Tensor) - Tensor of shape $$(C,)$$.

class mindspore.ops.operations.BiasAdd(*args, **kwargs)[source]

Returns sum of input and bias tensor.

Adds the 1-D bias tensor to the input tensor, and boardcasts the shape on all axis except for the channel axis.

Inputs:
• input_x (Tensor) - Input value, with shape $$(N, C)$$ or $$(N, C, H, W)$$.

• bias (Tensor) - Bias value, with shape $$(C)$$.

Outputs:

Tensor, with the same shape and type as input_x.

class mindspore.ops.operations.BinaryCrossEntropy(*args, **kwargs)[source]

Computes the Binary Cross Entropy between the target and the output.

Note

Sets input as $$x$$, input label as $$y$$, output as $$\ell(x, y)$$. Let,

$L = \{l_1,\dots,l_N\}^\top, \quad l_n = - w_n \left[ y_n \cdot \log x_n + (1 - y_n) \cdot \log (1 - x_n) \right]$

Then,

$\begin{split}\ell(x, y) = \begin{cases} L, & \text{if reduction} = \text{'none';}\\ \operatorname{mean}(L), & \text{if reduction} = \text{'mean';}\\ \operatorname{sum}(L), & \text{if reduction} = \text{'sum'.} \end{cases}\end{split}$
Parameters

reduction (str) – Specifies the reduction to apply to the output. Its value should be one of ‘none’, ‘mean’, ‘sum’. Default: ‘mean’.

Inputs:
• input_x (Tensor) - The input Tensor.

• input_y (Tensor) - The label Tensor which has same shape as input_x.

• weight (Tensor, optional) - A rescaling weight applied to the loss of each batch element. And it should have same shape as input_x. Default: None.

Outputs:

Tensor or Scalar, if reduction is ‘none’, then output is a tensor and same shape as input_x. Otherwise it is a scalar.

class mindspore.ops.operations.BoundingBoxDecode(*args, **kwargs)[source]

Decode bounding boxes locations.

Parameters
• means (tuple) – The means of deltas calculation. Default: (0.0, 0.0, 0.0, 0.0).

• stds (tuple) – The standard deviations of deltas calculation. Default: (1.0, 1.0, 1.0, 1.0).

• max_shape (tuple) – The max size limit for decoding box calculation.

• wh_ratio_clip (float) – The limit of width and height ratio for decoding box calculation. Default: 0.016.

Inputs:
• anchor_box (Tensor) - Anchor boxes.

• deltas (Tensor) - Delta of boxes.

Outputs:

Tensor, decoded boxes.

Examples

>>> boundingbox_decode = BoundingBoxDecode(means=(0.0, 0.0, 0.0, 0.0), stds=(1.0, 1.0, 1.0, 1.0),
max_shape=(768, 1280), wh_ratio_clip=0.016)
>>> bbox = boundingbox_decode(anchor_box, deltas)

class mindspore.ops.operations.BoundingBoxEncode(*args, **kwargs)[source]

Encode bounding boxes locations.

Parameters
• means (tuple) – Means for encoding bounding boxes calculation. Default: (0.0, 0.0, 0.0, 0.0).

• stds (tuple) – Stds for encoding bounding boxes calculation. Default: (1.0, 1.0, 1.0, 1.0).

Inputs:
• anchor_box (Tensor) - Anchor boxes.

• groundtruth_box (Tensor) - Ground truth boxes.

Outputs:

Tensor, encoded bounding boxes.

Examples

>>> boundingbox_encode = BoundingBoxEncode(means=(0.0, 0.0, 0.0, 0.0), stds=(1.0, 1.0, 1.0, 1.0))
>>> delta_box = boundingbox_encode(anchor_box, groundtruth_box)

class mindspore.ops.operations.Broadcast(*args, **kwargs)[source]

Broadcasts the tensor to the whole group.

Note

Tensor must have the same shape and format in all processes participating in the collective.

Parameters
• root_rank (int) – Source rank. Required in all processes except the one that is sending the data.

• group (str) – The communication group to work on. Default: “hccl_world_group”.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

Outputs:

Tensor, has the same shape of the input, i.e., $$(x_1, x_2, ..., x_R)$$. The contents depend on the data of the root_rank device.

Raises

TypeError – If root_rank is not a integer or group is not a string.

Examples

>>> from mindspore.communication.management import init
>>> import mindspore.ops.operations as P
>>> init('nccl')
>>> class Net(nn.Cell):
>>>     def __init__(self):
>>>         super(Net, self).__init__()
>>>
>>>     def construct(self, x):
>>>
>>> input_ = Tensor(np.ones([2, 8]).astype(np.float32))
>>> net = Net()
>>> output = net(input_)

class mindspore.ops.operations.Cast(*args, **kwargs)[source]

Returns a tensor with the new specified data type.

Inputs:
• input_x (Union[Tensor, Number]) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$. The tensor to be casted.

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

Outputs:

Tensor, the shape of tensor is $$(x_1, x_2, ..., x_R)$$, same as input_x.

Examples

>>> input_np = np.random.randn(2, 3, 4, 5).astype(np.float32)
>>> input_x = Tensor(input_np)
>>> type_dst = mindspore.int32
>>> cast = Cast()
>>> result = cast(input_x, type_dst)
>>> expect = input_np.astype(type_dst)

class mindspore.ops.operations.CheckValid(*args, **kwargs)[source]

Check bounding box.

Check whether the bounding box cross data and data border.

Inputs:
• bboxes (Tensor) - Bounding boxes tensor with shape (N, 4).

• img_metas (Tensor) - Raw image size information, format (height, width, ratio).

Outputs:

Tensor, the valided tensor.

class mindspore.ops.operations.Concat(*args, **kwargs)[source]

Concat tensor in specified axis.

Concat input tensors along with the given axis.

Note

The input data is a tuple of tensors. These tensors have the same rank R. Set the given axis as m, and $$0 \le m < N$$. Set the number of input tensors as N. For the $$i$$-th tensor $$t_i$$ has the shape $$(x_1, x_2, ..., x_{mi}, ..., x_R)$$. $$x_{mi}$$ is the $$m$$-th dimension of the $$i$$-th tensor. Then, the output tensor shape is

$(x_1, x_2, ..., \sum_{i=1}^Nx_{mi}, ..., x_R)$
Parameters

axis (int) – The specified axis. Default: 0.

Inputs:
• input_x (tuple, list) - Tuple or list of input tensors.

Outputs:

Tensor, the shape is $$(x_1, x_2, ..., \sum_{i=1}^Nx_{mi}, ..., x_R)$$.

Examples

>>> data1 = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))
>>> data2 = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))
>>> op = Concat()
>>> output = op((data1, data2))

class mindspore.ops.operations.ConcatOffset(*args, **kwargs)[source]

class mindspore.ops.operations.ControlDepend(*args, **kwargs)[source]

Adds control dependency relation between source and destination operation.

In many cases, we need to control the execution order of operations. ControlDepend is designed for this. ControlDepend will indicate the execution engine to run the operations in specific order. ControlDepend tells the engine that the destination operations should depend on the source operation which means the source operations should be executed before the destination.

Parameters

depend_mode (int) – Use 0 for normal depend, 1 for depend on operations that used the parameter. Default: 0.

Inputs:
• src (Any) - The source input. It can be a tuple of operations output or a single operation output. We do not concern about the input data, but concern about the operation that generates the input data. If depend_mode = 1 is specified and the source input is parameter, we will try to find the operations that used the parameter as input.

• dst (Any) - The destination input. It can be a tuple of operations output or a single operation output. We do not concern about the input data, but concern about the operation that generates the input data. If depend_mode = 1 is specified and the source input is parameter, we will try to find the operations that used the parameter as input.

Outputs:

Bool. This operation has no actual data output, it will be used to setup the order of relative operations.

Examples

>>> # In the following example, the data calculation uses original global_step. After the calculation the global
>>> # step should be increased, so the add operation should depend on the data calculation operation.
>>> class Net(nn.Cell):
>>>     def __init__(self):
>>>        super(Net, self).__init__()
>>>         self.global_step = Parameter(initializer(0, [1]), name="global_step")
>>>         self.rate = 0.2
>>>         self.control_depend = ControlDepend()
>>>
>>>     def construct(self, x):
>>>         data = self.rate * self.global_step + x
>>>         added_global_step = self.global_step + 1
>>>         return data

class mindspore.ops.operations.Conv2D(*args, **kwargs)[source]

2D convolution layer.

Applies a 2D convolution over an input tensor which is typically of shape $$(N, C_{in}, H_{in}, W_{in})$$, where $$N$$ is batch size and $$C_{in}$$ is channel number. For each batch of shape $$(C_{in}, H_{in}, W_{in})$$, the formula is defined as:

$out_j = \sum_{i=0}^{C_{in} - 1} ccor(W_{ij}, X_i) + b_j,$

where $$ccor$$ is cross correlation operator, $$C_{in}$$ is the input channel number, $$j$$ ranges from $$0$$ to $$C_{out} - 1$$, $$W_{ij}$$ corresponds to $$i$$-th channel of the $$j$$-th filter and $$out_{j}$$ corresponds to the $$j$$-th channel of the output. $$W_{ij}$$ is a slice of kernel and it has shape $$(\text{ks_h}, \text{ks_w})$$, where $$\text{ks_h}$$ and $$\text{ks_w}$$ are height and width of the convolution kernel. The full kernel has shape $$(C_{out}, C_{in} // \text{group}, \text{ks_h}, \text{ks_w})$$, where group is the group number to split the input in the channel dimension.

If the ‘pad_mode’ is set to be “valid”, the output height and width will be $$\left \lfloor{1 + \frac{H_{in} + 2 \times \text{padding} - \text{ks_h} - (\text{ks_h} - 1) \times (\text{dilation} - 1) }{\text{stride}}} \right \rfloor$$ and $$\left \lfloor{1 + \frac{W_{in} + 2 \times \text{padding} - \text{ks_w} - (\text{ks_w} - 1) \times (\text{dilation} - 1) }{\text{stride}}} \right \rfloor$$ respectively.

The first introduction can be found in paper Gradient Based Learning Applied to Document Recognition. More detailed introduction can be found here: http://cs231n.github.io/convolutional-networks/.

Parameters
• out_channel (int) – The dimension of the output.

• kernel_size (Union[int, tuple[int]]) – The kernel size of the 2D convolution.

• mode (int) – 0 Math convolutiuon, 1 cross-correlation convolution , 2 deconvolution, 3 depthwise convolution. Default: 1.

• stride (int) – The stride to apply conv filter. Default: 1.

• dilation (int) – Specify the space to use between kernel elements. Default: 1.

• group (int) – Split input into groups. Default: 1.

Returns

Tensor, the value that applied 2D convolution.

Inputs:
• input (Tensor) - Tensor of shape $$(N, C_{in}, H_{in}, W_{in})$$.

• weight (Tensor) - Set size of kernel is $$(K_1, K_2)$$, then the shape is $$(C_{out}, C_{in}, K_1, K_2)$$.

Outputs:

Tensor of shape $$(N, C_{out}, H_{out}, W_{out})$$.

class mindspore.ops.operations.Conv2DBackpropInput(*args, **kwargs)[source]

Computes the gradients of convolution with respect to the input.

Parameters
• out_channel (int) – The dimensionality of the output space.

• kernel_size (Union[int, tuple[int]]) – The size of the convolution window.

• mode (int) – 0 Math convolutiuon, 1 cross-correlation convolution , 2 deconvolution, 3 depthwise convolution. Default: 1.

• stride (int) – The stride to apply conv filter. Default: 1.

• dilation (int) – Specifies the dilation rate to use for dilated convolution. Default: 1.

• group (int) – Splits input into groups. Default: 1.

Returns

class mindspore.ops.operations.Cos(*args, **kwargs)[source]

Computes cosine of input element-wise.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

Outputs:

Tensor, has the same shape as input_x.

Examples

>>> cos = Cos()
>>> X = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), ms.float32)
>>> output = cos(X)

class mindspore.ops.operations.CumProd(*args, **kwargs)[source]

Compute the cumulative product of the tensor x along axis.

Parameters
• exclusive (bool) – If True, perform exclusive cumulative product. Default: False.

• reverse (bool) – If True, reverse the result along axis. Default: False

Inputs:
• input_x (Tensor[Number]) - The input tensor.

• axis (int) - The dimensions to compute the cumulative product.

Outputs:

Tensor, has the same shape and dtype as the ‘input_x’.

Examples

>>> data = Tensor(np.array([a, b, c]).astype(np.float32))
>>> op0 = CumProd()
>>> output = op0(data, 0) # output=[a, a * b, a * b * c]
>>> op1 = CumProd(exclusive=True)
>>> output = op1(data, 0) # output=[1, a, a * b]
>>> op2 = CumProd(reverse=True)
>>> output = op2(data, 0) # output=[a * b * c, b * c, c]
>>> op3 = CumProd(exclusive=True, reverse=True)
>>> output = op3(data, 0) # output=[b * c, c, 1]

class mindspore.ops.operations.CumSum(*args, **kwargs)[source]

Computes the cumulative sum of input tensor along axis.

Parameters
• exclusive (bool) – If True, perform exclusive mode. Default: False.

• reverse (bool) – If True, perform inverse cumulative sum. Default: False.

Inputs:
• input (Tensor) - The input tensor to accumulate.

• axis (int) - The axis to accumulate the tensor’s value.

Outputs:

Tensor, the shape of the output tensor is consistent with the input tensor’s.

Examples

>>> input = Tensor(np.array([[3, 4, 6, 10],[1, 6, 7, 9],[4, 3, 8, 7],[1, 3, 7, 9]]).astype(np.float32))
>>> cumsum = CumSum()
>>> output = cumsum(input, 1)
[[ 3.  7. 13. 23.]
[ 1.  7. 14. 23.]
[ 4.  7. 15. 22.]
[ 1.  4. 11. 20.]]

class mindspore.ops.operations.DType(*args, **kwargs)[source]

Returns the data type of input tensor as mindspore.dtype.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

Outputs:

mindspore.dtype, the data type of a tensor.

Examples

>>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
>>> type = DType()(input_tensor)

class mindspore.ops.operations.DepthToSpace(*args, **kwargs)[source]

Rearrange blocks of depth data into spatial dimensions.

This is the reverse operation of SpaceToDepth.

The output tensor’s height dimension is $$height * block\_size$$.

The output tensor’s weight dimension is $$weight * block\_size$$.

The depth of output tensor is $$input\_depth / (block\_size * block\_size)$$.

The input tensor’s depth must be divisible by block_size * block_size. The data format is “NCHW”.

Parameters

block_size (int) – The block size used to divide depth data. It must be >= 2.

Inputs:
• x (Tensor) - The target tensor.

Outputs:

Tensor, the same type as x.

Examples

>>> x = Tensor(np.random.rand(1,12,1,1), mindspore.float32)
>>> block_size = 2
>>> op = DepthToSpace(block_size)
>>> output = op(x)
>>> output.asnumpy().shape == (1,3,2,2)

class mindspore.ops.operations.DepthwiseConv2dNative(*args, **kwargs)[source]

Returns the depth-wise convolution value for the input.

Applies depthwise conv2d for the input, which will generate more channels with channel_multiplier. Given an input tensor of shape $$(N, C_{in}, H_{in}, W_{in})$$ where $$N$$ is the batch size and a filter tensor with kernel size $$(ks_{h}, ks_{w})$$, containing $$C_{in} * \text{channel_multiplier}$$ convolutional filters of depth 1; it applies different filters to each input channel (channel_multiplier channels for each with default value 1), then concatenates the results together. The output has $$\text{in_channels} * \text{channel_multiplier}$$ channels.

Parameters
• channel_multiplier (int) – The multipiler for the original output conv.

• kernel_size (int or tuple) – The size of the conv kernel.

• mode (int) – 0 Math convolution, 1 cross-correlation convolution , 2 deconvolution, 3 depthwise convolution. Default: 3.

• stride (int) – The stride to apply conv filter. Default: 1.

• dilation (int) – Specifies the dilation rate to use for dilated convolution. Default: 1.

• group (int) – Splits input into groups. Default: 1.

Inputs:
• input (Tensor) - Tensor of shape $$(N, C_{in}, H_{in}, W_{in})$$.

• weight (Tensor) - Set size of kernel is $$(K_1, K_2)$$, then the shape is $$(C_{out}, C_{in}, K_1, K_2)$$.

Outputs:

Tensor of shape $$(N, C_{in} * \text{channel_multiplier}, H_{out}, W_{out})$$.

class mindspore.ops.operations.Diag(*args, **kwargs)[source]

Construct a diagonal tensor with a given diagonal values.

Assume input_x has dimensions $$[D_1,... D_k]$$, the output is a tensor of rank 2k with dimensions $$[D_1,..., D_k, D_1,..., D_k]$$ where: $$output[i_1,..., i_k, i_1,..., i_k] = input_x[i_1,..., i_k]$$ and 0 everywhere else.

Inputs:
• input_x (Tensor) - The input tensor.

Outputs:

Tensor.

Examples

>>> input_x = Tensor([1, 2, 3, 4])
>>> diag = P.Diag()
>>> diag(x)
[[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]]

class mindspore.ops.operations.DiagPart(*args, **kwargs)[source]

Extract the diagonal part from given tensor.

Assume input has dimensions $$[D_1,..., D_k, D_1,..., D_k]$$, the output is a tensor of rank k with dimensions $$[D_1,..., D_k]$$ where: $$output[i_1,..., i_k] = input[i_1,..., i_k, i_1,..., i_k]$$.

Inputs:
• input_x (Tensor) - The input Tensor.

Outputs:

Tensor.

Examples
>>> input_x = Tensor([[1, 0, 0, 0],
>>>                   [0, 2, 0, 0],
>>>                   [0, 0, 3, 0],
>>>                   [0, 0, 0, 4]])
>>> diag_part = P.DiagPart()
>>> diag_part(x)
[1, 2, 3, 4]

class mindspore.ops.operations.Div(*args, **kwargs)[source]

Computes the quotient of dividing the first input tensor by the second input tensor element-wise.

The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be same. When the inputs are one tensor and one scalar, the scalar cannot be a parameter, only can be a constant, and the type of the scalar is the same as the data type of the tensor.

Inputs:
• input_x (Union[Tensor, Number]) - The first input is a tensor whose data type is number or a number.

• input_y (Union[Tensor, Number]) - The second input is a tensor whose data type is same as ‘input_x’ or a number.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is same as ‘input_x’.

Raises

ValueError – When input_x and input_y are not the same dtype.

Examples

>>> input_x = Tensor(np.array([-4.0, 5.0, 6.0]), mindspore.float32)
>>> input_y = Tensor(np.array([3.0, 2.0, 3.0]), mindspore.float32)
>>> div = Div()
>>> div(input_x, input_y)
[-2.0, 2.0, 2.0]

class mindspore.ops.operations.DropoutDoMask(*args, **kwargs)[source]

Applies dropout mask on the input tensor.

Take the mask output of DropoutGenMask as input, and apply dropout on the input.

Inputs:
• input_x (Tensor) - The input tensor.

• mask (Tensor) - The mask to be applied on input_x, which is the output of DropoutGenMask. And the shape of input_x must be same as the value of DropoutGenMask’s input shape. If input wrong mask, the output of DropoutDoMask are unpredictable.

• keep_prob (Tensor) - The keep rate, between 0 and 1, e.g. keep_prob = 0.9, means dropping out 10% of input units. The value of keep_prob is same as the input keep_prob of DropoutGenMask.

Outputs:

Tensor, the value that applied dropout on.

Examples

>>> x = Tensor(np.ones([20, 16, 50]), mindspore.float32)
>>> shape = (20, 16, 50)
>>> keep_prob = Tensor(0.5, mindspore.float32)
>>> assert output.shape() == (20, 16, 50)

class mindspore.ops.operations.DropoutGenMask(*args, **kwargs)[source]

Generates the mask value for the input shape.

Parameters
• Seed0 (int) – Seed0 value for random generating. Default: 0.

• Seed1 (int) – Seed1 value for random generating. Default: 0.

Inputs:
• shape (tuple[int]) - The shape of target mask.

• keep_prob (Tensor) - The keep rate, between 0 and 1, e.g. keep_prob = 0.9, means dropping out 10% of input units.

Outputs:

Tensor, the value of generated mask for input shape.

Examples

>>> dropout_gen_mask = DropoutGenMask()
>>> shape = (20, 16, 50)
>>> keep_prob = Tensor(0.5, mindspore.float32)

class mindspore.ops.operations.Equal(*args, **kwargs)[source]

Computes the equivalence between two tensors element-wise.

The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be same. When the inputs are one tensor and one scalar, the scalar cannot be a parameter, only can be a constant, and the type of the scalar is the same as the data type of the tensor.

Inputs:
• input_x (Union[Tensor, Number, bool]) - The first input is a tensor whose data type is number or bool, or a number or a bool object.

• input_y (Union[Tensor, Number, bool]) - The second input tensor whose data type is same as ‘input_x’ or a number or a bool object.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is bool.

Examples

>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.float32)
>>> equal = Equal()
>>> equal(input_x, 2.0)
[False, True, False]
>>>
>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
>>> input_y = Tensor(np.array([1, 2, 4]), mindspore.int32)
>>> equal = Equal()
>>> equal(input_x, input_y)
[True, True, False]

class mindspore.ops.operations.EqualCount(*args, **kwargs)[source]

Computes the number of the same elements of two tensors.

The two input tensors should have same shape.

Inputs:
• input_x (Tensor) - The first input tensor.

• input_y (Tensor) - The second input tensor.

Outputs:

Tensor, has the same shape as the input_x.

Examples

>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
>>> input_y = Tensor(np.array([1, 2, 4]), mindspore.int32)
>>> equal_count = EqualCount()
>>> equal_count(input_x, input_y)
[2]

class mindspore.ops.operations.Exp(*args, **kwargs)[source]

Returns exponential of a tensor element-wise.

Inputs:
• input_x (Tensor) - The input tensor.

Outputs:

Tensor, has the same shape as the input_x.

Examples

>>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
>>> exp = Exp()
>>> exp(input_x)
[ 2.71828183,  7.3890561 , 54.59815003]

class mindspore.ops.operations.ExpandDims(*args, **kwargs)[source]

Note

If the specified axis is a negative number, the index is counted backward from the end and starts at 1.

Raises

ValueError – If axis is not an integer or not in the valid range.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

• axis (int) - Specifies the dimension index at which to expand the shape of input_x. The value of axis must be in the range [-input_x.dim()-1, input_x.dim()]. Only constant value is allowed.

Outputs:

Tensor, the shape of tensor is $$(1, x_1, x_2, ..., x_R)$$ if the value of axis is 0.

Examples

>>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
>>> expand_dims = ExpandDims()
>>> output = expand_dims(input_tensor, 0)

class mindspore.ops.operations.Eye(*args, **kwargs)[source]

Creates a tensor with ones on the diagonal and zeros elsewhere.

Inputs:
• n (int) - Number of rows of returned tensor

• m (int) - Number of columns of returned tensor

• t (mindspore.dtype) - Mindspore’s dtype, The data type of the returned tensor.

Outputs:

Tensor, a tensor with ones on the diagonal and zeros elsewhere.

Examples

>>> eye = P.Eye()
>>> out_tensor = eye(2, 2, mindspore.int32)

class mindspore.ops.operations.Fill(*args, **kwargs)[source]

Creates a tensor filled with a scalar value.

Creates a tensor with shape described by the first argument and fills it with values in the second argument.

Inputs:
• type (mindspore.dtype) - The specified type of output tensor. Only constant value is allowed.

• shape (tuple) - The specified shape of output tensor. Only constant value is allowed.

• value (scalar) - Value to fill the returned tensor. Only constant value is allowed.

Outputs:

Tensor, has the same type and shape as input value.

Examples

>>> fill = P.Fill()
>>> fill(P.DType()(x), (2, 2), 1)

class mindspore.ops.operations.Flatten(*args, **kwargs)[source]

Flattens a tensor without changing its batch size on the 0-th axis.

Inputs:
• input_x (Tensor) - Tensor of shape $$(N, \ldots)$$ to be flattened.

Outputs:

Tensor, the shape of the output tensor is $$(N, X)$$, where $$X$$ is the product of the remaining dimension.

Examples

>>> input_tensor = Tensor(np.ones(shape=[1, 2, 3, 4]), mindspore.float32)
>>> flatten = Flatten()
>>> output = flatten(input_tensor)
>>> assert output.shape() == (1, 24)

class mindspore.ops.operations.Floor(*args, **kwargs)[source]

Round a tensor down to the closest integer element-wise.

Inputs:
• input_x (Tensor) - The input tensor. Its element data type must be float.

Outputs:

Tensor, has the same shape as input_x.

Examples

>>> input_x = Tensor(np.array([1.1, 2.5, -1.5]), mindspore.float32)
>>> floor = Floor()
>>> floor(input_x)
[1.0, 2.0, -2.0]

class mindspore.ops.operations.FloorDiv(*args, **kwargs)[source]

Divide the first input tensor by the second input tensor element-wise and rounds down to the closest integer.

The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be same. When the inputs are one tensor and one scalar, the scalar cannot be a parameter, only can be a constant, and the type of the scalar is the same as the data type of the tensor.

Inputs:
• input_x (Union[Tensor, Number]) - The first input is a tensor whose data type is number or a number.

• input_y (Union[Tensor, Number]) - The second input is a tensor whose data type is same as ‘input_x’ or a number.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is same as ‘input_x’.

Examples

>>> input_x = Tensor(np.array([2, 4, -1]), mindspore.int32)
>>> input_y = Tensor(np.array([3, 3, 3]), mindspore.int32)
>>> floor_div = FloorDiv()
>>> floor_div(input_x, input_y)
[0, 1, -1]

class mindspore.ops.operations.FusedBatchNorm(*args, **kwargs)[source]

FusedBatchNorm is a BatchNorm that moving mean and moving variance will be computed instead of being loaded.

Batch Normalization is widely used in convolutional networks. This operation applies Batch Normalization over input to avoid internal covariate shift as described in the paper Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift. It rescales and recenters the feature using a mini-batch of data and the learned parameters which can be described in the following formula.

$y = \frac{x - mean}{\sqrt{variance + \epsilon}} * \gamma + \beta$

where $$\gamma$$ is scale, $$\beta$$ is bias, $$\epsilon$$ is epsilon.

Parameters
• mode (int) – Mode of batch normalization, value is 0 or 1. Default: 0.

• epsilon (float) – A small value added for numerical stability. Default: 1e-5.

• momentum (float) – The hyper parameter to compute moving average for running_mean and running_var (e.g. $$new\_running\_mean = momentum * running\_mean + (1 - momentum) * current\_mean$$). Momentum value should be [0, 1]. Default: 0.9.

Inputs:
• input_x (Tensor) - Tensor of shape $$(N, C)$$.

• scale (Tensor) - Tensor of shape $$(C,)$$.

• bias (Tensor) - Tensor of shape $$(C,)$$.

• mean (Tensor) - Tensor of shape $$(C,)$$.

• variance (Tensor) - Tensor of shape $$(C,)$$.

Outputs:

Tuple of 5 Tensor, the normalized input and the updated parameters.

• output_x (Tensor) - The same type and shape as the input_x.

• updated_scale (Tensor) - Tensor of shape $$(C,)$$.

• updated_bias (Tensor) - Tensor of shape $$(C,)$$.

• updated_moving_mean (Tensor) - Tensor of shape $$(C,)$$.

• updated_moving_variance (Tensor) - Tensor of shape $$(C,)$$.

class mindspore.ops.operations.GatherNd(*args, **kwargs)[source]

Gathers slices from a tensor by indices.

Using given indices to gather slices from a tensor with a specified shape.

Inputs:
• input_x (Tensor) - The target tensor to gather values.

• indices (Tensor) - The index tensor.

Outputs:

Tensor, has the same type as input_x and the shape is indices_shape[:-1] + x_shape[indices_shape[-1]:].

Examples

>>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
>>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
>>> op = GatherNd()
>>> output = op(input_x, indices)

class mindspore.ops.operations.GatherV2(*args, **kwargs)[source]

Returns a slice of input tensor based on the specified indices and axis.

Inputs:
• input_params (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$. The original Tensor.

• input_indices (Tensor) - The shape of tensor is $$(y_1, y_2, ..., y_S)$$. Specifies the indices of elements of the original Tensor. Must be in the range [0, input_param.shape()[axis]).

• axis (int) - Specifies the dimension index to gather indices.

Outputs:

Tensor, the shape of tensor is $$(z_1, z_2, ..., z_N)$$.

Examples

>>> params = Tensor(np.array([[1, 2, 7, 42], [3, 4, 54, 22], [2, 2, 55, 3]]), mindspore.float32)
>>> indices = Tensor(np.array([1, 2]), mindspore.int32)
>>> axis = 1
>>> out = GatherV2()(params, indices, axis)

class mindspore.ops.operations.GeSwitch(*args, **kwargs)[source]

Switch data to flow into false or true branch depend on the condition. If the condition is true, the true branch will be activated, or vise verse.

Inputs:
• data (Tensor) - The data to be used for switch control.

• pred (Tensor) - It should be a scalar whose type is bool and shape is (), It is used as condition for switch control.

Outputs:

tuple. Output is tuple(false_output, true_output). The Elements in the tuple has the same shape of input data. The false_output connects with the false_branch and the true_output connects with the true_branch.

Examples

>>> class Net(nn.Cell):
>>>     def __init__(self):
>>>         super(Net, self).__init__()
>>>         self.square = P.Square()
>>>         self.value = Tensor(np.full((1), 3, dtype=np.float32))
>>>         self.switch = P.GeSwitch()
>>>         self.merge = P.Merge()
>>>         self.less = P.Less()
>>>
>>>     def construct(self, x, y):
>>>         cond = self.less(x, y)
>>>         st1, sf1 = self.switch(x, cond)
>>>         st2, sf2 = self.switch(y, cond)
>>>         st3, sf3 = self.switch(self.value, cond)
>>>         sq_ret = self.square(sf3)
>>>         return ret[0]
>>>
>>> x = Tensor(x_init, dtype=mindspore.float32)
>>> y = Tensor(y_init, dtype=mindspore.float32)
>>> net = Net()
>>> output = net(x, y)

class mindspore.ops.operations.Gelu(*args, **kwargs)[source]

Gaussian Error Linear Units activation function.

GeLU is described in the paper Gaussian Error Linear Units (GELUs). And also please refer to BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding..

Defined as follows:

$\text{output} = 0.5 * x * (1 + erf(x / \sqrt{2})),$

where $$erf$$ is the “Gauss error function” .

Inputs:
• input_x (Tensor) - Input to compute the Gelu.

Outputs:

Tensor, with the same type and shape as input.

Examples

>>> tensor = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
>>> gelu = Gelu()
>>> result = gelu(tensor)

class mindspore.ops.operations.GetNext(*args, **kwargs)[source]

Returns the next element in the dataset queue.

Note

GetNext op needs to be associated with network and also depends on the init_dataset interface, it can’t be used directly as a single op. For details, please refer to nn.cell_wrapper.DataWrapper source code.

Parameters
• types (list[mindspore.dtype]) – The type of the outputs.

• shapes (list[tuple[int]]) – The dimensionality of the outputs.

• output_num (int) – The output number, length of types and shapes.

• shared_name (str) – The queue name of init_dataset interface.

Inputs:

No inputs.

Outputs:

tuple[Tensor], the output of Dataset. The shape is described in shapes and the type is described is types.

Examples

>>> get_next = GetNext([mindspore.float32, mindspore.int32], [[32, 1, 28, 28], [10]], 'shared_name')
>>> feature, label = get_next()

class mindspore.ops.operations.Greater(*args, **kwargs)[source]

Computes the boolean value of $$x > y$$ element-wise.

The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be same. When the inputs are one tensor and one scalar, the scalar cannot be a parameter, only can be a constant, and the type of the scalar is the same as the data type of the tensor.

Inputs:
• input_x (Union[Tensor, Number]) - The first input is a tensor whose data type is number or a number.

• input_y (Union[Tensor, Number]) - The second input is a tensor whose data type is same as ‘input_x’ or a number.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is same as ‘input_x’.

Examples

>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
>>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
>>> greater = Greater()
>>> greater(input_x, input_y)
[False, True, False]

class mindspore.ops.operations.GreaterEqual(*args, **kwargs)[source]

Computes the boolean value of $$x >= y$$ element-wise.

The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be same. When the inputs are one tensor and one scalar, the scalar cannot be a parameter, only can be a constant, and the type of the scalar is the same as the data type of the tensor.

Inputs:
• input_x (Union[Tensor, Number]) - The first input is a tensor whose data type is number or a number.

• input_y (Union[Tensor, Number]) - The second input is a tensor whose data type is same as ‘input_x’ or a number.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is bool’.

Examples

>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
>>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
>>> greater_equal = GreaterEqual()
>>> greater_equal(input_x, input_y)
[True, True, False]

class mindspore.ops.operations.IOU(*args, **kwargs)[source]

Calculate intersection over union for boxes.

Calculate the specific value of overlap and union of the boxes.

Parameters

mode (string) – The mode is used to specify the calculation method, now support ‘iou’ (intersection over union) or ‘iof’ (intersection over foreground) mode. Default: ‘iou’.

Inputs:
• anchor_boxes (Tensor) - Anchor boxes, tensor of shape (N, 4).

• gt_boxes (Tensor) - Ground truth boxes, tensor of shape (M, 4).

Outputs:

Tensor, the ‘iou’ values, tensor of shape (M, N).

Examples

>>> iou = IOU()
>>> anchor_boxes = Tensor(np.random.randint(1,5, [10, 4]))
>>> gt_boxes = Tensor(np.random.randint(1,5, [3, 4]))
>>> iou(anchor_boxes, gt_boxes)

class mindspore.ops.operations.ImageSummary(*args, **kwargs)[source]

Output image tensor to protocol buffer through image summary operator.

Inputs:
• name (str) - The name of the input variable.

• value (Tensor) - The value of image.

Examples

>>> class Net(nn.Cell):
>>>     def __init__(self):
>>>         super(Net, self).__init__()
>>>         self.summary = P.ImageSummary()
>>>
>>>     def construct(self, x):
>>>         name = "image"
>>>         out = self.summary(name, x)
>>>         return out

class mindspore.ops.operations.InsertGradientOf(*args, **kwargs)[source]

Attach callback to graph node that will be invoked on the node’s gradient.

Parameters

f (Function) – MindSpore’s Function. Callback function.

Inputs:
• input_x (Tensor) - The graph node to attach to.

Outputs:

Tensor, returns input_x directly. InsertGradientOf does not affect the forward result.

Examples

>>> def clip_gradient(dx):
>>>     ret = dx
>>>     if ret > 1.0:
>>>         ret = 1.0
>>>
>>>     if ret < 0.2:
>>>         ret = 0.2
>>>
>>>     return ret
>>>
>>>     def clip_test(x, y):
>>>         x = clip(x)
>>>         y = clip(y)
>>>         c = x * y
>>>         return c
>>>
>>>     @ms_function
>>>     def f(x, y):
>>>         return clip_test(x, y)
>>>
>>>     def fd(x, y):
>>>
>>>     print("forward: ", f(1.1, 0.1))

class mindspore.ops.operations.InvertPermutation(*args, **kwargs)[source]

Computes the inverse of an index permutation.

Given a tuple input, this operation inserts a dimension of 1 at the dimension This operation calculates the inverse of the index replacement. It requires a 1-dimensional tuple x, which represents the array starting at zero, and swaps each value with its index position. In other words, for the output tuple y and the input tuple x, this operation calculates the following: $$y[x[i]] = i, \quad i \in [0, 1, \ldots, \text{len}(x)-1]$$.

Note

These values must include 0. There must be no duplicate values and the values can not be negative.

Inputs:
• input_x (tuple[int]) - The input tuple is constructed by multiple integers, i.e., $$(y_1, y_2, ..., y_S)$$ representing the indices. The values must include 0. There can be no duplicate values or negative values.

Outputs:

tuple[int]. the lenth is same as input.

Examples

>>> invert = InvertPermutation()
>>> input_data = (3, 4, 0, 2, 1)
>>> output = invert(input_data)
>>> output == (2, 4, 3, 0, 1)

class mindspore.ops.operations.IsInstance(*args, **kwargs)[source]

Check whether an object is an instance of a target type.

Inputs:
• inst (Any Object) - The instance to be check. Only constant value is allowed.

• type_ (mindspore.dtype) - The target type. Only constant value is allowed.

Outputs:

bool, the check result.

Examples

>>> a = 1
>>> result = IsInstance()(a, mindspore.int32)

class mindspore.ops.operations.IsSubClass(*args, **kwargs)[source]

Check whether one type is sub class of another type.

Inputs:
• sub_type (mindspore.dtype) - The type to be check. Only constant value is allowed.

• type_ (mindspore.dtype) - The target type. Only constant value is allowed.

Outputs:

bool, the check result.

Examples

>>> result = IsSubClass()(mindspore.int32,  mindspore.intc)

class mindspore.ops.operations.L2Normalize(*args, **kwargs)[source]

L2 normalization Operator.

This operator will normalizes the input using the given axis. The function is shown as follows:

$\text{output} = \frac{x}{\sqrt{\text{max}(\text{sum} (\text{input_x}^2), \epsilon)}},$

where $$\epsilon$$ is epsilon.

Parameters
• axis (int) – The begin axis for the input to apply L2 normalize. Default: 0.

• epsilon (float) – A small value added for numerical stability. Default: 1e-4.

Inputs:
• input_x (Tensor) - Input to compute the normalization.

Outputs:

Tensor, with the same type and shape as the input.

class mindspore.ops.operations.LARSUpdate(*args, **kwargs)[source]

Conduct lars (layer-wise adaptive rate scaling) update on the square sum of gradient.

Parameters
• epsilon (float) – Term added to the denominator to improve numerical stability. Default: 1e-05.

• hyperpara (float) – Trust coefficient for calculating the local learning rate. Default: 0.001.

• use_clip (bool) – Whether to use clip operation for calculating the local learning rate. Default: False.

Inputs:
• weight (Tensor) - The weight to be updated.

• gradient (Tensor) - The gradient of weight, which has the same shape and dtype with weight.

• norm_weight (Tensor) - A scalar tensor, representing the square sum of weight.

• norm_gradient (Tensor) - A scalar tensor, representing the square sum of gradient.

• weight_decay (Union[Number, Tensor]) - Weight decay. It should be a scalar tensor or number.

• learning_rate (Union[Number, Tensor]) - Learning rate. It should be a scalar tensor or number.

Outputs:

class mindspore.ops.operations.LSTM(*args, **kwargs)[source]

Performs the long short term memory(LSTM) on the input.

Detailed information, please refer to nn.LSTM.

class mindspore.ops.operations.LayerNorm(*args, **kwargs)[source]

Applies the Layer Normalization to the input tensor.

This operator will normalize the input tensor on given axis. LayerNorm is described in the paper Layer Normalization.

$y = \frac{x - mean]}{\sqrt{variance + \epsilon}} * \gamma + \beta$

where $$\gamma$$ is scale, $$\beta$$ is bias, $$\epsilon$$ is epsilon.

Parameters
• begin_norm_axis (int) – The begin axis of the input_x to apply LayerNorm, the value should be in [-1, rank(input)). Default: 1.

• begin_params_axis (int) – The begin axis of the parameter input (gamma, beta) to apply LayerNorm, the value should be in [-1, rank(input)). Default: 1.

Inputs:
• input_x (Tensor) - Tensor of shape $$(N, \ldots)$$. The input of LayerNorm.

• gamma (Tensor) - Tensor of shape $$(P_0, \ldots, P_\text{begin_params_axis})$$. The learnable parameter gamma as the scale on norm.

• beta (Tensor) - Tensor of shape $$(P_0, \ldots, P_\text{begin_params_axis})$$. The learnable parameter beta as the scale on norm.

Outputs:

tuple[Tensor], tuple of 3 tensors, the normalized input and the updated parameters.

• output_x (Tensor) - The normalized input, has the same type and shape as the input_x. The shape is $$(N, C)$$.

• updated_gamma (Tensor) - Tensor of shape $$(C,)$$.

• updated_beta (Tensor) - Tensor of shape $$(C,)$$.

class mindspore.ops.operations.Less(*args, **kwargs)[source]

Computes the boolean value of $$x < y$$ element-wise.

The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be same. When the inputs are one tensor and one scalar, the scalar cannot be a parameter, only can be a constant, and the type of the scalar is the same as the data type of the tensor.

Inputs:
• input_x (Union[Tensor, Number]) - The first input is a tensor whose data type is number or a number.

• input_y (Union[Tensor, Number]) - The second input is a tensor whose data type is same as ‘input_x’ or a number.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is bool.

Examples

>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
>>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
>>> less = Less()
>>> less(input_x, input_y)
[False, False, True]

class mindspore.ops.operations.LessEqual(*args, **kwargs)[source]

Computes the boolean value of $$x <= y$$ element-wise.

The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be same. When the inputs are one tensor and one scalar, the scalar cannot be a parameter, only can be a constant, and the type of the scalar is the same as the data type of the tensor.

Inputs:
• input_x (Union[Tensor, Number]) - The first input is a tensor whose data type is number or a number.

• input_y (Union[Tensor, Number]) - The second input is a tensor whose data type is same as ‘input_x’ or a number.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is bool.

Examples

>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
>>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
>>> less_equal = LessEqual()
>>> less_equal(input_x, input_y)
[True, False, True]

class mindspore.ops.operations.Log(*args, **kwargs)[source]

Returns the natural logarithm of a tensor element-wise.

Inputs:
• input_x (Tensor) - The input tensor.

Outputs:

Tensor, has the same shape as the input_x.

Examples

>>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
>>> log = Log()
>>> log(input_x)
[0.0, 0.69314718, 1.38629436]

class mindspore.ops.operations.LogSoftmax(*args, **kwargs)[source]

Log Softmax activation function.

Applies the Log Softmax function to the input tensor on the specified axis. Suppose a slice along the given aixs $$x$$ then for each element $$x_i$$ the Log Softmax function is shown as follows:

$\text{output}(x_i) = \log \left(\frac{exp(x_i)} {\sum_{j = 0}^{N-1}\exp(x_j)}\right),$

where $$N$$ is the length of the Tensor.

Parameters

axis (int) – The axis to do the Log softmax operation. Default: -1.

Inputs:
• logits (Tensor) - The input of Log Softmax.

Outputs:

Tensor, with the same type and shape as the logits.

class mindspore.ops.operations.LogicalAnd(*args, **kwargs)[source]

Computes the “logical AND” of two tensors element-wise.

The inputs must be two tensors or one tensor and one bool object. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be bool. When the inputs are one tensor and one bool object, the bool object cannot be a parameter, only can be a constant, and the data type of the tensor should be bool.

Inputs:
• input_x (Union[Tensor, bool]) - The first input is a tensor whose data type is bool or a bool object.

• input_y (Union[Tensor, bool]) - The second input is a tensor whose data type is bool or a bool object.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is bool.

Examples

>>> input_x = Tensor(np.array([True, False, True]), mindspore.bool_)
>>> input_y = Tensor(np.array([True, True, False]), mindspore.bool_)
>>> logical_and = LogicalAnd()
>>> logical_and(input_x, input_y)
[True, False, False]

class mindspore.ops.operations.LogicalNot(*args, **kwargs)[source]

Computes the “logical NOT” of a tensor element-wise.

Inputs:
• input_x (Tensor) - The input tensor whose dtype is bool

Outputs:

Tensor, the shape is same as the input_x, and the dtype is bool.

Examples

>>> input_x = Tensor(np.array([True, False, True]), mindspore.bool_)
>>> logical_not = LogicalNot()
>>> logical_not(input_x)
[False, True, False]

class mindspore.ops.operations.LogicalOr(*args, **kwargs)[source]

Computes the “logical OR” of two tensors element-wise.

The inputs must be two tensors or one tensor and one bool object. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be bool. When the inputs are one tensor and one bool object, the bool object cannot be a parameter, only can be a constant, and the data type of the tensor should be bool.

Inputs:
• input_x (Union[Tensor, bool]) - The first input is a tensor whose data type is bool or a bool object.

• input_y (Union[Tensor, bool]) - The second input is a tensor whose data type is bool or a bool object.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is bool.

Examples

>>> input_x = Tensor(np.array([True, False, True]), mindspore.bool_)
>>> input_y = Tensor(np.array([True, True, False]), mindspore.bool_)
>>> logical_or = LogicalOr()
>>> logical_or(input_x, input_y)
[True, True, True]

class mindspore.ops.operations.MakeRefKey(*args, **kwargs)[source]

Make a RefKey instance by string. RefKey stores the name of Parameter, can be passed through the functions, and used for Assign target.

Parameters

tag (str) – Parameter name to make the RefKey.

Inputs:

No input.

Outputs:

RefKeyType, made from the Parameter name.

Examples

>>> from mindspore.ops import functional as F
>>> class Net(nn.Cell):
>>>     def __init__(self):
>>>         super(Net, self).__init__()
>>>         self.y = Parameter(Tensor(np.ones([6, 8, 10], np.int32)), name="y")
>>>         self.make_ref_key = MakeRefKey("y")
>>>
>>>     def construct(self, x):
>>>         key = self.make_ref_key()
>>>         ref = F.make_ref(key, x, self.y)
>>>         return ref + x
>>>
>>> x = Tensor(np.ones([3, 4, 5], np.int32))
>>> net = Net()
>>> net(x)

class mindspore.ops.operations.MatMul(*args, **kwargs)[source]

Multiplies matrix a by matrix b.

The rank of input tensors must be 2.

Parameters
• transpose_a (bool) – If True, a is transposed before multiplication. Default: False.

• transpose_b (bool) – If True, b is transposed before multiplication. Default: False.

Inputs:
• input_x (Tensor) - The first tensor to be multiplied. The shape of the tensor is $$(N, C)$$. If transpose_a is True, its shape should be $$(N, C)$$ after transposing.

• input_y (Tensor) - The second tensor to be multiplied. The shape of the tensor is $$(C, M)$$. If transpose_b is True, its shape should be $$(C, M)$$ after transpose.

Outputs:

Tensor, the shape of the output tensor is $$(N, M)$$.

Examples

>>> input_x = Tensor(np.ones(shape=[1, 3]), mindspore.float32)
>>> input_y = Tensor(np.ones(shape=[3, 4]), mindspore.float32)
>>> matmul = MatMul()
>>> output = matmul(input_x, input_y)

class mindspore.ops.operations.MaxPool(*args, **kwargs)[source]

Max pooling operation.

Applies a 2D max pooling over an input Tensor which can be regarded as a composition of 2D planes.

Typically the input is of shape $$(N_{in}, C_{in}, H_{in}, W_{in})$$, MaxPool outputs regional maximum in the $$(H_{in}, W_{in})$$-dimension. Given kernel size $$ks = (h_{ker}, w_{ker})$$ and stride $$s = (s_0, s_1)$$, the operation is as follows.

$\text{output}(N_i, C_j, h, w) = \max_{m=0, \ldots, h_{ker}-1} \max_{n=0, \ldots, w_{ker}-1} \text{input}(N_i, C_j, s_0 \times h + m, s_1 \times w + n)$
Parameters
• ksize (Union[int, tuple[int]]) – The size of the window to take a max over, that should be a tuple of two int for width and height. Default: 1.

• stride (Union[int, tuple[int]]) – The stride of the window, that should be a tuple of two int for width and height. Default: 1.

• padding (str) – The optional values for pad mode “SAME”, “VALID”. Default: “VALID”.

Inputs:
• input (Tensor) - Tensor of shape $$(N, C_{in}, H_{in}, W_{in})$$.

Outputs:

Tensor, with shape $$(N, C_{out}, H_{out}, W_{out})$$.

class mindspore.ops.operations.MaxPoolWithArgmax(*args, **kwargs)[source]

Performs max pooling on the input Tensor and return both max values and indices.

Typically the input is of shape $$(N_{in}, C_{in}, H_{in}, W_{in})$$, MaxPool outputs regional maximum in the $$(H_{in}, W_{in})$$-dimension. Given kernel size $$ks = (h_{ker}, w_{ker})$$ and stride $$s = (s_0, s_1)$$, the operation is as follows.

$\text{output}(N_i, C_j, h, w) = \max_{m=0, \ldots, h_{ker}-1} \max_{n=0, \ldots, w_{ker}-1} \text{input}(N_i, C_j, s_0 \times h + m, s_1 \times w + n)$
Parameters

• window (Union[int, tuple[int]]) – The size of window, which is the kernel size, two int for width and height. Default: 1.

• stride (Union[int, tuple[int]]) – The stride of the window, that should be a tuple of two int for width and height. Default: 1.

Inputs:
• input (Tensor) - Tensor of shape $$(N, C_{in}, H_{in}, W_{in})$$.

Outputs:

Tuple of 2 Tensor, the maxpool result and where max values from.

• output (Tensor) - Maxpooling result, with shape $$(N, C_{out}, H_{out}, W_{out})$$.

class mindspore.ops.operations.Maximum(*args, **kwargs)[source]

Computes the element-wise maximum of input tensors.

The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be same. When the inputs are one tensor and one scalar, the scalar cannot be a parameter, only can be a constant, and the type of the scalar is the same as the data type of the tensor.

Inputs:
• input_x (Union[Tensor, Number]) - The first input is a tensor whose data type is number or a number.

• input_y (Union[Tensor, Number]) - The second input is a tensor whose data type is same as ‘input_x’ or a number.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is same as ‘input_x’.

Examples

>>> input_x = Tensor(np.array([1.0, 5.0, 3.0]), mindspore.float32)
>>> input_y = Tensor(np.array([4.0, 2.0, 6.0]), mindspore.float32)
>>> maximum = Maximum()
>>> maximum(input_x, input_y)
[4.0, 5.0, 6.0]

class mindspore.ops.operations.Merge(*args, **kwargs)[source]

Merges all input data to one.

One and only one of the inputs should be selected as the output

Inputs:
• inputs (Tuple) - The data to be merged. All tuple elements should have same shape.

Outputs:

tuple. Output is tuple(data, output_index). The data has the same shape of inputs element.

class mindspore.ops.operations.Minimum(*args, **kwargs)[source]

Computes the element-wise minimum of input tensors.

The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be same. When the inputs are one tensor and one scalar, the scalar cannot be a parameter, only can be a constant, and the type of the scalar is the same as the data type of the tensor.

Inputs:
• input_x (Union[Tensor, Number]) - The first input is a tensor whose data type is number or a number.

• input_y (Union[Tensor, Number]) - The second input is a tensor whose data type is same as ‘input_x’ or a number.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is same as ‘input_x’.

Examples

>>> input_x = Tensor(np.array([1.0, 5.0, 3.0]), mindspore.float32)
>>> input_y = Tensor(np.array([4.0, 2.0, 6.0]), mindspore.float32)
>>> minimum = Minimum()
>>> minimum(input_x, input_y)
[1.0, 2.0, 3.0]

class mindspore.ops.operations.Mul(*args, **kwargs)[source]

Multiplies two tensors element-wise.

The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be same. When the inputs are one tensor and one scalar, the scalar cannot be a parameter, only can be a constant, and the type of the scalar is the same as the data type of the tensor.

Inputs:
• input_x (Union[Tensor, Number]) - The first input is a tensor whose data type is number or a number.

• input_y (Union[Tensor, Number]) - The second input is a tensor whose data type is same as ‘input_x’ or a number.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is same as ‘input_x’.

Examples

>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
>>> input_y = Tensor(np.array([4, 5, 6]), mindspore.int32)
>>> mul = Mul()
>>> mul(input_x, input_y)
[4, 10, 18]

class mindspore.ops.operations.NMSWithMask(*args, **kwargs)[source]

Select some bounding boxes in descending order of score.

Parameters

iou_threshold (float) – Specifies the threshold of overlap boxes with respect to IOU. Default: 0.5.

Raises

ValueError – If the iou_threshold is not a float number, or if the first dimension of input Tensor is less than or equal to 0, or if the data type of the input Tensor is not float16 or float32.

Inputs:
• bboxes (Tensor) - The shape of tensor is $$(N, 5)$$. Input bounding boxes. N is the number of input bounding boxes. Every bounding box contains 5 values, the first 4 values are the coordinates of bounding box, and the last value is the score of this bounding box.

Outputs:

tuple[Tensor], tuple of three tensors, they are selected_boxes, selected_idx and selected_mask.

• selected_boxes (Tensor) - The shape of tensor is $$(N, 5)$$. Bounding boxes list after non-max suppression calculation.

• selected_idx (Tensor) - The shape of tensor is $$(N,)$$. The indexes list of valid input bounding boxes.

• selected_mask (Tensor) - The shape of tensor is $$(N,)$$. A mask list of valid output bounding boxes.

Examples

>>> bbox = np.random.rand(128, 5)
>>> bbox[:, 2] += bbox[:, 0]
>>> bbox[:, 3] += bbox[:, 1]
>>> inputs = Tensor(bbox)
>>> output_boxes, indices, mask = nms(inputs)

class mindspore.ops.operations.NPUAllocFloatStatus(*args, **kwargs)[source]

Allocates a flag to store the overflow status.

The flag is a tensor whose shape is (8,) and data type is mindspore.dtype.float32.

Note

Examples: see NPUGetFloatStatus.

Outputs:

Tensor, has the shape of (8,).

Examples

>>> alloc_status = NPUAllocFloatStatus()
>>> init = alloc_status()
Tensor([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], shape=(8,), dtype=mindspore.float32)

class mindspore.ops.operations.NPUClearFloatStatus(*args, **kwargs)[source]

Clear the flag which stores the overflow status.

Note

The flag is in the register on the Ascend device. It will be reset and can not be reused again after the NPUClearFloatStatus is called.

Examples: see NPUGetFloatStatus.

Inputs:
• input_x (Tensor) - The output tensor of NPUAllocFloatStatus.

Outputs:

Tensor, has the same shape as input_x. All the elements in the tensor will be zero.

Examples

>>> alloc_status = NPUAllocFloatStatus()
>>> get_status = NPUGetFloatStatus()
>>> clear_status = NPUClearFloatStatus()
>>> init = alloc_status()
>>> flag = get_status(init)
>>> clear = clear_status(init)
Tensor([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], shape=(8,), dtype=mindspore.float32)

class mindspore.ops.operations.NPUGetFloatStatus(*args, **kwargs)[source]

Updates the flag which is the output tensor of NPUAllocFloatStatus with latest overflow status.

The flag is a tensor whose shape is (8,) and data type is mindspore.dtype.float32. If the sum of the flag equals 0, there is no overflow happened. If the sum of the flag is bigger than 0, there is overflow happened.

Inputs:
• input_x (Tensor) - The output tensor of NPUAllocFloatStatus.

Outputs:

Tensor, has the same shape as input_x. All the elements in the tensor will be zero.

Examples

>>> alloc_status = NPUAllocFloatStatus()
>>> get_status = NPUGetFloatStatus()
>>> init = alloc_status()
>>> flag = get_status(init)
Tensor([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], shape=(8,), dtype=mindspore.float32)

class mindspore.ops.operations.Neg(*args, **kwargs)[source]

Returns a tensor with negative values of the input tensor element-wise.

Inputs:
• input_x (Tensor) - The input tensor whose dtype is number.

Outputs:

Tensor, has the same shape and dtype as input.

class mindspore.ops.operations.NotEqual(*args, **kwargs)[source]

Computes the non-equivalence of two tensors element-wise.

The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be same. When the inputs are one tensor and one scalar, the scalar cannot be a parameter, only can be a constant, and the type of the scalar is the same as the data type of the tensor.

Inputs:
• input_x (Union[Tensor, Number, bool]) - The first input is a tensor whose data type is number or bool, or a number or a bool object.

• input_y (Union[Tensor, Number, bool]) - The second input tensor whose data type is same as ‘input_x’ or a number or a bool object.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is bool.

Examples

>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.float32)
>>> not_equal = NotEqual()
>>> not_equal(input_x, 2.0)
[True, False, True]
>>>
>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
>>> input_y = Tensor(np.array([1, 2, 4]), mindspore.int32)
>>> not_equal = NotEqual()
>>> not_equal(input_x, input_y)
[False, False, True]

class mindspore.ops.operations.OneHot(*args, **kwargs)[source]

Computes a one-hot tensor.

Makes a new tensor, whose locations represented by indices in indices take value on_value, while all other locations take value off_value.

Note

If the input indices is rank N, the output will have rank N+1. The new axis is created at dimension axis.

Parameters

axis (int) – Position to insert the value. e.g. If indices shape is [n, c], and axis is -1 the output shape will be [n, c, depth], If axis is 0 the output shape will be [depth, n, c]. Default: -1.

Inputs:
• indices (Tensor) - A tensor of indices. Tensor of shape $$(X_0, \ldots, X_n)$$.

• depth (int) - A scalar defining the depth of the one hot dimension.

• on_value (Tensor) - A value to fill in output when indices[j] = i.

• off_value (Tensor) - A value to fill in output when indices[j] != i.

Outputs:

Tensor, one_hot tensor. Tensor of shape $$(X_0, \ldots, X_{axis}, \text{depth} ,X_{axis+1}, \ldots, X_n)$$.

Examples

>>> indices = Tensor(np.array([0, 1, 2]), mindspore.int32)
>>> depth, on_value, off_value = 3, Tensor(1.0, mindspore.float32), Tensor(0.0, mindspore.float32)
>>> onehot = OneHot()
>>> result = onehot(indices, depth, on_value, off_value)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]

class mindspore.ops.operations.OnesLike(*args, **kwargs)[source]

Creates a new tensor. All elements’ value are 1.

Returns a tensor of ones with the same shape and type as the input.

Inputs:
• input_x (Tensor) - Input tensor.

Outputs:

Tensor, has the same shape and type as input_x but filled with ones.

Examples

>>> oneslike = P.OnesLike()
>>> x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))
>>> output = oneslike(x)

class mindspore.ops.operations.PReLU(*args, **kwargs)[source]

Parametric Rectified Linear Unit activation function.

PReLU is described in the paper Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification. Defined as follows:

$prelu(x_i)= \max(0, x_i) + \min(0, w * x_i),$

where $$x_i$$ is an element of an channel of the input.

Inputs:
• input_x (Tensor) - Float tensor, representing the output of the preview layer.

• weight (Tensor) - Float Tensor, w > 0, there is only two shapes are legitimate, 1 or the number of channels at input.

Outputs:

Tensor, with the same type as input_x.

Detailed information, please refer to nn.PReLU.

class mindspore.ops.operations.Pad(*args, **kwargs)[source]

Parameters

paddings (tuple) – The shape of parameter paddings is (N, 2). N is the rank of input data. All elements of paddings are int type. For D th dimension of input, paddings[D, 0] indicates how many sizes to be extended ahead of the D th dimension of the input tensor, and paddings[D, 1] indicates how many sizes to be extended behind of the D th dimension of the input tensor.

Inputs:
• input_x (Tensor) - The input tensor.

Outputs:

Examples

>>> input_tensor = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
>>> assert output_tensor == Tensor(np.array([[ 0. ,  0. ,  0. ,  0. ,  0. ,  0. ],
>>>                                          [ 0. ,  0. , -0.1,  0.3,  3.6,  0. ],
>>>                                          [ 0. ,  0. ,  0.4,  0.5, -3.2,  0. ],
>>>                                          [ 0. ,  0. ,  0. ,  0. ,  0. ,  0. ],
>>>                                          [ 0. ,  0. ,  0. ,  0. ,  0. ,  0. ]]), mindspore.float32)

class mindspore.ops.operations.Pow(*args, **kwargs)[source]

Computes a tensor to the power of the second input.

Inputs:
• input_x (Tensor) - The input tensor.

• input_y (Union[Tensor, Number]) - The exponent part. If exponent is a tensor, its shape must be able to broadcast to the shape of the input_x.

Outputs:

Tensor, has the same shape as the input_x.

Examples

>>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
>>> input_y = 3.0
>>> pow = Pow()
>>> pow(input_x, input_y)
[1.0, 8.0, 64.0]
>>>
>>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
>>> input_y = Tensor(np.array([2.0, 4.0, 3.0]), mindspore.float32)
>>> pow = Pow()
>>> pow(input_x, input_y)
[1.0, 16.0, 64.0]

class mindspore.ops.operations.Print(*args, **kwargs)[source]

Output tensor to stdout.

Inputs:
• input_x (Tensor) - The graph node to attach to.

Examples

>>> class PrintDemo(nn.Cell):
>>>     def __init__(self,):
>>>         super(PrintDemo, self).__init__()
>>>         self.print = P.Print()
>>>
>>>     def construct(self, x):
>>>         self.print(x)
>>>         return x

class mindspore.ops.operations.ROIAlign(*args, **kwargs)[source]

Computes Region of Interest (RoI) Align operator.

The operator computes the value of each sampling point by bilinear interpolation from the nearby grid points on the feature map. No quantization is performed on any coordinates involved in the RoI, its bins, or the sampling points. The details of (RoI) Align operator are described in Mask R-CNN.

Parameters
• pooled_height (int) – The output features’ height.

• pooled_width (int) – The output features’ width.

• spatial_scale (float) – A scaling factor that maps the raw image coordinates to the input feature map coordinates. Suppose the height of a RoI is ori_h in the raw image and fea_h in the input feature map, the spatial_scale should be fea_h / ori_h.

• sample_num (int) – Number of sampling points. Default: 2.

Inputs:
• features (Tensor) - The input features, whose shape should be (N, C, H, W).

• rois (Tensor) - The shape is (rois_n, 5). rois_n represents the number of RoI. The size of the second dimension should be 5 and the 5 colunms are (image_index, top_left_x, top_left_y, bottom_right_x, bottom_right_y). image_index represents the index of image. top_left_x and top_left_y represent the x, y coordinates of the top left corner of corresponding RoI, respectively. bottom_right_x and bottom_right_y represent the x, y coordinates of the bottom right corner of corresponding RoI, respectively.

Outputs:

Tensor, the shape is (rois_n, C, pooled_height, pooled_width).

Examples

>>> input_tensor = Tensor(np.array([[[[1., 2.], [3., 4.]]]]), mindspore.float32)
>>> rois = Tensor(np.array([[0, 0.2, 0.3, 0.2, 0.3]]), mindspore.float32)
>>> roi_align = P.ROIAlign(1, 1, 0.5, 2)
>>> output_tensor = roi_align(input_tensor, rois)
>>> assert output_tensor == Tensor(np.array([[[[2.15]]]]), mindspore.float32)

class mindspore.ops.operations.RandomChoiceWithMask(*args, **kwargs)[source]

Generates a random samply as index tensor with a mask tensor from a given tensor.

The input must be a tensor of rank >= 2, the first dimension specify the number of sample. The index tensor and the mask tensor have the same and fixed shape. The index tensor denotes the index of the nonzero sample, while the mask tensor denotes which element in the index tensor are valid.

Parameters
• count (int) – Number of items expected to get. Default: 256.

• seed (int) – Random seed.

• seed2 (int) – Random seed2.

Inputs:
• input_x (Tensor) - The input tensor.

Outputs:

Tuple, two tensors, the first one is the index tensor and the other one is the mask tensor.

Examples

>>> rnd_choice_mask = RandomChoiceWithMask()
>>> input_x = Tensor(np.ones(shape=[240000, 4]), ms.bool_)

class mindspore.ops.operations.Rank(*args, **kwargs)[source]

Returns the rank of a tensor.

Returns a 0-D int32 Tensor representing the rank of input; the rank of a tensor is the number of indices required to uniquely select each element of the tensor.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

Outputs:

Tensor. 0-D int32 Tensor representing the rank of input, i.e., $$R$$.

Examples

>>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
>>> rank = Rank()
>>> rank(input_tensor)

class mindspore.ops.operations.ReLU(*args, **kwargs)[source]

Computes ReLU(Rectified Linear Unit) of input tensor element-wise.

It returns $$\max(x,\ 0)$$ element-wise.

Inputs:
• input_x (Tensor) - The input tensor.

Outputs:

Tensor, with the same type and shape as the input_x.

Examples

>>> input_x = Tensor(np.array([[-1.0, 4.0, -8.0], [2.0, -5.0, 9.0]], np.float32))
>>> relu = ReLU()
>>> result = relu(input_x)
[[0, 4.0, 0.0], [2.0, 0.0, 9.0]]

class mindspore.ops.operations.ReLU6(*args, **kwargs)[source]

Computes ReLU(Rectified Linear Unit) upper bounded by 6 of input tensor element-wise.

It returns $$\min(\max(0,x), 6)$$ element-wise.

Inputs:
• input_x (Tensor) - The input tensor.

Outputs:

Tensor, with the same type and shape as the input_x.

Examples

>>> input_x = Tensor(np.array([[-1.0, 4.0, -8.0], [2.0, -5.0, 9.0]], np.float32))
>>> relu6 = ReLU6()
>>> result = relu6(input_x)
>>> assert result.asnumpy() == Tensor(np.array([[0, 4.0, 0.0], [2.0, 0.0, 6.0]], np.float32)).asnumpy()

class mindspore.ops.operations.RealDiv(*args, **kwargs)[source]

Divide the first input tensor by the second input tensor in floating-point type element-wise.

The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be same. When the inputs are one tensor and one scalar, the scalar cannot be a parameter, only can be a constant, and the type of the scalar is the same as the data type of the tensor.

Inputs:
• input_x (Union[Tensor, Number]) - The first input is a tensor whose data type is number or a number.

• input_y (Union[Tensor, Number]) - The second input is a tensor whose data type is same as ‘input_x’ or a number.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is same as ‘input_x’.

Examples

>>> input_x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
>>> input_y = Tensor(np.array([4.0, 5.0, 6.0]), mindspore.float32)
>>> realdiv = RealDiv()
>>> realdiv(input_x, input_y)
[0.25, 0.4, 0.5]

class mindspore.ops.operations.Reciprocal(*args, **kwargs)[source]

Returns reciprocal of a tensor element-wise.

Inputs:
• input_x (Tensor) - The input tensor.

Outputs:

Tensor, has the same shape as the input_x.

Examples

>>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
>>> reciprocal = Reciprocal()
>>> reciprocal(input_x)
[1.0, 0.5, 0.25]

class mindspore.ops.operations.ReduceAll(*args, **kwargs)[source]

Reduce a dimension of a tensor by the “logical and” of all elements in the dimension.

The dtype of the tensor to be reduced is bool.

Parameters

keep_dims (bool) – If True, keep these reduced dimensions and the length is 1. If False, don’t keep these dimensions. Default : False, don’t keep these reduced dimensions.

Inputs:
• input_x (Tensor[bool]) - The input tensor.

• axis (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions. Only constant value is allowed.

Outputs:

Tensor, the dtype is bool.

• If axis is (), and keep_dims is false, the output is a 0-D tensor representing the “logical and” of of all elements in the input tensor.

• If axis is int, set as 2, and keep_dims is false, and keep_dims is false, the shape of output is $$(x_1, x_3, ..., x_R)$$.

• If axis is tuple(int), set as (2, 3), and keep_dims is false, the shape of output is $$(x_1, x_4, ..., x_R)$$.

Examples

>>> data = Tensor(np.array([[True, False], [True, True]]))
>>> op = ReduceAll(keep_dims=True)
>>> output = op(data, 1)

class mindspore.ops.operations.ReduceMax(*args, **kwargs)[source]

Reduce a dimension of a tensor by the maximum value in this dimension.

The dtype of the tensor to be reduced is number.

Parameters

keep_dims (bool) – If True, keep these reduced dimensions and the length is 1. If False, don’t keep these dimensions. Default : False, don’t keep these reduced dimensions.

Inputs:
• input_x (Tensor[Number]) - The input tensor.

• axis (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions. Only constant value is allowed.

Outputs:

Tensor, has the same dtype as the ‘input_x’.

• If axis is (), and keep_dims is false, the output is a 0-D tensor representing the maximum of all elements in the input tensor.

• If axis is int, set as 2, and keep_dims is false, the shape of output is $$(x_1, x_3, ..., x_R)$$.

• If axis is tuple(int), set as (2, 3), and keep_dims is false, the shape of output is $$(x_1, x_4, ..., x_R)$$.

Examples

>>> data = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
>>> op = ReduceMax(keep_dims=True)
>>> output = op(data, 1)

class mindspore.ops.operations.ReduceMean(*args, **kwargs)[source]

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

The dtype of the tensor to be reduced is number.

Parameters

keep_dims (bool) – If True, keep these reduced dimensions and the length is 1. If False, don’t keep these dimensions. Default : False.

Inputs:
• input_x (Tensor[Number]) - The input tensor.

• axis (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions. Only constant value is allowed.

Outputs:

Tensor, has the same dtype as the ‘input_x’.

• If axis is (), and keep_dims is false, the output is a 0-D tensor representing the sum of all elements in the input tensor.

• If axis is int, set as 2, and keep_dims is false, the shape of output is $$(x_1, x_3, ..., x_R)$$.

• If axis is tuple(int), set as (2, 3), and keep_dims is false, the shape of output is $$(x_1, x_4, ..., x_R)$$.

Examples

>>> data = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
>>> op = ReduceMean(keep_dims=True)
>>> output = op(data, 1)

class mindspore.ops.operations.ReduceMin(*args, **kwargs)[source]

Reduce a dimension of a tensor by the minimum value in the dimension.

The dtype of the tensor to be reduced is number.

Parameters

keep_dims (bool) – If True, keep these reduced dimensions and the length is 1. If False, don’t keep these dimensions. Default : False, don’t keep these reduced dimensions.

Inputs:
• input_x (Tensor[Number]) - The input tensor.

• axis (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions. Only constant value is allowed.

Outputs:

Tensor, has the same dtype as the ‘input_x’.

• If axis is (), and keep_dims is false, the output is a 0-D tensor representing the minimum of all elements in the input tensor.

• If axis is int, set as 2, and keep_dims is false, the shape of output is $$(x_1, x_3, ..., x_R)$$.

• If axis is tuple(int), set as (2, 3), and keep_dims is false, the shape of output is $$(x_1, x_4, ..., x_R)$$.

Examples

>>> data = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
>>> op = ReduceMin(keep_dims=True)
>>> output = op(data, 1)

class mindspore.ops.operations.ReduceOp[source]

Operation options for reduce tensors.

There are four kinds of operation options, “SUM”,”MAX”,”MIN”,”PROD”.

• SUM: Take the sum.

• MAX: Take the maximum.

• MIN: Take the minimum.

• PROD: Take the product.

class mindspore.ops.operations.ReduceProd(*args, **kwargs)[source]

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

The dtype of the tensor to be reduced is number.

Parameters

keep_dims (bool) – If True, keep these reduced dimensions and the length is 1. If False, don’t keep these dimensions. Default : False, don’t keep these reduced dimensions.

Inputs:
• input_x (Tensor[Number]) - The input tensor.

• axis (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.

Outputs:

Tensor, has the same dtype as the ‘input_x’.

• If axis is (), and keep_dims is false, the output is a 0-D tensor representing the product of all elements in the input tensor.

• If axis is int, set as 2, and keep_dims is false, the shape of output is $$(x_1, x_3, ..., x_R)$$.

• If axis is tuple(int), set as (2, 3), and keep_dims is false, the shape of output is $$(x_1, x_4, ..., x_R)$$.

Examples

>>> data = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
>>> op = ReduceProd(keep_dims=True)
>>> output = op(data, 1)

class mindspore.ops.operations.ReduceScatter(*args, **kwargs)[source]

Reduces and scatters tensors from the specified communication group.

Note

The back propagation of the op is not surported yet. Stay tuned for more. Tensor must have the same shape and format in all processes participating in the collective.

Parameters
• op (str) – Specifies an operation used for element-wise reductions, like sum, max, avg. Default: ReduceOp.SUM.

• group (str) – The communication group to work on. Default: “hccl_world_group”.

Raises
• TypeError – If any of op and group is not a string

• ValueError – If the first dimension of input can not be divided by rank size.

Examples

>>> from mindspore.communication.management import init
>>> import mindspore.ops.operations as P
>>> init('nccl')
>>> class Net(nn.Cell):
>>>     def __init__(self):
>>>         super(Net, self).__init__()
>>>         self.reducescatter = P.ReduceScatter(ReduceOp.SUM, group="nccl_world_group")
>>>
>>>     def construct(self, x):
>>>         return self.reducescatter(x)
>>>
>>> input_ = Tensor(np.ones([2, 8]).astype(np.float32))
>>> net = Net()
>>> output = net(input_)

class mindspore.ops.operations.ReduceSum(*args, **kwargs)[source]

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

The dtype of the tensor to be reduced is number.

Parameters

keep_dims (bool) – If True, keep these reduced dimensions and the length is 1. If False, don’t keep these dimensions. Default : False.

Inputs:
• input_x (Tensor[Number]) - The input tensor.

• axis (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions. Only constant value is allowed.

Outputs:

Tensor, has the same dtype as the ‘input_x’.

• If axis is (), and keep_dims is false, the output is a 0-D tensor representing the sum of all elements in the input tensor.

• If axis is int, set as 2, and keep_dims is false, the shape of output is $$(x_1, x_3, ..., x_R)$$.

• If axis is tuple(int), set as (2, 3), and keep_dims is false, the shape of output is $$(x_1, x_4, ..., x_R)$$.

Examples

>>> data = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
>>> op = ReduceSum(keep_dims=True)
>>> output = op(data, 1)

class mindspore.ops.operations.Reshape(*args, **kwargs)[source]

Reshapes input tensor with the same values based on a given shape tuple.

Raises

ValueError – Given a shape tuple, if it has more than one -1; or if the product of its elements is less than or equal to 0 or cannot be divided by the product of the input tensor shape; or if it does not match the input’s array size.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

• input_shape (tuple[int]) - The input tuple is constructed by multiple integers, i.e., $$(y_1, y_2, ..., y_S)$$. Only constant value is allowed.

Outputs:

Tensor, the shape of tensor is $$(y_1, y_2, ..., y_S)$$.

Examples

>>> input_tensor = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
>>> reshape = Reshape()
>>> output = reshape(input_tensor, (3, 2))

class mindspore.ops.operations.ResizeBilinear(*args, **kwargs)[source]

Resizes the image to certain size using bilinear interpolation.

The resizing only affects the lower two dimensions which represent the height and width. The input images can be represented by different data types, but the data types of output images are always float32.

Parameters
• size (tuple[int]) – A tuple of 2 int elements (new_height, new_width), the new size for the images.

• align_corners (bool) – If it’s true, rescale input by (new_height - 1) / (height - 1), which exactly aligns the 4 corners of images and resized images. If it’s false, rescale by new_height / height. Default: False.

Inputs:
• input (Tensor) - Image to be resized. Tensor of shape (N_i, …, N_n, height, width).

Outputs:

Tensor, resized image. Tensor of shape (N_i, …, N_n, new_height, new_width) in float32.

Examples

>>> tensor = Tensor([[[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]]], mindspore.int32)
>>> resize_bilinear = P.ResizeBilinear((5, 5))
>>> result = resize_bilinear(tensor)
>>> assert result.shape() == (5, 5)

class mindspore.ops.operations.ResizeNearestNeighbor(*args, **kwargs)[source]

Resize the input tensor by using nearest neighbor algorithm.

Resize input tensor to given size by using nearest neighbor algorithm. The nearest neighbor algorithm selects the value of the nearest point and does not consider the values of neighboring points at all, yielding a piecewise-constant interpolant.

Parameters
• size (Union[tuple, list]) – The target size. The dimension of size must be 2.

• align_corners (bool) – Whether the centers of the 4 corner pixels of the input and output tensors are aligned. Default: False.

Inputs:
• input_x (Tensor) - The input tensor. The shape of the tensor is $$(N, C, H, W)$$.

Outputs:

Tensor, the shape of the output tensor is $$(N, NEW_C, NEW_H, W)$$.

Examples

>>> input_tensor = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
>>> resize = ResizeNearestNeighbor((2, 2))
>>> output = resize(input_tensor)

class mindspore.ops.operations.Round(*args, **kwargs)[source]

Returns half to even of a tensor element-wise.

Inputs:
• input_x (Tensor) - The input tensor.

Outputs:

Tensor, has the same shape and type as the input_x.

Examples

>>> input_x = Tensor(np.array([0.8, 1.5, 2.3, 2.5, -4.5]), mindspore.float32)
>>> round = Round()
>>> round(input_x)
[1.0, 2.0, 2.0, 2.0, -4.0]

class mindspore.ops.operations.Rsqrt(*args, **kwargs)[source]

Computes reciprocal of square root of input tensor element-wise.

Inputs:
• input_x (Tensor) - The input of Rsqrt. Each element should be a non-negative number.

Outputs:

Tensor, has the same type and shape as input_x.

Examples

>>> input_tensor = Tensor([[4, 4], [9, 9]], mindspore.float32)
>>> rsqrt = Rsqrt()
>>> rsqrt(input_tensor)
[[0.5, 0.5], [0.333333, 0.333333]]

class mindspore.ops.operations.SGD(*args, **kwargs)[source]

Computes stochastic gradient descent (optionally with momentum).

Nesterov momentum is based on the formula from On the importance of initialization and momentum in deep learning.

Note

For details, please refer to nn.SGD source code.

Parameters
• dampening (float) – The dampening for momentum. Default: 0.0.

• weight_decay (float) – Weight decay (L2 penalty). Default: 0.0.

• nesterov (bool) – Enable Nesterov momentum. Default: False.

Inputs:
• parameters (Tensor) - Parameters to be updated.

• learning_rate (Tensor) - Learning rate. e.g. Tensor(0.1, mindspore.float32).

• accum (Tensor) - Accum(velocity) to be updated.

• momentum (Tensor) - Momentum. e.g. Tensor(0.1, mindspore.float32).

• stat (Tensor) - States to be updated with the same shape as gradient.

Outputs:

Tensor, parameters to be updated.

class mindspore.ops.operations.SameTypeShape(*args, **kwargs)[source]

Checks whether data type and shape of two tensors are the same.

Raises

ValueError – If not the same.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

• input_y (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_S)$$.

Outputs:

Tensor, the shape of tensor is $$(x_1, x_2, ..., x_R)$$, if data type and shape of input_x and input_y are the same.

Examples

>>> input_x = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
>>> input_y = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
>>> out = SameTypeShape()(input_x, input_y)

class mindspore.ops.operations.ScalarCast(*args, **kwargs)[source]

Cast the input scalar to another type.

Inputs:
• input_x (scalar) - The input scalar. Only constant value is allowed.

• input_y (mindspore.dtype) - The type should cast to be. Only constant value is allowed.

Outputs:

Scalar. The type is same as the python type corresponding to input_y.

Examples

>>> scalar_cast = P.ScalarCast()
>>> output = scalar_cast(255.0, mindspore.int32)

class mindspore.ops.operations.ScalarSummary(*args, **kwargs)[source]

Output scalar to protocol buffer through scalar summary operator.

Inputs:
• name (str) - The name of the input variable.

• value (Tensor) - The value of scalar.

Examples

>>> class SummaryDemo(nn.Cell):
>>>     def __init__(self,):
>>>         super(SummaryDemo, self).__init__()
>>>         self.summary = P.ScalarSummary()
>>>
>>>     def construct(self, x, y):
>>>         name = "x"
>>>         self.summary(name, x)
>>>         return x

class mindspore.ops.operations.ScalarToArray(*args, **kwargs)[source]

Converts scalar to Tensor.

Inputs:
• input_x (Union[int, float]) - The input is a scalar. Only constant value is allowed.

Outputs:

Tensor. 0-D Tensor and the content is the input.

Examples

>>> op = ScalarToArray()
>>> data = 1.0
>>> output = op(data)

class mindspore.ops.operations.ScalarToTensor(*args, **kwargs)[source]

Converts scalar to Tensor, and convert data type to specified type.

Inputs:
• input_x (Union[int, float]) - The input is a scalar. Only constant value is allowed.

• dtype (mindspore.dtype) - The target data type. Default: mindspore.float32. Only constant value is allowed.

Outputs:

Tensor. 0-D Tensor and the content is the input.

Examples

>>> op = ScalarToTensor()
>>> data = 1
>>> output = op(data, mindspore.float32)

class mindspore.ops.operations.ScatterNd(*args, **kwargs)[source]

Scatters a tensor into a new tensor depending on the specified indices.

Creates an empty tensor, and set values by scattering the update tensor depending on indices.

Inputs:
• indices (Tensor) - The index of scattering in the new tensor.

• update (Tensor) - The source Tensor to be scattered.

• shape (tuple[int]) - Define the shape of the output tensor. Has the same type as indices.

Outputs:

Tensor, the new tensor, has the same type as update and the same shape as shape.

Examples

>>> op = ScatterNd()
>>> update = Tensor(np.array([3.2, 1.1]), mindspore.float32)
>>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32)
>>> shape = (3, 3)
>>> output = op(indices, update, shape)

class mindspore.ops.operations.ScatterNdUpdate(*args, **kwargs)[source]

Update tensor value by using input indices and value.

Using given values to update tensor value, along with the input indices.

Parameters

use_locking (bool) – Whether protect the assignment by a lock. Defaule: True.

Inputs:
• input_x (Tensor) - The target tensor.

• indices (Tensor) - The index of input tensor.

• update (Tensor) - The tensor to add to the input tensor, has the same type as input.

Outputs:

Tensor, has the same shape and type as input_x.

Examples

>>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
>>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
>>> update = Tensor(np.array([1.0, 2.2]), mindspore.float32)
>>> op = ScatterNdUpdate()
>>> output = op(input_x, indices, update)

class mindspore.ops.operations.Select(*args, **kwargs)[source]

Return the selected elements, either from input $$x$$ or input $$y$$, depending on the condition.

Given a tensor as input, this operation inserts a dimension of 1 at the dimension, if both $$x$$ and $$y$$ are none, the operation returns the coordinates of the true element in the condition, the coordinates are returned as a two-dimensional tensor, where the first dimension (row) represents the number of true elements and the second dimension (columns) represents the coordinates of the true elements. Keep in mind that the shape of the output tensor can vary depending on how much of the true value is in the input. Indexes are output in row-first order.

If neither is None, $$x$$ and $$y$$ must have the same shape. If $$x$$ and $$y$$ are scalars, the conditional tensor must be a scalar. If $$x$$ and $$y$$ are higher-demensional vectors, the condition must be a vector whose size matches the first dimension of $$x$$, or must have the same shape as $$y$$.

The conditional tensor acts as an optional compensation (mask), which determines whether the corresponding element / row in the output should be selected from $$x$$ (if true) or $$y$$ (if false) based on the value of each element.

If condition is a vector, then $$x$$ and $$y$$ are higher-demensional matrices, then it chooses to copy that row (external dimensions) from $$x$$ and $$y$$. If condition has the same shape as $$x$$ and $$y$$, you can choose to copy these elements from $$x$$ and $$y$$.

Inputs:
• input_x (Tensor[bool]) - The shape is $$(x_1, x_2, ..., x_N)$$. The condition tensor, decides whose element is chosen.

• input_y (Tensor) - The shape is $$(x_1, x_2, ..., x_N, ..., x_R)$$. The first input tensor.

• input_z (Tensor) - The shape is $$(x_1, x_2, ..., x_N, ..., x_R)$$. The second input tensor.

Outputs:

Tensor, has the same shape as input_y. The shape is $$(x_1, x_2, ..., x_N, ..., x_R)$$.

Examples

>>> select = Select()
>>> input_x = Tensor([True, False])
>>> input_y = Tensor([2,3], mindspore.float32)
>>> input_z = Tensor([1,2], mindspore.float32)
>>> select(input_x, input_y, input_z)

class mindspore.ops.operations.Shape(*args, **kwargs)[source]

Returns the shape of input tensor.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

Outputs:

tuple[int], the output tuple is constructed by multiple integers, $$(x_1, x_2, ..., x_R)$$.

Examples

>>> input_tensor = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32)
>>> shape = Shape()
>>> output = shape(input_tensor)

class mindspore.ops.operations.Sigmoid(*args, **kwargs)[source]

Sigmoid activation function.

Computes Sigmoid of input element-wise. The Sigmoid function is defined as:

$\text{sigmoid}(x_i) = \frac{1}{1 + exp(-x_i)},$

where $$x_i$$ is the element of the input.

Inputs:
• input_x (Tensor) - The input of Sigmoid.

Outputs:

Tensor, with the same type and shape as the input_x.

class mindspore.ops.operations.SigmoidCrossEntropyWithLogits(*args, **kwargs)[source]

Uses the given logits to compute sigmoid cross entropy.

Note

Sets input logits as X, input label as Y, output as loss. Then,

$p_{ij} = sigmoid(X_{ij}) = \frac{1}{1 + e^{-X_{ij}}}$
$loss_{ij} = -[Y_{ij} * ln(p_{ij}) + (1 - Y_{ij})ln(1 - p_{ij})]$
Inputs:
• logits (Tensor) - Input logits.

• label (Tensor) - Ground truth label.

Outputs:

Tensor, with the same shape and type as input logits.

class mindspore.ops.operations.Sign(*args, **kwargs)[source]

Perform $$sign$$ on tensor element-wise.

Note

$sign(x) = \begin{cases} -1, &if\ x < 0 \cr 0, &if\ x == 0 \cr 1, &if\ x > 0\end{cases}$
Inputs:
• input_x (Tensor) - The input tensor.

Outputs:

Tensor, has the same shape and type as the input_x.

Examples

>>> input_x = Tensor(np.array([[2.0, 0.0, -1.0]]), mindspore.float32)
>>> sign = Sign()
>>> output = sign(input_x)
[[1.0, 0.0, -1.0]]

class mindspore.ops.operations.Sin(*args, **kwargs)[source]

Computes sine of input element-wise.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

Outputs:

Tensor, has the same shape as input_x.

Examples

>>> sin = Sin()
>>> X = Tensor(np.array([0.62, 0.28, 0.43, 0.62]), ms.float32)
>>> output = sin(X)

class mindspore.ops.operations.Size(*args, **kwargs)[source]

Returns the elements count size of a tensor.

Returns an int scalar representing the elements size of input, the total number of elements in the tensor.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

Outputs:

int, a scalar representing the elements size of input_x, tensor is the number of elements in a tensor, $$size=x_1*x_2*...x_R$$.

Examples

>>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
>>> size = Size()
>>> output = size(input_tensor)

class mindspore.ops.operations.Slice(*args, **kwargs)[source]

Slice a tensor in specified shape.

Parameters
• x (Tensor) – The target tensor.

• begin (tuple) – The beginning of the slice. Only constant value is allowed.

• size (tuple) – The size of the slice. Only constant value is allowed.

Returns

Tensor.

Examples

>>> data = Tensor(np.array([3,2,3]).astype(np.int32))
>>> type = P.Slice()(data, (1, 0, 0), (1, 1, 3))

class mindspore.ops.operations.SmoothL1Loss(*args, **kwargs)[source]

Computes smooth L1 loss, a robust L1 loss.

SmoothL1Loss is a Loss similar to MSELoss but less sensitive to outliers as described in the Fast R-CNN by Ross Girshick.

Note

Sets input prediction as X, input target as Y, output as loss. Then,

$\text{SmoothL1Loss} = \begin{cases}0.5x^{2}, &if \left |x \right |\leq \text{sigma} \cr \left |x \right|-0.5, &\text{otherwise}\end{cases}$
Parameters

sigma (float) – A parameter used to control the point where the function will change from quadratic to linear. Default: 1.0.

Inputs:
• prediction (Tensor) - Predict data.

• target (Tensor) - Ground truth data, with the same type and shape as prediction.

Outputs:

Tensor, with the same type and shape as prediction.

class mindspore.ops.operations.Softmax(*args, **kwargs)[source]

Softmax operation.

Applies the Softmax operation to the input tensor on the specified axis. Suppose a slice along the given aixs $$x$$ then for each element $$x_i$$ the Softmax function is shown as follows:

$\text{output}(x_i) = \frac{exp(x_i)}{\sum_{j = 0}^{N-1}\exp(x_j)},$

where $$N$$ is the length of the tensor.

Parameters

axis (Union[int, tuple]) – The axis to do the Softmax operation. Default: -1.

Inputs:
• logits (Tensor) - The input of Softmax.

Outputs:

Tensor, with the same type and shape as the logits.

class mindspore.ops.operations.SoftmaxCrossEntropyWithLogits(*args, **kwargs)[source]

Gets the softmax cross-entropy value between logits and labels which shoule be one-hot encoding.

Note

Sets input logits as X, input label as Y, output as loss. Then,

$p_{ij} = softmax(X_{ij}) = \frac{exp(x_i)}{\sum_{j = 0}^{N-1}\exp(x_j)}$
$loss_{ij} = -\sum_j{Y_{ij} * ln(p_{ij})}$
Inputs:
• logits (Tensor) - Input logits, with shape $$(N, C)$$.

• labels (Tensor) - Ground truth labels, with shape $$(N, C)$$.

Outputs:

Tuple of 2 Tensor, the loss shape is (N,), and the dlogits with the same shape as logits.

class mindspore.ops.operations.SpaceToDepth(*args, **kwargs)[source]

Rearrange blocks of spatial data into depth.

The output tensor’s height dimension is $$height / block\_size$$.

The output tensor’s weight dimension is $$weight / block\_size$$.

The depth of output tensor is $$block\_size * block\_size * input\_depth$$.

The input tensor’s height and width must be divisible by block_size. The data format is “NCHW”.

Parameters

block_size (int) – The block size used to divide spatial data. It must be >= 2.

Inputs:
• x (Tensor) - The target tensor.

Outputs:

Tensor, the same type as x.

Examples

>>> x = Tensor(np.random.rand(1,3,2,2), mindspore.float32)
>>> block_size = 2
>>> op = SpaceToDepth(block_size)
>>> output = op(x)
>>> output.asnumpy().shape == (1,12,1,1)

class mindspore.ops.operations.SparseApplyAdagrad(*args, **kwargs)[source]

$accum += grad * grad$
$var -= lr * grad * (1 / sqrt(accum))$
Parameters
• lr (float) – Learning rate.

• use_locking (bool) – If True, updating of the var and accum tensors will be protected. Default: False.

Inputs:
• var (Tensor) - Variable to be updated. The type must be float32.

• accum (Tensor) - Accum to be updated. The shape must be the same as var’s shape, the type must be float32.

• grad (Tensor) - Gradient. The shape must be the same as var’s shape except first dimension, the type must be float32.

• indices (Tensor) - A vector of indices into the first dimension of var and accum. The shape of indices must be the same as grad in first dimension, the type must be int32.

Outputs:

Tensor, has the same shape and type as var.

class mindspore.ops.operations.SparseSoftmaxCrossEntropyWithLogits(*args, **kwargs)[source]

Computes the softmax cross-entropy value between logits and sparse encoding labels.

Note

Sets input logits as X, input label as Y, output as loss. Then,

$p_{ij} = softmax(X_{ij}) = \frac{exp(x_i)}{\sum_{j = 0}^{N-1}\exp(x_j)}$
$loss_{ij} = \begin{cases} -ln(p_{ij}), &j = y_i \cr -ln(1 - p_{ij}), & j \neq y_i \end{cases}$
$loss = \sum_{ij} loss_{ij}$
Parameters

is_grad (bool) – If it’s true, this operation returns the computed gradient. Default: False.

Inputs:
• logits (Tensor) - Input logits, with shape $$(N, C)$$.

• labels (Tensor) - Ground truth labels, with shape $$(N)$$.

Outputs:

Tensor, if is_grad is False, the output tensor is the value of loss which is a scalar tensor; if is_grad is True, the output tensor is the gradient of input with the same shape as logits.

class mindspore.ops.operations.Split(*args, **kwargs)[source]

Splits input tensor into output_num of tensors along the given axis and output numbers.

Parameters
• axis (int) – Index of the split position. Default: 0.

• output_num (int) – The number of output tensors. Default: 1.

Raises

ValueError – If axis is out of the range [-len(input_x.shape()), len(input_x.shape())), or if the output_num is less than or equal to 0, or if the dimension which to split cannot be evenly divided by output_num.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

Outputs:

tuple[Tensor], the shape of each output tensor is same, which is $$(y_1, y_2, ..., y_S)$$.

Examples

>>> split = Split(1, 2)
>>> x = Tensor(np.array([[1, 1, 1, 1], [2, 2, 2, 2]]))
>>> output = split(x)

class mindspore.ops.operations.Sqrt(*args, **kwargs)[source]

Returns square root of a tensor element-wise.

Inputs:
• input_x (Tensor) - The input tensor whose dtype is number.

Outputs:

Tensor, has the same shape as the input_x.

Examples

>>> input_x = Tensor(np.array([1.0, 4.0, 9.0]), mindspore.float32)
>>> sqrt = Sqrt()
>>> sqrt(input_x)
[1.0, 2.0, 3.0]

class mindspore.ops.operations.Square(*args, **kwargs)[source]

Returns square of a tensor element-wise.

Inputs:
• input_x (Tensor) - The input tensor whose dtype is number.

Outputs:

Tensor, has the same shape and dtype as the input_x.

Examples

>>> input_x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
>>> square = Square()
>>> square(input_x)
[1.0, 4.0, 9.0]

class mindspore.ops.operations.Squeeze(*args, **kwargs)[source]

Returns a tensor with the same type but dimensions of 1 being removed based on axis.

Note

The dimension index starts at 0 and must be in the range [-input.dim(), input.dim()).

Raises

ValueError – If the corresponding dimension of the specified axis does not equal to 1.

Parameters

axis (int) – Specifies the dimension indexes of shape to be removed, which will remove all the dimensions that are equal to 1. If specified, it must be int32 or int64. Default: (), an empty tuple.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

Outputs:

Tensor, the shape of tensor is $$(x_1, x_2, ..., x_S)$$.

Examples

>>> input_tensor = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32)
>>> squeeze = Squeeze(2)
>>> output = squeeze(input_tensor)

class mindspore.ops.operations.StridedSlice(*args, **kwargs)[source]

Extracts a strided slice of a tensor.

Given an input tensor, this operation inserts a dimension of length 1 at the dimension. This operation extracts a fragment of size (end-begin)/stride from the given ‘input_tensor’. Starting from the position specified by the begin, the fragment continues adding stride to the index until all dimensions are not less than end.

Note

The stride may be negative value, which causes reverse slicing. The shape of begin, end and strides should be the same.

Parameters
• begin_mask (int) – Starting index of the slice. Default: 0.

• end_mask (int) – Ending index of the slice. Default: 0.

Inputs:
• input_x (Tensor) - The input Tensor.

• begin (tuple[int]) - A tuple which represents the location where to start. Only constant value is allowed.

• end (tuple[int]) - A tuple or which represents the maximum location where to stop. Only constant value is allowed.

• strides (tuple[int]) - A tuple which represents the stride continuously added before reach the maximum location. Only constant value is allowed.

Outputs:

Tensor. Explain with the following example.

• In the 0th dim, begin is 1, end is 2, and strides is 1, because $$1+1=2\geq2$$, the interval is $$[1,2)$$. Thus, return the element with $$index = 1$$ in 0th dim, i.e., [[3, 3, 3], [4, 4, 4]].

• In the 1st dim, similarly, the interval is $$[0,1)$$. Based on the return value of the 0th dim, return the element with $$index = 0$$, i.e., [3, 3, 3].

• In the 2nd dim, similarly, the interval is $$[0,3)$$. Based on the return value of the 1st dim, return the element with $$index = 0,1,2$$, i.e., [3, 3, 3].

• Finally, the output is [3, 3, 3].

Examples
>>> input_x = Tensor([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]], [[5, 5, 5], [6, 6, 6]]])
>>> slice = StridedSlice()
>>> output = slice(input_x, (1, 0, 0), (2, 1, 3), (1, 1, 1))
>>> output.shape()
(1, 1, 3)
>>> output
[[[3, 3, 3]]]

class mindspore.ops.operations.Sub(*args, **kwargs)[source]

Subtracts the second input tensor from the first input tensor element-wise.

The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be same. When the inputs are one tensor and one scalar, the scalar cannot be a parameter, only can be a constant, and the type of the scalar is the same as the data type of the tensor.

Inputs:
• input_x (Union[Tensor, Number]) - The first input is a tensor whose data type is number or a number.

• input_y (Union[Tensor, Number]) - The second input is a tensor whose data type is same as ‘input_x’ or a number.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is same as ‘input_x’.

Examples

>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
>>> input_y = Tensor(np.array([4, 5, 6]), mindspore.int32)
>>> sub = Sub()
>>> sub(input_x, input_y)
[-3, -3, -3]

class mindspore.ops.operations.Tanh(*args, **kwargs)[source]

Tanh activation function.

Computes hyperbolic tangent of input element-wise. The Tanh function is defined as:

$tanh(x_i) = \frac{\exp(x_i) - \exp(-x_i)}{\exp(x_i) + \exp(-x_i)} = \frac{\exp(2x_i) - 1}{\exp(2x_i) + 1},$

where $$x_i$$ is an element of the input Tensor.

Inputs:
• input_x (Tensor) - The input of Tanh.

Outputs:

Tensor, with the same type and shape as the input_x.

class mindspore.ops.operations.TensorAdd(*args, **kwargs)[source]

The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors, the shapes of them could be broadcast, and the data types of them should be same. When the inputs are one tensor and one scalar, the scalar cannot be a parameter, only can be a constant, and the type of the scalar is the same as the data type of the tensor.

Inputs:
• input_x (Union[Tensor, Number]) - The first input is a tensor whose data type is number or a number.

• input_y (Union[Tensor, Number]) - The second input is a tensor whose data type is same as ‘input_x’ or a number.

Outputs:

Tensor, the shape is same as the shape after broadcasting, and the data type is same as ‘input_x’.

Examples

>>> add = P.TensorAdd()
>>> x = Tensor(np.array([1,2,3]).astype(np.float32))
>>> y = Tensor(np.array([4,5,6]).astype(np.float32))
[5,7,9]

class mindspore.ops.operations.TensorSummary(*args, **kwargs)[source]

Output tensor to protocol buffer through tensor summary operator.

Inputs:
• name (str) - The name of the input variable.

• value (Tensor) - The value of tensor.

Examples

>>> class SummaryDemo(nn.Cell):
>>>     def __init__(self,):
>>>         super(SummaryDemo, self).__init__()
>>>         self.summary = P.TensorSummary()
>>>
>>>     def construct(self, x, y):
>>>         name = "x"
>>>         self.summary(name, x)
>>>         return x

class mindspore.ops.operations.Tile(*args, **kwargs)[source]

Replicates a tensor with given multiples times.

Creates a new tensor by replicating input multiples times. The dimension of output tensor is the larger of the dimension length of input and the length of multiples.

Inputs:
• input_x (Tensor) - 1-D or higher Tensor. Set the shape of input tensor as $$(x_1, x_2, ..., x_S)$$.

• multiples (tuple[int]) - The input tuple is constructed by multiple integers, i.e., $$(y_1, y_2, ..., y_S)$$. The length of multiples can’t be smaller than the length of shape in input_x.

Outputs:

Tensor, has the same type as the input_x.

• If the length of multiples is the same as the length of shape in input_x, then the shape of their corresponding positions can be multiplied, and the shape of Outputs is $$(x_1*y_1, x_2*y_2, ..., x_S*y_R)$$.

• If the length of multiples is larger than the length of shape in input_x, fill in multiple 1 in front of the shape in input_x until their lengths are consistent. Such as set the shape of input_x as $$(1, ..., x_1, x_2, ..., x_S)$$, then the shape of their corresponding positions can be multiplied, and the shape of Outputs is $$(1*y_1, ..., x_S*y_R)$$.

class mindspore.ops.operations.TopK(*args, **kwargs)[source]

Finds values and indices of the k largest entries along the last dimension.

Parameters

sorted (bool) – If true, the resulting elements will be sorted by the values in descending order. Default: False.

Inputs:
• input_x (Tensor) - Input to be computed.

• k (int) - Number of top elements to be computed along the last dimension, constant input is needed.

Outputs:

Tuple of 2 Tensor, the values and the indices.

• values (Tensor) - The k largest elements along each last dimensional slice.

• indices (Tensor) - The indices of values within the last dimension of input.

Examples

>>> topk = TopK(sorted=True)
>>> x = Tensor(np.array([1, 2, 3, 4, 5]).astype(np.float16))
>>> values, indices = topk(x)
>>> assert values == Tensor(np.array([5, 4, 3]))
>>> assert indices == Tensor(np.array([4, 3, 2]))

class mindspore.ops.operations.Transpose(*args, **kwargs)[source]

Permutes the dimensions of input tensor according to input perm.

Inputs:
• input_x (Tensor) - The shape of tensor is $$(x_1, x_2, ..., x_R)$$.

• input_perm (tuple[int]) - The permutation to be converted. The input tuple is constructed by multiple indexes. The length of input_perm and the shape of input_x should be the same. Only constant value is allowed.

Outputs:

Tensor, the type of output tensor is same as input_x and the shape of output tensor is decided by the shape of input_x and the value of input_perm.

Examples

>>> input_tensor = Tensor(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]), mindspore.float32)
>>> perm = (0, 2, 1)
>>> expect = np.array([[[1, 4], [2, 5], [3, 6]], [[7, 10], [8, 11], [9, 12]]])
>>> transpose = Transpose()
>>> output = transpose(input_tensor, perm)

class mindspore.ops.operations.TruncatedNormal(*args, **kwargs)[source]

Returns a tensor of the specified shape filled with truncated normal values.

The generated values follow a normal distribution.

Parameters
Inputs:
• shape (Tensor) - Shape of output tensor. The shape is a 1-D tensor, and type is int.

Outputs:

Tensor, type of output tensor is same as attribute dtype.

Examples

>>> input_shape = Tensor(np.array([1, 2, 3]))
>>> truncated_normal = TruncatedNormal()
>>> output = truncated_normal(input_shape)

class mindspore.ops.operations.TupleToArray(*args, **kwargs)[source]

Converts a tuple to tensor.

If the first number type of tuple is int, the output tensor type is int. Else, the output tensor type is float.

Inputs:
• input_x (tuple) - A tuple of numbers. These numbers have the same type. Only constant value is allowed.

Outputs:

Tensor, if the input tuple contain N numbers, then the output tensor shape is (N,).

Examples

>>> type = TupleToArray()((1,2,3))

class mindspore.ops.operations.UnsortedSegmentSum(*args, **kwargs)[source]

Computes the sum along segments of a tensor.

Calculates a tensor such that $$\text{output}[i] = \sum_{segment\_ids[j] == i} \text{data}[j, \ldots]$$, where $$j$$ is a tuple describing the index of element in data. segment_ids selects which elements in data to sum up. Segment_ids does not need to be sorted, and it does not need to cover all values in the entire valid value range.

If the sum of the given segment_ids $$i$$ is empty, then $$\text{output}[i] = 0$$. If the given segment_ids is negative, the value will be ignored. ‘num_segments’ should be equal to the number of different segment_ids.

Inputs:
• input_x (Tensor) - The shape is $$(x_1, x_2, ..., x_R)$$.

• segment_ids (Tensor) - Set the shape as $$(x_1, x_2, ..., x_N)$$, where 0 < N <= R. Type must be int.

• num_segments (int) - Set $$z$$ as num_segments.

Outputs:

Tensor, the shape is $$(z, x_{N+1}, ..., x_R)$$.

Examples

>>> input_x = [1, 2, 3, 4]
>>> segment_ids = [0, 0, 1, 2]
>>> num_segments = 4
>>> type = P.UnsortedSegmentSum()(input_x, segment_ids, num_segments)

class mindspore.ops.operations.ZerosLike(*args, **kwargs)[source]

Creates a new tensor. All elements value are 0.

Returns a tensor of zeros with the same shape and type as the input tensor.

Inputs:
• input_x (Tensor) - Input tensor.

Outputs:

Tensor, has the same shape and type as input_x but filled with zeros.

Examples

>>> zeroslike = P.ZerosLike()
>>> x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))
>>> output = zeroslike(x)