mindspore.ops.one_hot

View Source On Gitee
mindspore.ops.one_hot(indices, depth, on_value=1, off_value=0, 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 has rank N, the output will have rank N+1. The new axis is created at dimension axis. On Ascend, if on_value is int64 dtype, indices must be int64 dtype, and the value for on_value and off_value can only be 1 and 0.

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

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

  • on_value (Union[Tensor, int, float], optional) – A value to fill in output when indices[j] = i. Data type must be int32, int64, float16 or float32. Default: 1 .

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

  • axis (int, optional) – 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)\), and it has the same data type as on_value.

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

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

  • TypeError – If dtype of on_value is not int32, int64, float16 or float32.

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