Categorical features
Convert class IDs into categorical feature vectors before feeding them to a model.
TensorFlow · Function
Returns a one-hot tensor by expanding each integer index into a vector of length depth. The selected position uses on_value and all other positions use off_value.
tf.one_hot converts each integer in indices into a vector whose length is depth. It inserts a new dimension at axis, using on_value where an index selects a position and off_value everywhere else; with the default axis, that dimension is appended.
tf.one_hot(indices, depth, on_value=None, off_value=None, axis=None, dtype=None, name=None)| Name | Type | Description |
|---|---|---|
indices | Tensor | Tensor containing integer indices to encode. |
depth | scalar | Scalar specifying the size of the one-hot dimension. |
on_value | scalar | Value placed where an index selects a position; defaults to 1. |
off_value | scalar | Value placed where an index does not select a position; defaults to 0. |
axis | int | Dimension at which to insert the one-hot axis; defaults to -1. |
dtype | data type | Output tensor data type. |
name | string | Optional operation name. |
The one-hot tensor.
import tensorflow as tf
indices = tf.constant([0, 2, 1])
encoded = tf.one_hot(indices, depth=3)
print(encoded)
Creates one length-three vector per index, placing the default on-value at the indexed position and the default off-value elsewhere.
Convert class IDs into categorical feature vectors before feeding them to a model.
Transform integerized vocabulary values into fixed-width representations for training.
Control the encoding dimension when integrating with tensors whose feature axis is not last.
tf.one_hot maps integer indices to vectors of length depth. The selected position receives on_value and every other position receives off_value; these default to 1 and 0.
Follow-up: What shape does it produce for rank-N input? It produces rank N+1, inserting the new dimension at axis, or appending it when axis is left at its default.
The depth argument defines the size of the one-hot dimension. An input scalar produces a vector of length depth, while a rank-N input gains one additional dimension.
Follow-up: What happens if an index is outside the represented range? The documentation does not specify an out-of-range behavior on this page, so code should ensure indices are valid for the chosen depth.
axis chooses where the new one-hot dimension is inserted, with -1 meaning the new inner-most dimension. on_value and off_value control the selected and unselected values, and dtype controls the output type.
Follow-up: How would you create a boolean encoding? Supply boolean on_value and off_value explicitly, because non-numeric output types require both values.
tf.keras.ops.one_hottf.keras.layers.CategoryEncodingtf.sparse.SparseTensor