one_hot

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

WARING: This OP requires the last dimension of Tensor shape must be equal to 1. This OP will be deprecated in a future release. It is recommended to use fluid. one_hot .

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 adding depth dimension behind the last dimension of the input shape.

Example 1 (allow_out_of_range=False):

input:
    X.shape = [4, 1]
    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, 1]
    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, 1]
    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, 1]\) , which contains at least one dimension and the last dimension must be 1. The data type is int32 or int64.

  • depth (scalar) – 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, 1] and one_hot_label.shape is [4, 4].
label = fluid.data(name="label", shape=[4, 1], dtype="int64")
one_hot_label = fluid.layers.one_hot(input=label, depth=4)