Create one-hot training labels
Preparing targets for a multiclass neural-network output.
TensorFlow · Function
Converts integer class labels into a binary class matrix. The class count can be supplied explicitly or inferred from the largest label.
The function takes integer class labels and creates a NumPy matrix whose rows encode the corresponding classes. The number of columns comes from num_classes, or, when omitted, from one more than the largest label; the class dimension is placed last.
tf.keras.utils.to_categorical(x, num_classes=None)| Name | Type | Description |
|---|---|---|
x | Array-like | Array-like integer class values to convert; values range from 0 through num_classes - 1. |
num_classes | int or None | Total number of classes. If None, inferred as max(x) + 1. Defaults to None. |
A binary matrix representation of the input as a NumPy array, with the class axis last.
import numpy as np
import tensorflow as tf
labels = np.array([0, 1, 2, 1])
one_hot = tf.keras.utils.to_categorical(labels, num_classes=3)
print(one_hot)
Converts integer class labels into rows of a three-column one-hot matrix.
Preparing targets for a multiclass neural-network output.
Matching target representation to a multiclass probability loss.
Representing class indices as fixed-width vectors for downstream NumPy processing.
It converts an integer class vector into a binary, or one-hot, class matrix. Each input label becomes a row with one active class position.
Follow-up: What determines the output width? If num_classes is supplied, it determines the width; otherwise TensorFlow infers it as max(x) + 1.
num_classes specifies the total number of classes and defaults to None. When it is None, the function infers the value from the maximum input label plus one.
Follow-up: Why can inference be unsafe for a dataset split? A split that omits the highest class produces a narrower matrix than the full label space, so pass the global class count explicitly.
The result is a NumPy array containing the binary matrix representation of the input. Its class axis is the final axis, making it suitable for losses such as categorical crossentropy.
Follow-up: When should labels remain integer-valued instead? Use an integer-label loss when the model and loss expect sparse targets, avoiding one-hot expansion.
tf.keras.utilskeras.ops.categorical_crossentropy