class mindspore.ops.OneHot(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.


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


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

  • 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 (Tensor) - A value to fill in output when indices[j] = i. With data type of float16 or float32.

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


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

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

  • TypeError – If dtype of indices is neither int32 nor int64.

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

  • ValueError – If axis is not in range [-1, len(indices_shape)].

  • ValueError – If depth is less than 0.

Supported Platforms:

Ascend GPU CPU


>>> 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)
>>> onehot = ops.OneHot()
>>> output = onehot(indices, depth, on_value, off_value)
>>> print(output)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]