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

mindspore.ops.operations - 图1
.

  • Outputs:
  • Tensor, has the same shape as input_x.

Examples

  1. Copy>>> acos = ACos()
  2. >>> X = Tensor(np.array([0.74, 0.04, 0.30, 0.56]), ms.float32)
  3. >>> 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

mindspore.ops.operations - 图2
.

  • Outputs:
  • Tensor, has the same shape as the input_x.

Examples

  1. Copy>>> input_x = Tensor(np.array([-1.0, 1.0, 0.0]), mindspore.float32)
  2. >>> abs = Abs()
  3. >>> abs(input_x)
  4. [1.0, 1.0, 0.0]
  • class mindspore.ops.operations.Adam(*args, **kwargs)[source]
  • Updates gradients by Adaptive Moment Estimation (Adam) algorithm.

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

The updating formulas are as follows,

mindspore.ops.operations - 图3

mindspore.ops.operations - 图4
represents the 1st moment vector,
mindspore.ops.operations - 图5
represents the 2nd moment vector,
mindspore.ops.operations - 图6
representsgradient,
mindspore.ops.operations - 图7
represents scaling factor lr,
mindspore.ops.operations - 图8
represent beta1 and beta2,
mindspore.ops.operations - 图9
represents updating step while
mindspore.ops.operations - 图10
and
mindspore.ops.operations - 图11
represent beta1_power andbeta2_power,
mindspore.ops.operations - 图12
represents learning_rate,
mindspore.ops.operations - 图13
represents var,
mindspore.ops.operations - 图14
representsepsilon.

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

    • use_nesterov (bool) – Whether to use Nesterov Accelerated Gradient (NAG) algorithm to update the gradients.If True, updates the gradients using NAG.If False, updates the gradients without using NAG. 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) -

mindspore.ops.operations - 图15
in the updating formula.

  1. -

beta2_power (float) -

mindspore.ops.operations - 图16
in the updating formula.

  1. -

lr (float) -

mindspore.ops.operations - 图17
in the updating formula.

  1. -

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

  1. -

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

  1. -

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

  1. -

gradient (Tensor) - Gradients.

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

  1. Copy>>> class NetAddN(nn.Cell):
  2. >>> def __init__(self):
  3. >>> super(NetAddN, self).__init__()
  4. >>> self.addN = AddN()
  5. >>>
  6. >>> def construct(self, *z):
  7. >>> return self.addN(z)
  8. >>>
  9. >>> net = NetAddN()
  10. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  11. >>> input_y = Tensor(np.array([4, 5, 6]), mindspore.int32)
  12. >>> net(input_x, input_y, input_x, input_y)
  13. 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

mindspore.ops.operations - 图18
.

  • Outputs:
  • Tensor. If the number of devices in the group is N,then the shape of output is

mindspore.ops.operations - 图19
.

Examples

  1. Copy>>> from mindspore.communication.management import init
  2. >>> import mindspore.ops.operations as P
  3. >>> init('nccl')
  4. >>> class Net(nn.Cell):
  5. >>> def __init__(self):
  6. >>> super(Net, self).__init__()
  7. >>> self.allgather = P.AllGather(group="nccl_world_group")
  8. >>>
  9. >>> def construct(self, x):
  10. >>> return self.allgather(x)
  11. >>>
  12. >>> input_ = Tensor(np.ones([2, 8]).astype(np.float32))
  13. >>> net = Net()
  14. >>> 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

mindspore.ops.operations - 图20
.

  • Outputs:
  • Tensor, has the same shape of the input, i.e.,

mindspore.ops.operations - 图21
.The contents depend on the specified operation.

