one_hot

paddle.fluid.one_hot(input, depth, allow_out_of_range=False)[source]

The operator converts each id in the input to an one-hot vector with a depth 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 or LoDTensor is generated by appending depth dimension behind the last dimension of the input shape.

Example 1 (allow_out_of_range=False):

input:
    X.shape = [4]
    X.data = [1, 1, 3, 0]
    depth = 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 (allow_out_of_range=True):

input:
    X.shape = [4]
    X.data = [1, 1, 5, 0]
    depth = 4
    allow_out_of_range = True

output:
    Out.shape = [4, 4]
    Out.data = [[0., 1., 0., 0.],
                [0., 1., 0., 0.],
                [0., 0., 0., 0.], # This id is 5, which goes beyond depth, so set it all-zeros data.
                [1., 0., 0., 0.]]

Example 3 (allow_out_of_range=False):

input:
    X.shape = [4]
    X.data = [1, 1, 5, 0]
    depth = 4
    allow_out_of_range = False

output: Throw an exception for Illegal value
    The second dimension in X is 5, which is greater than depth.
    Allow_out_of_range =False means that does not allow the word id to exceed depth,
    so it throws an exception.
Parameters
  • input (Variable) – Tensor or LoDTensor with shape \([N_1, N_2, ..., N_k]\) , which contains at least one dimension. The data type is int32 or int64.

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

  • allow_out_of_range (bool) – A bool value indicating whether the input indices could be out of range \([0, depth)\) . When input indices are out of range, exceptions Illegal value is raised if allow_out_of_range is False, or zero-filling representations is created if it is set True. Default: False.

Returns

The one-hot representations of input. A Tensor or LoDTensor with type float32.

Return type

Variable

Examples

import paddle.fluid as fluid
# Correspond to the first example above, where label.shape is 4 and one_hot_label.shape is [4, 4].
label = fluid.data(name="label", shape=[4], dtype="int64")
one_hot_label = fluid.one_hot(input=label, depth=4)