Prepare categorical targets
Classification targets are stored as integer IDs but a loss expects categorical indicator vectors.
Keras · Module
Converts integer class labels into a binary, one-hot-style matrix. The number of classes can be supplied explicitly or inferred from the largest label.
The function maps each integer class label to a row whose class position contains 1 and all other positions contain 0. It creates as many class columns as specified by num_classes, or infers that count as the largest label plus one, and returns the class dimension last.
keras.utils.to_categorical(y, num_classes=None, dtype="float32")| Name | Type | Description |
|---|---|---|
y | array-like | Array-like integer class values to encode; values range from 0 to num_classes - 1. |
num_classes | int or None | Total number of classes; if None, inferred as max(y) + 1. |
dtype | string or dtype | Data type for the result; defaults to float32. |
A binary matrix represented as a NumPy array, with the class axis last.
import numpy as np
from keras.utils import to_categorical
labels = np.array([0, 2, 1, 2])
encoded = to_categorical(labels, num_classes=3)
print(encoded)
Converts integer labels into three-column one-hot rows.
Classification targets are stored as integer IDs but a loss expects categorical indicator vectors.
A model has a fixed number of output classes and a batch may not contain every class.
Labels need a configurable numeric representation for downstream NumPy-based processing.
It converts an integer class vector into a binary matrix suitable for categorical classification. Each row represents one input label, with a one at that label's class position and zeros elsewhere.
Follow-up: How can you preserve a known class space when a batch omits some classes? Pass the complete class count through num_classes rather than relying on inference.
num_classes sets the total number of output classes. If omitted, Keras derives it from max(y) + 1, while dtype controls the output data type and defaults to float32.
Follow-up: What problem can inference cause? A dataset subset lacking the highest class can produce fewer columns than the model expects, so specify num_classes.
The result is a NumPy array containing the binary class representation, with the class axis placed last. For a one-dimensional label vector, the output therefore has one row per label and one class column per class.
Follow-up: How does this differ from sparse categorical targets? Sparse targets remain integer IDs, whereas this function expands them into categorical indicator rows.
keras.utilscategorical_crossentropysparse_categorical_crossentropy