Examples

  1. Copy>>> from mindspore.communication.management import init
  2. >>> import mindspore.ops.operations as P
  3. >>> init('nccl')
  4. >>> class Net(nn.Cell):
  5. >>> def __init__(self):
  6. >>> super(Net, self).__init__()
  7. >>> self.allreduce_sum = P.AllReduce(ReduceOp.SUM, group="nccl_world_group")
  8. >>>
  9. >>> def construct(self, x):
  10. >>> return self.allreduce_sum(x)
  11. >>>
  12. >>> input_ = Tensor(np.ones([2, 8]).astype(np.float32))
  13. >>> net = Net()
  14. >>> output = net(input_)
  • vmimpl(_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 deeplearning 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.

    • gradient_scale (float) – The scale of the gradient. Default: 1.0.

  • Inputs:

    • variable (Tensor) - Weights to be updated.

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

    • learning_rate (float) - Learning rate.

    • gradient (Tensor) - Gradients.

    • momentum (float) - Momentum.

  • Outputs:

  • Tensor, parameters to be updated.

Examples

  1. Copy>>> net = ResNet50()
  2. >>> loss = SoftmaxCrossEntropyWithLogits()
  3. >>> opt = ApplyMomentum(Tensor(np.array([0.001])), Tensor(np.array([0.9])),
  4. filter(lambda x: x.requires_grad, net.get_parameters()))
  5. >>> 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

mindspore.ops.operations - 图22
.

  • Outputs:
  • Tensor, corresponding index and maximum value of input tensor. If keep_dims is true, the output tensors shapeis

mindspore.ops.operations - 图23
. Else, the shape is
mindspore.ops.operations - 图24
.

Examples

  1. Copy>>> input = Tensor(np.random.rand(5))
  2. >>> 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

mindspore.ops.operations - 图25
.

  • Outputs:
  • Tensor, corresponding index and minimum value of input tensor. If keep_dims is true, the output tensors shapeis

mindspore.ops.operations - 图26
. Else, the shape is
mindspore.ops.operations - 图27
.

Examples

  1. Copy>>> input = Tensor(np.random.rand(5))
  2. >>> 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

mindspore.ops.operations - 图28
, the output tensor shape is
mindspore.ops.operations - 图29
.

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

    • output_type (mindspore.dtype) – An optional data type of mindspore.dtype.int32 andmindspore.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

  1. Copy>>> input = Tensor(np.array([2.0, 3.1, 1.2]))
  2. >>> index = Argmax()(input)
  3. >>> 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

mindspore.ops.operations - 图30
, the output tensor shape is
mindspore.ops.operations - 图31
.

  • 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

  1. Copy>>> input = Tensor(np.array([2.0, 3.1, 1.2]))
  2. >>> index = Argmin()(input)
  3. >>> 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

  1. Copy>>> class Net(nn.Cell):
  2. >>> def __init__(self):
  3. >>> super(Net, self).__init__()
  4. >>> self.y = mindspore.Parameter(Tensor([1.0], mindspore.float32), name="y")
  5. >>>
  6. >>> def construct(self, x):
  7. >>> Assign()(self.y, x)
  8. >>> return x
  9. >>> x = Tensor([2.0], mindspore.float32)
  10. >>> net = Net()
  11. >>> net(x)
  • class mindspore.ops.operations.AssignAdd(*args, **kwargs)[source]
  • Updates a Parameter by adding a value to it.

    • Inputs:
      • input_x (Parameter) - The Parameter.

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

Examples

  1. Copy>>> class Net(Cell):
  2. >>> def __init__(self):
  3. >>> self.AssignAdd = P.AssignAdd()
  4. >>> self.inputdata = Parameter(initializer(1, [1], mindspore.int64), name="global_step")
  5. >>>
  6. >>> def construct(self, x):
  7. >>> self.AssignAdd(self.inputdata, x)
  8. >>> return self.inputdata
  9. >>>
  10. >>> net = Net()
  11. >>> x = Tensor(np.ones([1]).astype(np.int64)*100)
  12. >>> 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

  1. Copy>>> class Net(Cell):
  2. >>> def __init__(self):
  3. >>> self.AssignSub = P.AssignSub()
  4. >>> self.inputdata = Parameter(initializer(1, [1], mindspore.int64), name="global_step")
  5. >>>
  6. >>> def construct(self, x):
  7. >>> self.AssignSub(self.inputdata, x)
  8. >>> return self.inputdata
  9. >>>
  10. >>> net = Net()
  11. >>> x = Tensor(np.ones([1]).astype(np.int64)*100)
  12. >>> 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

mindspore.ops.operations - 图32
, AvgPool2d outputsregional average in the
mindspore.ops.operations - 图33
-dimension. Given kernel size
mindspore.ops.operations - 图34
and stride
mindspore.ops.operations - 图35
, the operation is as follows.

mindspore.ops.operations - 图36

  • Parameters
    • ksize (Union__[int, tuple[int]__]) – The size of the window to take a average over, that should be a tupleof 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 forwidth and height. Default: 1.

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

  • Inputs:

    • input (Tensor) - Tensor of shape

mindspore.ops.operations - 图37
.

  • Outputs:
  • Tensor, with shape

mindspore.ops.operations - 图38
.

  • 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

mindspore.ops.operations - 图39
,where
mindspore.ops.operations - 图40
represents the batch size which can be multidimensional,
mindspore.ops.operations - 图41
and
mindspore.ops.operations - 图42
are thesize of the last two dimensions. If transpose_a is True, its shape should be
mindspore.ops.operations - 图43
.

  1. -

input_y (Tensor) - The second tensor to be multiplied. The shape of the tensor is

mindspore.ops.operations - 图44
. Iftranspose_b is True, its shape should be
mindspore.ops.operations - 图45
.

  • Outputs:
  • Tensor, the shape of the output tensor is

mindspore.ops.operations - 图46
.

Examples

  1. Copy>>> input_x = Tensor(np.ones(shape=[2, 4, 1, 3]), mindspore.float32)
  2. >>> input_y = Tensor(np.ones(shape=[2, 4, 3, 4]), mindspore.float32)
  3. >>> batmatmul = BatchMatMul()
  4. >>> output = batmatmul(input_x, input_y)
  5. >>>
  6. >>> input_x = Tensor(np.ones(shape=[2, 4, 3, 1]), mindspore.float32)
  7. >>> input_y = Tensor(np.ones(shape=[2, 4, 3, 4]), mindspore.float32)
  8. >>> batmatmul = BatchMatMul(transpose_a=True)
  9. >>> 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 operationapplies Batch Normalization over input to avoid internal covariate shift as describedin the paper Batch Normalization: Accelerating Deep Network Training by Reducing InternalCovariate Shift. It rescales and recenters thefeatures using a mini-batch of data and the learned parameters which can be describedin the following formula,

mindspore.ops.operations - 图47

where

mindspore.ops.operations - 图48
is scale,
mindspore.ops.operations - 图49
is bias,
mindspore.ops.operations - 图50
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

mindspore.ops.operations - 图51
.

  1. -

scale (Tensor) - Tensor of shape

mindspore.ops.operations - 图52
.

  1. -

bias (Tensor) - Tensor of shape

mindspore.ops.operations - 图53
.

  1. -

mean (Tensor) - Tensor of shape

mindspore.ops.operations - 图54
.

  1. -

variance (Tensor) - Tensor of shape

mindspore.ops.operations - 图55
.

  • 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

mindspore.ops.operations - 图56
.

  1. -

updated_scale (Tensor) - Tensor of shape

mindspore.ops.operations - 图57
.

  1. -

updated_bias (Tensor) - Tensor of shape

mindspore.ops.operations - 图58
.

  1. -

reserve_space_1 (Tensor) - Tensor of shape

mindspore.ops.operations - 图59
.

  1. -

reserve_space_2 (Tensor) - Tensor of shape

mindspore.ops.operations - 图60
.

  1. -

reserve_space_3 (Tensor) - Tensor of shape

mindspore.ops.operations - 图61
.

  • 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 axisexcept for the channel axis.

  • Inputs:
    • input_x (Tensor) - Input value, with shape

mindspore.ops.operations - 图62
or
mindspore.ops.operations - 图63
.

  1. -

bias (Tensor) - Bias value, with shape

mindspore.ops.operations - 图64
.

  • 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

mindspore.ops.operations - 图65
, input label as
mindspore.ops.operations - 图66
, output as
mindspore.ops.operations - 图67
.Let,

mindspore.ops.operations - 图68

Then,

mindspore.ops.operations - 图69

  • 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

  1. Copy>>> boundingbox_decode = BoundingBoxDecode(means=(0.0, 0.0, 0.0, 0.0), stds=(1.0, 1.0, 1.0, 1.0),
  2. max_shape=(768, 1280), wh_ratio_clip=0.016)
  3. >>> 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

  1. Copy>>> boundingbox_encode = BoundingBoxEncode(means=(0.0, 0.0, 0.0, 0.0), stds=(1.0, 1.0, 1.0, 1.0))
  2. >>> 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 onethat 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

mindspore.ops.operations - 图70
.

  • Outputs:
  • Tensor, has the same shape of the input, i.e.,

mindspore.ops.operations - 图71
.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

  1. Copy>>> from mindspore.communication.management import init
  2. >>> import mindspore.ops.operations as P
  3. >>> init('nccl')
  4. >>> class Net(nn.Cell):
  5. >>> def __init__(self):
  6. >>> super(Net, self).__init__()
  7. >>> self.broadcast = P.Broadcast(1)
  8. >>>
  9. >>> def construct(self, x):
  10. >>> return self.broadcast((x,))
  11. >>>
  12. >>> input_ = Tensor(np.ones([2, 8]).astype(np.float32))
  13. >>> net = Net()
  14. >>> 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

mindspore.ops.operations - 图72
.The tensor to be casted.

  1. -

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

  • Outputs:
  • Tensor, the shape of tensor is

mindspore.ops.operations - 图73
, same as input_x.

Examples

  1. Copy>>> input_np = np.random.randn(2, 3, 4, 5).astype(np.float32)
  2. >>> input_x = Tensor(input_np)
  3. >>> type_dst = mindspore.int32
  4. >>> cast = Cast()
  5. >>> result = cast(input_x, type_dst)
  6. >>> 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

mindspore.ops.operations - 图74
. Set the number of input tensors as N. For the
mindspore.ops.operations - 图75
-th tensor
mindspore.ops.operations - 图76
hasthe shape
mindspore.ops.operations - 图77
.
mindspore.ops.operations - 图78
is the
mindspore.ops.operations - 图79
-th dimension of the
mindspore.ops.operations - 图80
-th tensor. Then, the output tensor shape is

mindspore.ops.operations - 图81

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

  • Inputs:

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

  • Tensor, the shape is

mindspore.ops.operations - 图82
.

Examples

  1. Copy>>> data1 = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))
  2. >>> data2 = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))
  3. >>> op = Concat()
  4. >>> output = op((data1, data2))
  • class mindspore.ops.operations.ConcatOffset(*args, **kwargs)[source]
  • primitive for computing Concat’s gradient.
  • 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. ControlDependtells the engine that the destination operations should depend on the source operation which means the sourceoperations 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 donot 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 thatused 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 thatused 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

  1. Copy>>> # In the following example, the data calculation uses original global_step. After the calculation the global
  2. >>> # step should be increased, so the add operation should depend on the data calculation operation.
  3. >>> class Net(nn.Cell):
  4. >>> def __init__(self):
  5. >>> super(Net, self).__init__()
  6. >>> self.global_step = Parameter(initializer(0, [1]), name="global_step")
  7. >>> self.rate = 0.2
  8. >>> self.control_depend = ControlDepend()
  9. >>>
  10. >>> def construct(self, x):
  11. >>> data = self.rate * self.global_step + x
  12. >>> added_global_step = self.global_step + 1
  13. >>> self.global_step = added_global_step
  14. >>> self.control_depend(data, added_global_step)
  15. >>> 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

mindspore.ops.operations - 图83
,where
mindspore.ops.operations - 图84
is batch size and
mindspore.ops.operations - 图85
is channel number. For each batch of shape
mindspore.ops.operations - 图86
, the formula is defined as:

mindspore.ops.operations - 图87

where

