mindspore.ops.one_hot

mindspore.ops.one_hot(indices, depth, on_value, off_value, axis=- 1)[source]

Computes a one-hot tensor.

The locations represented by indices in indices take value on_value, while all other locations take value off_value.

Note

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

Parameters
  • indices (Tensor) – A tensor of indices. Tensor of shape \((X_0, \ldots, X_n)\). Data type must be uint8, int32 or int64.

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

  • on_value (Union[Tensor, int, float]) – A value to fill in output when indices[j] = i. Support uint8, uint16, uint32, uint64, int8, int16, int32, int64, float16, float32, float64, bool, complex64, complex128.

  • off_value (Union[Tensor, int, float]) – A value to fill in output when indices[j] != i. Has the same data type as on_value.

  • axis (int) – Position to insert the value. e.g. If shape of self is \((N, C)\), and axis is -1, the output shape will be \((N, C, depth)\), If axis is 0, the output shape will be \((depth, N, C)\). Default: -1 .

Returns

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

Raises
  • TypeError – If axis or depth is not an int.

  • TypeError – If dtype of indices is not uint8, int32 or int64.

  • TypeError – If indices, on_value or off_value is not a Tensor.

  • ValueError – If axis is not in range [-1, ndim].

  • ValueError – If depth is less than 0.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore
>>> import numpy as np
>>> from mindspore import Tensor, ops
>>> indices = Tensor(np.array([0, 1, 2]), mindspore.int32)
>>> depth, on_value, off_value = 3, Tensor(1.0, mindspore.float32), Tensor(0.0, mindspore.float32)
>>> output = ops.one_hot(indices, depth, on_value, off_value, axis=-1)
>>> print(output)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]