mindspore.ops.Unique

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

Returns the unique elements of input tensor and also return a tensor containing the index of each value of input tensor corresponding to the output unique tensor.

The shape of Tensor y and Tensor idx is different in most cases, because Tensor y will be deduplicated, and the shape of Tensor idx is consistent with the input.

To get the same shape between idx and y, please ref to ‘UniqueWithPad’ operator

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

Outputs:

Tuple, containing Tensor objects (y, idx), `y is a tensor with the same type as x, and contains the unique elements in x, sorted in ascending order. idx is a tensor containing indices of elements in the input corresponding to the output tensor.

Raises

TypeError – If x is not a Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> x = Tensor(np.array([1, 2, 5, 2]), mindspore.int32)
>>> output = ops.Unique()(x)
>>> print(output)
(Tensor(shape=[3], dtype=Int32, value= [1, 2, 5]), Tensor(shape=[4], dtype=Int32, value= [0, 1, 2, 1]))
>>>
>>> # note that for GPU, this operator must be wrapped inside a model, and executed in graph mode.
>>> class UniqueNet(nn.Cell):
...     def __init__(self):
...         super(UniqueNet, self).__init__()
...         self.unique_op = ops.Unique()
...
...     def construct(self, x):
...         output, indices = self.unique_op(x)
...         return output, indices
...
>>> x = Tensor(np.array([1, 2, 5, 2]), mindspore.int32)
>>> net = UniqueNet()
>>> output = net(x)
>>> print(output)
(Tensor(shape=[3], dtype=Int32, value= [1, 2, 5]), Tensor(shape=[4], dtype=Int32, value= [0, 1, 2, 1]))