mindspore.ops.operations - 图88
is cross correlation operator,
mindspore.ops.operations - 图89
is the input channel number,
mindspore.ops.operations - 图90
rangesfrom
mindspore.ops.operations - 图91
to
mindspore.ops.operations - 图92
,
mindspore.ops.operations - 图93
corresponds to
mindspore.ops.operations - 图94
-th channel of the
mindspore.ops.operations - 图95
-thfilter and
mindspore.ops.operations - 图96
corresponds to the
mindspore.ops.operations - 图97
-th channel of the output.
mindspore.ops.operations - 图98
is a sliceof kernel and it has shape
mindspore.ops.operations - 图99
, where
mindspore.ops.operations - 图100
and
mindspore.ops.operations - 图101
are height and width of the convolution kernel. The full kernel has shape
mindspore.ops.operations - 图102
, where group is the group numberto split the input in the channel dimension.

If the ‘pad_mode’ is set to be “valid”, the output height and width will be

mindspore.ops.operations - 图103
and
mindspore.ops.operations - 图104
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.

    • pad_mode (str) – “valid”, “same”, “pad” the mode to fill padding. Default: “valid”.

    • pad (int) – The pad value to fill. Default: 0.

    • 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

mindspore.ops.operations - 图105
.

  1. -

weight (Tensor) - Set size of kernel is

mindspore.ops.operations - 图106
, then the shape is
mindspore.ops.operations - 图107
.

  • Outputs:
  • Tensor of shape

mindspore.ops.operations - 图108
.

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

      • pad_mode (str) – “valid”, “same”, “pad” the mode to fill padding. Default: “valid”.

      • pad (int) – The pad value to fill. Default: 0.

      • 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

    • Tensor, the gradients of convolution.
  • class mindspore.ops.operations.Cos(*args, **kwargs)[source]
  • Computes cosine of input element-wise.

    • Inputs:
      • input_x (Tensor) - The shape of tensor is

mindspore.ops.operations - 图109
.

  • Outputs:
  • Tensor, has the same shape as input_x.

