mindspore.mint.nn.functional.one_hot

mindspore.mint.nn.functional.one_hot(tensor, num_classes=- 1)[source]

Computes a one-hot tensor.

The locations represented by tensor in tensor take value 1, while all other locations take value 0.

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

  • num_classes (int) – A scalar defining the depth of the one-hot dimension, default: -1.

Returns

Tensor, one-hot tensor.

Raises
  • TypeError – If num_classes is not an int.

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

  • ValueError – If num_classes is less than -1.

Supported Platforms:

Ascend

Examples

>>> import mindspore
>>> import numpy as np
>>> from mindspore import Tensor, mint
>>> tensor = Tensor(np.array([0, 1, 2]), mindspore.int32)
>>> num_classes = 3
>>> output = mint.nn.functional.one_hot(tensor, num_classes)
>>> print(output)
[[1 0 0]
 [0 1 0]
 [0 0 1]]