one_hot

paddle.nn.functional. one_hot ( x, num_classes, name=None ) [source]

The operator converts each id in the input x to an one-hot vector with a num_classes length. The value in the vector dimension corresponding to the id is 1, and the value in the remaining dimension is 0.

The shape of output Tensor is generated by appending num_classes dimension behind the last dimension of the x shape.

Example 1:

input:
    x.shape = [4]
    x.data = [1, 1, 3, 0]
    num_classes = 4

output:
    Out.shape = [4, 4]
    Out.data = [[0., 1., 0., 0.],
                [0., 1., 0., 0.],
                [0., 0., 0., 1.],
                [1., 0., 0., 0.]]

Example 2:

input:
    x.shape = [4]
    x.data = [1, 1, 5, 0]
    num_classes = 4

output: Throw an exception for Illegal value
    The second dimension in X is 5, which is greater than num_classes,
    so it throws an exception.
Parameters
  • x (Tensor) – Tensor with shape \([N_1, N_2, ..., N_k]\) , which contains at least one dimension. The data type is int32 or int64.

  • num_classes (int) – An integer defining the num_classes of the one hot dimension. If input x is word id, num_classes is generally the dictionary size.

  • name (str|None, optional) – For detailed information, please refer to Name. Usually name is no need to set and None by default.

Returns

The one-hot representations of x. A Tensor with type float32.

Return type

Tensor

Examples

>>> import paddle
>>> # Correspond to the first example above, where label.shape is 4 and one_hot_label.shape is [4, 4].
>>> label = paddle.to_tensor([1, 1, 3, 0], dtype='int64')
>>> print(label.shape)
[4]
>>> one_hot_label = paddle.nn.functional.one_hot(label, num_classes=4)
>>> print(one_hot_label.shape)
[4, 4]
>>> print(one_hot_label)
Tensor(shape=[4, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
       [[0., 1., 0., 0.],
        [0., 1., 0., 0.],
        [0., 0., 0., 1.],
        [1., 0., 0., 0.]])