Examples

  1. Copy>>> cos = Cos()
  2. >>> X = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), ms.float32)
  3. >>> 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

  1. Copy>>> data = Tensor(np.array([a, b, c]).astype(np.float32))
  2. >>> op0 = CumProd()
  3. >>> output = op0(data, 0) # output=[a, a * b, a * b * c]
  4. >>> op1 = CumProd(exclusive=True)
  5. >>> output = op1(data, 0) # output=[1, a, a * b]
  6. >>> op2 = CumProd(reverse=True)
  7. >>> output = op2(data, 0) # output=[a * b * c, b * c, c]
  8. >>> op3 = CumProd(exclusive=True, reverse=True)
  9. >>> 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

  1. Copy>>> input = Tensor(np.array([[3, 4, 6, 10],[1, 6, 7, 9],[4, 3, 8, 7],[1, 3, 7, 9]]).astype(np.float32))
  2. >>> cumsum = CumSum()
  3. >>> output = cumsum(input, 1)
  4. [[ 3. 7. 13. 23.]
  5. [ 1. 7. 14. 23.]
  6. [ 4. 7. 15. 22.]
  7. [ 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

mindspore.ops.operations - 图110
.

  • Outputs:
  • mindspore.dtype, the data type of a tensor.

Examples

  1. Copy>>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  2. >>> 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

mindspore.ops.operations - 图111
.

The output tensor’s weight dimension is

mindspore.ops.operations - 图112
.

The depth of output tensor is

mindspore.ops.operations - 图113
.

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

  1. Copy>>> x = Tensor(np.random.rand(1,12,1,1), mindspore.float32)
  2. >>> block_size = 2
  3. >>> op = DepthToSpace(block_size)
  4. >>> output = op(x)
  5. >>> 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

mindspore.ops.operations - 图114
where
mindspore.ops.operations - 图115
is the batch size and afilter tensor with kernel size
mindspore.ops.operations - 图116
, containing
mindspore.ops.operations - 图117
convolutional filters of depth 1; it applies different filters to each input channel (channel_multiplier channelsfor each with default value 1), then concatenates the results together. The output has
mindspore.ops.operations - 图118
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.

    • pad_mode (str) – “valid”, “same”, “pad” the mode to fill padding. Default: “valid”.

    • pad (int) – The pad value to fill. Default: 0.

    • 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

mindspore.ops.operations - 图119
.

  1. -

weight (Tensor) - Set size of kernel is

mindspore.ops.operations - 图120
, then the shape is
mindspore.ops.operations - 图121
.

  • Outputs:
  • Tensor of shape

mindspore.ops.operations - 图122
.

  • class mindspore.ops.operations.Diag(*args, **kwargs)[source]
  • Construct a diagonal tensor with a given diagonal values.

Assume input_x has dimensions

mindspore.ops.operations - 图123
, the output is a tensor ofrank 2k with dimensions
mindspore.ops.operations - 图124
where:
mindspore.ops.operations - 图125
and 0 everywhere else.

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

  • Tensor.

Examples

  1. Copy>>> input_x = Tensor([1, 2, 3, 4])
  2. >>> diag = P.Diag()
  3. >>> diag(x)
  4. [[1, 0, 0, 0],
  5. [0, 2, 0, 0],
  6. [0, 0, 3, 0],
  7. [0, 0, 0, 4]]
  • class mindspore.ops.operations.DiagPart(*args, **kwargs)[source]
  • Extract the diagonal part from given tensor.

Assume input has dimensions

mindspore.ops.operations - 图126
, the output is a tensorof rank k with dimensions
mindspore.ops.operations - 图127
where:
mindspore.ops.operations - 图128
.

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

  • Tensor.

  • Examples

  1. Copy>>> input_x = Tensor([[1, 0, 0, 0],
  2. >>> [0, 2, 0, 0],
  3. >>> [0, 0, 3, 0],
  4. >>> [0, 0, 0, 4]])
  5. >>> diag_part = P.DiagPart()
  6. >>> diag_part(x)
  7. [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’ ora 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

  1. Copy>>> input_x = Tensor(np.array([-4.0, 5.0, 6.0]), mindspore.float32)
  2. >>> input_y = Tensor(np.array([3.0, 2.0, 3.0]), mindspore.float32)
  3. >>> div = Div()
  4. >>> div(input_x, input_y)
  5. [-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 theshape 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. keepprob = 0.9,means dropping out 10% of input units. The value of _keep_prob is same as the input keep_prob ofDropoutGenMask.

  • Outputs:

  • Tensor, the value that applied dropout on.

Examples

  1. Copy>>> x = Tensor(np.ones([20, 16, 50]), mindspore.float32)
  2. >>> shape = (20, 16, 50)
  3. >>> keep_prob = Tensor(0.5, mindspore.float32)
  4. >>> dropout_gen_mask = DropoutGenMask()
  5. >>> dropout_do_mask = DropoutDoMask()
  6. >>> mask = dropout_gen_mask(shape, keep_prob)
  7. >>> output = dropout_do_mask(x, mask, keep_prob)
  8. >>> 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

  1. Copy>>> dropout_gen_mask = DropoutGenMask()
  2. >>> shape = (20, 16, 50)
  3. >>> keep_prob = Tensor(0.5, mindspore.float32)
  4. >>> mask = dropout_gen_mask(shape, keep_prob)
  • 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, ora number or a bool object.

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

  • Outputs:

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

Examples

  1. Copy>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.float32)
  2. >>> equal = Equal()
  3. >>> equal(input_x, 2.0)
  4. [False, True, False]
  5. >>>
  6. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  7. >>> input_y = Tensor(np.array([1, 2, 4]), mindspore.int32)
  8. >>> equal = Equal()
  9. >>> equal(input_x, input_y)
  10. [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

  1. Copy>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2. >>> input_y = Tensor(np.array([1, 2, 4]), mindspore.int32)
  3. >>> equal_count = EqualCount()
  4. >>> equal_count(input_x, input_y)
  5. [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

  1. Copy>>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  2. >>> exp = Exp()
  3. >>> exp(input_x)
  4. [ 2.71828183, 7.3890561 , 54.59815003]
  • class mindspore.ops.operations.ExpandDims(*args, **kwargs)[source]
  • Adds an additional dimension at the given axis.

Note

If the specified axis is a negative number, the index is countedbackward 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

mindspore.ops.operations - 图129
.

  1. -

axis (int) - Specifies the dimension index at which to expandthe 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

mindspore.ops.operations - 图130
if thevalue of axis is 0.

Examples

  1. Copy>>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  2. >>> expand_dims = ExpandDims()
  3. >>> 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

  1. Copy>>> eye = P.Eye()
  2. >>> 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

  1. Copy>>> fill = P.Fill()
  2. >>> 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

mindspore.ops.operations - 图131
to be flattened.

  • Outputs:
  • Tensor, the shape of the output tensor is

mindspore.ops.operations - 图132
, where
mindspore.ops.operations - 图133
isthe product of the remaining dimension.

Examples

  1. Copy>>> input_tensor = Tensor(np.ones(shape=[1, 2, 3, 4]), mindspore.float32)
  2. >>> flatten = Flatten()
  3. >>> output = flatten(input_tensor)
  4. >>> 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

  1. Copy>>> input_x = Tensor(np.array([1.1, 2.5, -1.5]), mindspore.float32)
  2. >>> floor = Floor()
  3. >>> floor(input_x)
  4. [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’ ora number.

  • Outputs:

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

Examples

  1. Copy>>> input_x = Tensor(np.array([2, 4, -1]), mindspore.int32)
  2. >>> input_y = Tensor(np.array([3, 3, 3]), mindspore.int32)
  3. >>> floor_div = FloorDiv()
  4. >>> floor_div(input_x, input_y)
  5. [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 appliesBatch Normalization over input to avoid internal covariate shift as described in thepaper Batch Normalization: Accelerating Deep Network Training by Reducing InternalCovariate Shift. It rescales and recenters thefeature using a mini-batch of data and the learned parameters which can be describedin the following formula.

mindspore.ops.operations - 图134

where

mindspore.ops.operations - 图135
is scale,
mindspore.ops.operations - 图136
is bias,
mindspore.ops.operations - 图137
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.

mindspore.ops.operations - 图138
).Momentum value should be [0, 1]. Default: 0.9.

  • Inputs:
    • input_x (Tensor) - Tensor of shape

mindspore.ops.operations - 图139
.

  1. -

scale (Tensor) - Tensor of shape

mindspore.ops.operations - 图140
.

  1. -

bias (Tensor) - Tensor of shape

mindspore.ops.operations - 图141
.

  1. -

mean (Tensor) - Tensor of shape

mindspore.ops.operations - 图142
.

  1. -

variance (Tensor) - Tensor of shape

mindspore.ops.operations - 图143
.

  • 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

mindspore.ops.operations - 图144
.

  1. -

updated_bias (Tensor) - Tensor of shape

mindspore.ops.operations - 图145
.

  1. -

updated_moving_mean (Tensor) - Tensor of shape

mindspore.ops.operations - 图146
.

  1. -

updated_moving_variance (Tensor) - Tensor of shape

mindspore.ops.operations - 图147
.

  • 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

  1. Copy>>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
  2. >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
  3. >>> op = GatherNd()
  4. >>> 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

mindspore.ops.operations - 图148
.The original Tensor.

  1. -

input_indices (Tensor) - The shape of tensor is

mindspore.ops.operations - 图149
.Specifies the indices of elements of the original Tensor. Must be in the range[0, input_param.shape()[axis]).

  1. -

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

  • Outputs:
  • Tensor, the shape of tensor is

mindspore.ops.operations - 图150
.

Examples

  1. Copy>>> params = Tensor(np.array([[1, 2, 7, 42], [3, 4, 54, 22], [2, 2, 55, 3]]), mindspore.float32)
  2. >>> indices = Tensor(np.array([1, 2]), mindspore.int32)
  3. >>> axis = 1
  4. >>> out = GatherV2()(params, indices, axis)
  • class mindspore.ops.operations.GeSwitch(*args, **kwargs)[source]
  • Adds control switch to data.

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

  1. Copy>>> class Net(nn.Cell):
  2. >>> def __init__(self):
  3. >>> super(Net, self).__init__()
  4. >>> self.square = P.Square()
  5. >>> self.add = P.TensorAdd()
  6. >>> self.value = Tensor(np.full((1), 3, dtype=np.float32))
  7. >>> self.switch = P.GeSwitch()
  8. >>> self.merge = P.Merge()
  9. >>> self.less = P.Less()
  10. >>>
  11. >>> def construct(self, x, y):
  12. >>> cond = self.less(x, y)
  13. >>> st1, sf1 = self.switch(x, cond)
  14. >>> st2, sf2 = self.switch(y, cond)
  15. >>> add_ret = self.add(st1, st2)
  16. >>> st3, sf3 = self.switch(self.value, cond)
  17. >>> sq_ret = self.square(sf3)
  18. >>> ret = self.merge((add_ret, sq_ret))
  19. >>> return ret[0]
  20. >>>
  21. >>> x = Tensor(x_init, dtype=mindspore.float32)
  22. >>> y = Tensor(y_init, dtype=mindspore.float32)
  23. >>> net = Net()
  24. >>> 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:

mindspore.ops.operations - 图151

where

mindspore.ops.operations - 图152
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

  1. Copy>>> tensor = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
  2. >>> gelu = Gelu()
  3. >>> 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 initdataset 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

  1. Copy>>> get_next = GetNext([mindspore.float32, mindspore.int32], [[32, 1, 28, 28], [10]], 'shared_name')
  2. >>> feature, label = get_next()
  • class mindspore.ops.operations.Greater(*args, **kwargs)[source]
  • Computes the boolean value of

mindspore.ops.operations - 图153
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’ ora number.

  • Outputs:

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

Examples

  1. Copy>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2. >>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
  3. >>> greater = Greater()
  4. >>> greater(input_x, input_y)
  5. [False, True, False]
  • class mindspore.ops.operations.GreaterEqual(*args, **kwargs)[source]
  • Computes the boolean value of

mindspore.ops.operations - 图154
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’ ora number.

  • Outputs:

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

Examples

  1. Copy>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2. >>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
  3. >>> greater_equal = GreaterEqual()
  4. >>> greater_equal(input_x, input_y)
  5. [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

  1. Copy>>> iou = IOU()
  2. >>> anchor_boxes = Tensor(np.random.randint(1,5, [10, 4]))
  3. >>> gt_boxes = Tensor(np.random.randint(1,5, [3, 4]))
  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

  1. Copy>>> class Net(nn.Cell):
  2. >>> def __init__(self):
  3. >>> super(Net, self).__init__()
  4. >>> self.summary = P.ImageSummary()
  5. >>>
  6. >>> def construct(self, x):
  7. >>> name = "image"
  8. >>> out = self.summary(name, x)
  9. >>> 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

  1. Copy>>> def clip_gradient(dx):
  2. >>> ret = dx
  3. >>> if ret > 1.0:
  4. >>> ret = 1.0
  5. >>>
  6. >>> if ret < 0.2:
  7. >>> ret = 0.2
  8. >>>
  9. >>> return ret
  10. >>>
  11. >>> clip = P.InsertGradientOf(clip_gradient)
  12. >>> def InsertGradientOfClipDemo():
  13. >>> def clip_test(x, y):
  14. >>> x = clip(x)
  15. >>> y = clip(y)
  16. >>> c = x * y
  17. >>> return c
  18. >>>
  19. >>> @ms_function
  20. >>> def f(x, y):
  21. >>> return clip_test(x, y)
  22. >>>
  23. >>> def fd(x, y):
  24. >>> return C.grad_all(clip_test)(x, y)
  25. >>>
  26. >>> print("forward: ", f(1.1, 0.1))
  27. >>> print("clip_gradient:", fd(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 dimensionThis operation calculates the inverse of the index replacement. It requires a1-dimensional tuple x, which represents the array starting at zero,and swaps each value with its index position. In other words, for the outputtuple y and the input tuple x, this operation calculates the following:

mindspore.ops.operations - 图155
.

Note

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

  • Inputs:
    • input_x (tuple[int]) - The input tuple is constructed by multipleintegers, i.e.,

mindspore.ops.operations - 图156
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

  1. Copy>>> invert = InvertPermutation()
  2. >>> input_data = (3, 4, 0, 2, 1)
  3. >>> output = invert(input_data)
  4. >>> 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

  1. Copy>>> a = 1
  2. >>> 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

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

mindspore.ops.operations - 图157

where

mindspore.ops.operations - 图158
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:

    • Tensor, representing the new gradient.
  • 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 paperLayer Normalization.

mindspore.ops.operations - 图159

where

mindspore.ops.operations - 图160
is scale,
mindspore.ops.operations - 图161
is bias,
mindspore.ops.operations - 图162
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) toapply LayerNorm, the value should be in [-1, rank(input)). Default: 1.

  • Inputs:

    • input_x (Tensor) - Tensor of shape

mindspore.ops.operations - 图163
.The input of LayerNorm.

  1. -

gamma (Tensor) - Tensor of shape

mindspore.ops.operations - 图164
.The learnable parameter gamma as the scale on norm.

  1. -

beta (Tensor) - Tensor of shape

mindspore.ops.operations - 图165
.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

mindspore.ops.operations - 图166
.

  1. -

updated_gamma (Tensor) - Tensor of shape

mindspore.ops.operations - 图167
.

  1. -

updated_beta (Tensor) - Tensor of shape

mindspore.ops.operations - 图168
.

  • class mindspore.ops.operations.Less(*args, **kwargs)[source]
  • Computes the boolean value of

mindspore.ops.operations - 图169
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’ ora number.

  • Outputs:

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

Examples

  1. Copy>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2. >>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
  3. >>> less = Less()
  4. >>> less(input_x, input_y)
  5. [False, False, True]
  • class mindspore.ops.operations.LessEqual(*args, **kwargs)[source]
  • Computes the boolean value of

mindspore.ops.operations - 图170
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’ ora number.

  • Outputs:

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

Examples

  1. Copy>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2. >>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
  3. >>> less_equal = LessEqual()
  4. >>> less_equal(input_x, input_y)
  5. [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

  1. Copy>>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  2. >>> log = Log()
  3. >>> log(input_x)
  4. [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

mindspore.ops.operations - 图171
then for each element
mindspore.ops.operations - 图172
the Log Softmax function is shown as follows:

mindspore.ops.operations - 图173

where

mindspore.ops.operations - 图174
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

  1. Copy>>> input_x = Tensor(np.array([True, False, True]), mindspore.bool_)
  2. >>> input_y = Tensor(np.array([True, True, False]), mindspore.bool_)
  3. >>> logical_and = LogicalAnd()
  4. >>> logical_and(input_x, input_y)
  5. [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

  1. Copy>>> input_x = Tensor(np.array([True, False, True]), mindspore.bool_)
  2. >>> logical_not = LogicalNot()
  3. >>> logical_not(input_x)
  4. [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

  1. Copy>>> input_x = Tensor(np.array([True, False, True]), mindspore.bool_)
  2. >>> input_y = Tensor(np.array([True, True, False]), mindspore.bool_)
  3. >>> logical_or = LogicalOr()
  4. >>> logical_or(input_x, input_y)
  5. [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

  1. Copy>>> from mindspore.ops import functional as F
  2. >>> class Net(nn.Cell):
  3. >>> def __init__(self):
  4. >>> super(Net, self).__init__()
  5. >>> self.y = Parameter(Tensor(np.ones([6, 8, 10], np.int32)), name="y")
  6. >>> self.make_ref_key = MakeRefKey("y")
  7. >>>
  8. >>> def construct(self, x):
  9. >>> key = self.make_ref_key()
  10. >>> ref = F.make_ref(key, x, self.y)
  11. >>> return ref + x
  12. >>>
  13. >>> x = Tensor(np.ones([3, 4, 5], np.int32))
  14. >>> net = Net()
  15. >>> 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

mindspore.ops.operations - 图175
. Iftranspose_a is True, its shape should be
mindspore.ops.operations - 图176
after transposing.

  1. -

input_y (Tensor) - The second tensor to be multiplied. The shape of the tensor is

mindspore.ops.operations - 图177
. Iftranspose_b is True, its shape should be
mindspore.ops.operations - 图178
after transpose.

  • Outputs:
  • Tensor, the shape of the output tensor is

mindspore.ops.operations - 图179
.

Examples

  1. Copy>>> input_x = Tensor(np.ones(shape=[1, 3]), mindspore.float32)
  2. >>> input_y = Tensor(np.ones(shape=[3, 4]), mindspore.float32)
  3. >>> matmul = MatMul()
  4. >>> 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

mindspore.ops.operations - 图180
, MaxPool outputsregional maximum in the
mindspore.ops.operations - 图181
-dimension. Given kernel size
mindspore.ops.operations - 图182
and stride
mindspore.ops.operations - 图183
, the operation is as follows.

mindspore.ops.operations - 图184

  • Parameters
    • ksize (Union__[int, tuple[int]__]) – The size of the window to take a max over, that should be a tupleof 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 forwidth and height. Default: 1.

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

  • Inputs:

    • input (Tensor) - Tensor of shape

mindspore.ops.operations - 图185
.

  • Outputs:
  • Tensor, with shape

mindspore.ops.operations - 图186
.

  • 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

mindspore.ops.operations - 图187
, MaxPool outputsregional maximum in the
mindspore.ops.operations - 图188
-dimension. Given kernel size
mindspore.ops.operations - 图189
and stride
mindspore.ops.operations - 图190
, the operation is as follows.

mindspore.ops.operations - 图191

  • Parameters
    • pad_mode (str) – “valid”, “same”, “pad” the mode to fill padding. Default: “valid”.

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

    • pad (Union__[int, tuple[int]__]) – If pad_mode is pad, the pad value to fill, two int for widthand height. Default: 0.

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

  • Inputs:

    • input (Tensor) - Tensor of shape

mindspore.ops.operations - 图192
.

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

    • output (Tensor) - Maxpooling result, with shape

mindspore.ops.operations - 图193
.

  1. -

mask (Tensor) - Max values’ index represented by the mask.

  • 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’ ora number.

  • Outputs:

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

Examples

  1. Copy>>> input_x = Tensor(np.array([1.0, 5.0, 3.0]), mindspore.float32)
  2. >>> input_y = Tensor(np.array([4.0, 2.0, 6.0]), mindspore.float32)
  3. >>> maximum = Maximum()
  4. >>> maximum(input_x, input_y)
  5. [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’ ora number.

  • Outputs:

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

Examples

  1. Copy>>> input_x = Tensor(np.array([1.0, 5.0, 3.0]), mindspore.float32)
  2. >>> input_y = Tensor(np.array([4.0, 2.0, 6.0]), mindspore.float32)
  3. >>> minimum = Minimum()
  4. >>> minimum(input_x, input_y)
  5. [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’ ora number.

  • Outputs:

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

Examples

  1. Copy>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2. >>> input_y = Tensor(np.array([4, 5, 6]), mindspore.int32)
  3. >>> mul = Mul()
  4. >>> mul(input_x, input_y)
  5. [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 toIOU. 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

mindspore.ops.operations - 图194
. Input bounding boxes.N is the number of input bounding boxes. Every bounding boxcontains 5 values, the first 4 values are the coordinates of boundingbox, 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

mindspore.ops.operations - 图195
. Bounding boxeslist after non-max suppression calculation.

  1. -

selected_idx (Tensor) - The shape of tensor is

mindspore.ops.operations - 图196
. The indexes list ofvalid input bounding boxes.

  1. -

selected_mask (Tensor) - The shape of tensor is

mindspore.ops.operations - 图197
. A mask list ofvalid output bounding boxes.

Examples

  1. Copy>>> bbox = np.random.rand(128, 5)
  2. >>> bbox[:, 2] += bbox[:, 0]
  3. >>> bbox[:, 3] += bbox[:, 1]
  4. >>> inputs = Tensor(bbox)
  5. >>> nms = NMSWithMask(0.5)
  6. >>> 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

  1. Copy>>> alloc_status = NPUAllocFloatStatus()
  2. >>> init = alloc_status()
  3. 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 theNPUClearFloatStatus 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

  1. Copy>>> alloc_status = NPUAllocFloatStatus()
  2. >>> get_status = NPUGetFloatStatus()
  3. >>> clear_status = NPUClearFloatStatus()
  4. >>> init = alloc_status()
  5. >>> flag = get_status(init)
  6. >>> clear = clear_status(init)
  7. 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, thereis 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

  1. Copy>>> alloc_status = NPUAllocFloatStatus()
  2. >>> get_status = NPUGetFloatStatus()
  3. >>> init = alloc_status()
  4. >>> flag = get_status(init)
  5. 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, ora number or a bool object.

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

  • Outputs:

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

Examples

  1. Copy>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.float32)
  2. >>> not_equal = NotEqual()
  3. >>> not_equal(input_x, 2.0)
  4. [True, False, True]
  5. >>>
  6. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  7. >>> input_y = Tensor(np.array([1, 2, 4]), mindspore.int32)
  8. >>> not_equal = NotEqual()
  9. >>> not_equal(input_x, input_y)
  10. [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 allother 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 shapewill 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

mindspore.ops.operations - 图198
.

  1. -

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

  1. -

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

  1. -

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

  • Outputs:
  • Tensor, one_hot tensor. Tensor of shape

mindspore.ops.operations - 图199
.

Examples

  1. Copy>>> indices = Tensor(np.array([0, 1, 2]), mindspore.int32)
  2. >>> depth, on_value, off_value = 3, Tensor(1.0, mindspore.float32), Tensor(0.0, mindspore.float32)
  3. >>> onehot = OneHot()
  4. >>> result = onehot(indices, depth, on_value, off_value)
  5. [[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

  1. Copy>>> oneslike = P.OnesLike()
  2. >>> x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))
  3. >>> 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 onImageNet Classification. Defined as follows:

mindspore.ops.operations - 图200

where

mindspore.ops.operations - 图201
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]
  • Pads input tensor according to the paddings.

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

    • Inputs:

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

    • Tensor, the tensor after padding.

Examples

  1. Copy>>> input_tensor = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
  2. >>> pad_op = Pad(((1, 2), (2, 1)))
  3. >>> output_tensor = pad_op(input_tensor)
  4. >>> assert output_tensor == Tensor(np.array([[ 0. , 0. , 0. , 0. , 0. , 0. ],
  5. >>> [ 0. , 0. , -0.1, 0.3, 3.6, 0. ],
  6. >>> [ 0. , 0. , 0.4, 0.5, -3.2, 0. ],
  7. >>> [ 0. , 0. , 0. , 0. , 0. , 0. ],
  8. >>> [ 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 tobroadcast to the shape of the input_x.

    • Outputs:

    • Tensor, has the same shape as the input_x.

Examples

  1. Copy>>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  2. >>> input_y = 3.0
  3. >>> pow = Pow()
  4. >>> pow(input_x, input_y)
  5. [1.0, 8.0, 64.0]
  6. >>>
  7. >>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  8. >>> input_y = Tensor(np.array([2.0, 4.0, 3.0]), mindspore.float32)
  9. >>> pow = Pow()
  10. >>> pow(input_x, input_y)
  11. [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

  1. Copy>>> class PrintDemo(nn.Cell):
  2. >>> def __init__(self,):
  3. >>> super(PrintDemo, self).__init__()
  4. >>> self.print = P.Print()
  5. >>>
  6. >>> def construct(self, x):
  7. >>> self.print(x)
  8. >>> 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 thefeature map. No quantization is performed on any coordinates involved in the RoI, its bins, or the samplingpoints. 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 inputfeature map coordinates. Suppose the height of a RoI is ori_h in the raw image and fea_h in theinput 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 ofthe 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 theindex of image. top_left_x and top_left_y represent the x, y coordinates of the top left cornerof 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

  1. Copy>>> input_tensor = Tensor(np.array([[[[1., 2.], [3., 4.]]]]), mindspore.float32)
  2. >>> rois = Tensor(np.array([[0, 0.2, 0.3, 0.2, 0.3]]), mindspore.float32)
  3. >>> roi_align = P.ROIAlign(1, 1, 0.5, 2)
  4. >>> output_tensor = roi_align(input_tensor, rois)
  5. >>> 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 indexof 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

  1. Copy>>> rnd_choice_mask = RandomChoiceWithMask()
  2. >>> input_x = Tensor(np.ones(shape=[240000, 4]), ms.bool_)
  3. >>> output_y, output_mask = rnd_choice_mask(input_x)
  • 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 tensoris the number of indices required to uniquely select each element of the tensor.

  • Inputs:
    • input_x (Tensor) - The shape of tensor is

mindspore.ops.operations - 图202
.

  • Outputs:
  • Tensor. 0-D int32 Tensor representing the rank of input, i.e.,

mindspore.ops.operations - 图203
.

Examples

  1. Copy>>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  2. >>> rank = Rank()
  3. >>> rank(input_tensor)
  • class mindspore.ops.operations.ReLU(*args, **kwargs)[source]
  • Computes ReLU(Rectified Linear Unit) of input tensor element-wise.

It returns

mindspore.ops.operations - 图204
element-wise.

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

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

Examples

  1. Copy>>> input_x = Tensor(np.array([[-1.0, 4.0, -8.0], [2.0, -5.0, 9.0]], np.float32))
  2. >>> relu = ReLU()
  3. >>> result = relu(input_x)
  4. [[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

mindspore.ops.operations - 图205
element-wise.

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

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

Examples

  1. Copy>>> input_x = Tensor(np.array([[-1.0, 4.0, -8.0], [2.0, -5.0, 9.0]], np.float32))
  2. >>> relu6 = ReLU6()
  3. >>> result = relu6(input_x)
  4. >>> 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’ ora number.

  • Outputs:

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

Examples

  1. Copy>>> input_x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
  2. >>> input_y = Tensor(np.array([4.0, 5.0, 6.0]), mindspore.float32)
  3. >>> realdiv = RealDiv()
  4. >>> realdiv(input_x, input_y)
  5. [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

  1. Copy>>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  2. >>> reciprocal = Reciprocal()
  3. >>> reciprocal(input_x)
  4. [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

mindspore.ops.operations - 图206
.

  1. -

If axis is tuple(int), set as (2, 3), and keep_dims is false,the shape of output is

mindspore.ops.operations - 图207
.

Examples

  1. Copy>>> data = Tensor(np.array([[True, False], [True, True]]))
  2. >>> op = ReduceAll(keep_dims=True)
  3. >>> 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

mindspore.ops.operations - 图208
.

  1. -

If axis is tuple(int), set as (2, 3), and keep_dims is false,the shape of output is

mindspore.ops.operations - 图209
.

Examples

  1. Copy>>> data = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  2. >>> op = ReduceMax(keep_dims=True)
  3. >>> 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

mindspore.ops.operations - 图210
.

  1. -

If axis is tuple(int), set as (2, 3), and keep_dims is false,the shape of output is

mindspore.ops.operations - 图211
.

Examples

  1. Copy>>> data = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  2. >>> op = ReduceMean(keep_dims=True)
  3. >>> 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

mindspore.ops.operations - 图212
.

  1. -

If axis is tuple(int), set as (2, 3), and keep_dims is false,the shape of output is

mindspore.ops.operations - 图213
.

Examples

  1. Copy>>> data = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  2. >>> op = ReduceMin(keep_dims=True)
  3. >>> 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

mindspore.ops.operations - 图214
.

  1. -

If axis is tuple(int), set as (2, 3), and keep_dims is false,the shape of output is

mindspore.ops.operations - 图215
.

Examples

  1. Copy>>> data = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  2. >>> op = ReduceProd(keep_dims=True)
  3. >>> 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

  1. Copy>>> from mindspore.communication.management import init
  2. >>> import mindspore.ops.operations as P
  3. >>> init('nccl')
  4. >>> class Net(nn.Cell):
  5. >>> def __init__(self):
  6. >>> super(Net, self).__init__()
  7. >>> self.reducescatter = P.ReduceScatter(ReduceOp.SUM, group="nccl_world_group")
  8. >>>
  9. >>> def construct(self, x):
  10. >>> return self.reducescatter(x)
  11. >>>
  12. >>> input_ = Tensor(np.ones([2, 8]).astype(np.float32))
  13. >>> net = Net()
  14. >>> 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

mindspore.ops.operations - 图216
.

  1. -

If axis is tuple(int), set as (2, 3), and keep_dims is false,the shape of output is

mindspore.ops.operations - 图217
.

Examples

  1. Copy>>> data = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  2. >>> op = ReduceSum(keep_dims=True)
  3. >>> 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

mindspore.ops.operations - 图218
.

  1. -

input_shape (tuple[int]) - The input tuple is constructed by multipleintegers, i.e.,

mindspore.ops.operations - 图219
. Only constant value is allowed.

  • Outputs:
  • Tensor, the shape of tensor is

mindspore.ops.operations - 图220
.

Examples

  1. Copy>>> input_tensor = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
  2. >>> reshape = Reshape()
  3. >>> 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 imagescan 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

  1. Copy>>> tensor = Tensor([[[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]]], mindspore.int32)
  2. >>> resize_bilinear = P.ResizeBilinear((5, 5))
  3. >>> result = resize_bilinear(tensor)
  4. >>> 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 nearestneighbor algorithm selects the value of the nearest point and does not consider thevalues 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 inputand output tensors are aligned. Default: False.

  • Inputs:

    • input_x (Tensor) - The input tensor. The shape of the tensor is

mindspore.ops.operations - 图221
.

  • Outputs:
  • Tensor, the shape of the output tensor is

mindspore.ops.operations - 图222
.

Examples

  1. Copy>>> input_tensor = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
  2. >>> resize = ResizeNearestNeighbor((2, 2))
  3. >>> 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

  1. Copy>>> input_x = Tensor(np.array([0.8, 1.5, 2.3, 2.5, -4.5]), mindspore.float32)
  2. >>> round = Round()
  3. >>> round(input_x)
  4. [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

  1. Copy>>> input_tensor = Tensor([[4, 4], [9, 9]], mindspore.float32)
  2. >>> rsqrt = Rsqrt()
  3. >>> rsqrt(input_tensor)
  4. [[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 ofinitialization 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.

    • gradient (Tensor) - Gradients.

    • 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

mindspore.ops.operations - 图223
.

  1. -

input_y (Tensor) - The shape of tensor is

mindspore.ops.operations - 图224
.

  • Outputs:
  • Tensor, the shape of tensor is

mindspore.ops.operations - 图225
,if data type and shape of input_x and input_y are the same.

Examples

  1. Copy>>> input_x = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  2. >>> input_y = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  3. >>> 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

  1. Copy>>> scalar_cast = P.ScalarCast()
  2. >>> 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

  1. Copy>>> class SummaryDemo(nn.Cell):
  2. >>> def __init__(self,):
  3. >>> super(SummaryDemo, self).__init__()
  4. >>> self.summary = P.ScalarSummary()
  5. >>> self.add = P.TensorAdd()
  6. >>>
  7. >>> def construct(self, x, y):
  8. >>> name = "x"
  9. >>> self.summary(name, x)
  10. >>> x = self.add(x, y)
  11. >>> 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

  1. Copy>>> op = ScalarToArray()
  2. >>> data = 1.0
  3. >>> 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. Onlyconstant value is allowed.

    • Outputs:

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

Examples

  1. Copy>>> op = ScalarToTensor()
  2. >>> data = 1
  3. >>> 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

  1. Copy>>> op = ScatterNd()
  2. >>> update = Tensor(np.array([3.2, 1.1]), mindspore.float32)
  3. >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32)
  4. >>> shape = (3, 3)
  5. >>> 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

  1. Copy>>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
  2. >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
  3. >>> update = Tensor(np.array([1.0, 2.2]), mindspore.float32)
  4. >>> op = ScatterNdUpdate()
  5. >>> output = op(input_x, indices, update)
  • class mindspore.ops.operations.Select(*args, **kwargs)[source]
  • Return the selected elements, either from input

mindspore.ops.operations - 图226
or input
mindspore.ops.operations - 图227
, depending on the condition.

Given a tensor as input, this operation inserts a dimension of 1 at the dimension,if both

mindspore.ops.operations - 图228
and
mindspore.ops.operations - 图229
are none, the operation returns the coordinates of the trueelement in the condition, the coordinates are returned as a two-dimensionaltensor, where the first dimension (row) represents the number of true elementsand the second dimension (columns) represents the coordinates of the trueelements. Keep in mind that the shape of the output tensor can vary dependingon how much of the true value is in the input. Indexes are output in row-firstorder.

If neither is None,

mindspore.ops.operations - 图230
and
mindspore.ops.operations - 图231
must have the same shape. If
mindspore.ops.operations - 图232
and
mindspore.ops.operations - 图233
arescalars, the conditional tensor must be a scalar. If
mindspore.ops.operations - 图234
and
mindspore.ops.operations - 图235
arehigher-demensional vectors, the condition must be a vector whose size matches thefirst dimension of
mindspore.ops.operations - 图236
, or must have the same shape as
mindspore.ops.operations - 图237
.

The conditional tensor acts as an optional compensation (mask), whichdetermines whether the corresponding element / row in the output should beselected from

mindspore.ops.operations - 图238
(if true) or
mindspore.ops.operations - 图239
(if false) based on the value of eachelement.

If condition is a vector, then

mindspore.ops.operations - 图240
and
mindspore.ops.operations - 图241
are higher-demensional matrices, then itchooses to copy that row (external dimensions) from
mindspore.ops.operations - 图242
and
mindspore.ops.operations - 图243
. If condition hasthe same shape as
mindspore.ops.operations - 图244
and
mindspore.ops.operations - 图245
, you can choose to copy these elements from
mindspore.ops.operations - 图246
and
mindspore.ops.operations - 图247
.

  • Inputs:
    • input_x (Tensor[bool]) - The shape is

mindspore.ops.operations - 图248
.The condition tensor, decides whose element is chosen.

  1. -

input_y (Tensor) - The shape is

mindspore.ops.operations - 图249
.The first input tensor.

  1. -

input_z (Tensor) - The shape is

mindspore.ops.operations - 图250
.The second input tensor.

  • Outputs:
  • Tensor, has the same shape as input_y. The shape is

mindspore.ops.operations - 图251
.

Examples

  1. Copy>>> select = Select()
  2. >>> input_x = Tensor([True, False])
  3. >>> input_y = Tensor([2,3], mindspore.float32)
  4. >>> input_z = Tensor([1,2], mindspore.float32)
  5. >>> 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

mindspore.ops.operations - 图252
.

  • Outputs:
  • tuple[int], the output tuple is constructed by multiple integers,

mindspore.ops.operations - 图253
.

Examples

  1. Copy>>> input_tensor = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32)
  2. >>> shape = Shape()
  3. >>> 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:

mindspore.ops.operations - 图254

where

mindspore.ops.operations - 图255
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,

mindspore.ops.operations - 图256

mindspore.ops.operations - 图257

  • 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

mindspore.ops.operations - 图258
on tensor element-wise.

Note

mindspore.ops.operations - 图259

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

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

Examples

  1. Copy>>> input_x = Tensor(np.array([[2.0, 0.0, -1.0]]), mindspore.float32)
  2. >>> sign = Sign()
  3. >>> output = sign(input_x)
  4. [[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

mindspore.ops.operations - 图260
.

  • Outputs:
  • Tensor, has the same shape as input_x.

Examples

  1. Copy>>> sin = Sin()
  2. >>> X = Tensor(np.array([0.62, 0.28, 0.43, 0.62]), ms.float32)
  3. >>> 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

mindspore.ops.operations - 图261
.

  • Outputs:
  • int, a scalar representing the elements size of input_x, tensor is the number of elementsin a tensor,

mindspore.ops.operations - 图262
.

Examples

  1. Copy>>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  2. >>> size = Size()
  3. >>> 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

  1. Copy>>> data = Tensor(np.array([3,2,3]).astype(np.int32))
  2. >>> 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 theFast R-CNN by Ross Girshick.

Note

Sets input prediction as X, input target as Y, output as loss. Then,

mindspore.ops.operations - 图263

  • Parameters
  • sigma (float) – A parameter used to control the point where the function will change fromquadratic 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

mindspore.ops.operations - 图264
then for each element
mindspore.ops.operations - 图265
the Softmax function is shown as follows:

mindspore.ops.operations - 图266

where

mindspore.ops.operations - 图267
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,

mindspore.ops.operations - 图268

mindspore.ops.operations - 图269

  • Inputs:
    • logits (Tensor) - Input logits, with shape

mindspore.ops.operations - 图270
.

  1. -

labels (Tensor) - Ground truth labels, with shape

mindspore.ops.operations - 图271
.

  • 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

mindspore.ops.operations - 图272
.

The output tensor’s weight dimension is

mindspore.ops.operations - 图273
.

The depth of output tensor is

mindspore.ops.operations - 图274
.

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

  1. Copy>>> x = Tensor(np.random.rand(1,3,2,2), mindspore.float32)
  2. >>> block_size = 2
  3. >>> op = SpaceToDepth(block_size)
  4. >>> output = op(x)
  5. >>> output.asnumpy().shape == (1,12,1,1)
  • class mindspore.ops.operations.SparseApplyAdagrad(*args, **kwargs)[source]
  • Update relevant entries according to the adagrad scheme.

mindspore.ops.operations - 图275

mindspore.ops.operations - 图276

  • 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 shapeexcept 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,

mindspore.ops.operations - 图277

mindspore.ops.operations - 图278

mindspore.ops.operations - 图279

  • Parameters
  • is_grad (bool) – If it’s true, this operation returns the computed gradient. Default: False.

  • Inputs:

    • logits (Tensor) - Input logits, with shape

mindspore.ops.operations - 图280
.

  1. -

labels (Tensor) - Ground truth labels, with shape

mindspore.ops.operations - 图281
.

  • 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

mindspore.ops.operations - 图282
.

  • Outputs:
  • tuple[Tensor], the shape of each output tensor is same, which is

mindspore.ops.operations - 图283
.

Examples

  1. Copy>>> split = Split(1, 2)
  2. >>> x = Tensor(np.array([[1, 1, 1, 1], [2, 2, 2, 2]]))
  3. >>> 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

  1. Copy>>> input_x = Tensor(np.array([1.0, 4.0, 9.0]), mindspore.float32)
  2. >>> sqrt = Sqrt()
  3. >>> sqrt(input_x)
  4. [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

  1. Copy>>> input_x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
  2. >>> square = Square()
  3. >>> square(input_x)
  4. [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 removeall 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

mindspore.ops.operations - 图284
.

  • Outputs:
  • Tensor, the shape of tensor is

mindspore.ops.operations - 图285
.

Examples

  1. Copy>>> input_tensor = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32)
  2. >>> squeeze = Squeeze(2)
  3. >>> 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 fragmentcontinues 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.

    • ellipsis_mask (int) – An int mask. Default: 0.

    • new_axis_mask (int) – An int mask. Default: 0.

    • shrink_axis_mask (int) – An int mask. Default: 0.

  • Inputs:

    • input_x (Tensor) - The input Tensor.

    • begin (tuple[int]) - A tuple which represents the location where to start. Onlyconstant 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 addedbefore 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

    mindspore.ops.operations - 图286
    , the interval is
    mindspore.ops.operations - 图287
    .
    Thus, return the element with
    mindspore.ops.operations - 图288
    in 0th dim, i.e., [[3, 3, 3], [4, 4, 4]].


  • In the 1st dim, similarly, the interval is

    mindspore.ops.operations - 图289
    .
    Based on the return value of the 0th dim, return the element with
    mindspore.ops.operations - 图290
    ,
    i.e., [3, 3, 3].


  • In the 2nd dim, similarly, the interval is

    mindspore.ops.operations - 图291
    .
    Based on the return value of the 1st dim, return the element with
    mindspore.ops.operations - 图292
    ,
    i.e., [3, 3, 3].


  • Finally, the output is [3, 3, 3].



  • Examples
  1. Copy>>> input_x = Tensor([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]], [[5, 5, 5], [6, 6, 6]]])
  2. >>> slice = StridedSlice()
  3. >>> output = slice(input_x, (1, 0, 0), (2, 1, 3), (1, 1, 1))
  4. >>> output.shape()
  5. (1, 1, 3)
  6. >>> output
  7. [[[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’ ora number.

  • Outputs:

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

Examples

  1. Copy>>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2. >>> input_y = Tensor(np.array([4, 5, 6]), mindspore.int32)
  3. >>> sub = Sub()
  4. >>> sub(input_x, input_y)
  5. [-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:

mindspore.ops.operations - 图293

where

mindspore.ops.operations - 图294
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]
  • Adds two input 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’ ora number.

  • Outputs:

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

Examples

  1. Copy>>> add = P.TensorAdd()
  2. >>> x = Tensor(np.array([1,2,3]).astype(np.float32))
  3. >>> y = Tensor(np.array([4,5,6]).astype(np.float32))
  4. >>> add(x, y)
  5. [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

  1. Copy>>> class SummaryDemo(nn.Cell):
  2. >>> def __init__(self,):
  3. >>> super(SummaryDemo, self).__init__()
  4. >>> self.summary = P.TensorSummary()
  5. >>> self.add = P.TensorAdd()
  6. >>>
  7. >>> def construct(self, x, y):
  8. >>> x = self.add(x, y)
  9. >>> name = "x"
  10. >>> self.summary(name, x)
  11. >>> 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 ofoutput 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

mindspore.ops.operations - 图295
.

  1. -

multiples (tuple[int]) - The input tuple is constructed by multipleintegers, i.e.,

mindspore.ops.operations - 图296
. 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, andthe shape of Outputs is

mindspore.ops.operations - 图297
.

  1. -

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

mindspore.ops.operations - 图298
,then the shape of their corresponding positions can be multiplied, andthe shape of Outputs is
mindspore.ops.operations - 图299
.

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

  1. Copy>>> topk = TopK(sorted=True)
  2. >>> x = Tensor(np.array([1, 2, 3, 4, 5]).astype(np.float16))
  3. >>> values, indices = topk(x)
  4. >>> assert values == Tensor(np.array([5, 4, 3]))
  5. >>> 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

mindspore.ops.operations - 图300
.

  1. -

input_perm (tuple[int]) - The permutation to be converted. The input tuple is constructed by multipleindexes. The length of input_perm and the shape of input_x should be the same. Only constant value isallowed.

  • Outputs:
  • Tensor, the type of output tensor is same as input_x and the shape of output tensor is decided by theshape of input_x and the value of input_perm.

Examples

  1. Copy>>> input_tensor = Tensor(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]), mindspore.float32)
  2. >>> perm = (0, 2, 1)
  3. >>> expect = np.array([[[1, 4], [2, 5], [3, 6]], [[7, 10], [8, 11], [9, 12]]])
  4. >>> transpose = Transpose()
  5. >>> 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
    • seed (int) – A int number used to create random seed. Default: 0.

    • dtype (mindspore.dtype) – Data type. Default: mindspore.float32.

  • 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

  1. Copy>>> input_shape = Tensor(np.array([1, 2, 3]))
  2. >>> truncated_normal = TruncatedNormal()
  3. >>> 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

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

mindspore.ops.operations - 图301
, where
mindspore.ops.operations - 图302
is a tuple describing the index of element in data. segment_ids selects which elements in data to sumup. Segment_ids does not need to be sorted, and it does not need to cover all values in the entire valid valuerange.

If the sum of the given segment_ids

mindspore.ops.operations - 图303
is empty, then
mindspore.ops.operations - 图304
. If the given segment_idsis 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

mindspore.ops.operations - 图305
.

  1. -

segment_ids (Tensor) - Set the shape as

mindspore.ops.operations - 图306
, where 0 < N <= R. Type must be int.

  1. -

num_segments (int) - Set

mindspore.ops.operations - 图307
as num_segments.

  • Outputs:
  • Tensor, the shape is

mindspore.ops.operations - 图308
.

Examples

  1. Copy>>> input_x = [1, 2, 3, 4]
  2. >>> segment_ids = [0, 0, 1, 2]
  3. >>> num_segments = 4
  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

  1. Copy>>> zeroslike = P.ZerosLike()
  2. >>> x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))
  3. >>> output = zeroslike(x)