Keras
machine learning
multi-class classification
label encoding
deep learning

How to get labels ids in Keras when training on multiple classes?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

In multi-class Keras training, "label IDs" usually means the integer index assigned to each class, such as cat -> 0, dog -> 1, and rabbit -> 2. The exact way to get those IDs depends on how the dataset was built. Folder-based loaders, preprocessing layers, and manual NumPy pipelines all expose class mappings differently.

Understand what Keras actually trains on

Keras models do not train on class names directly. They train on numeric targets.

In a multi-class problem, the targets are usually one of these forms:

  • sparse integer labels such as 0, 1, 2
  • one-hot encoded vectors such as [0, 1, 0]

That means the real question is usually how to map your original class names to those numeric forms consistently.

Folder-based datasets expose a class order

If you use directory-based utilities, Keras builds a class order from the folder names. For example, with image data generators or dataset loaders, the classes are typically sorted and indexed deterministically.

A common pattern is:

python
1import tensorflow as tf
2
3train_ds = tf.keras.utils.image_dataset_from_directory(
4    "data/train",
5    label_mode="int",
6    image_size=(224, 224),
7    batch_size=32,
8)
9
10print(train_ds.class_names)

If class_names is ['cat', 'dog', 'rabbit'], then the label IDs are:

  • 'cat -> 0'
  • 'dog -> 1'
  • 'rabbit -> 2'

That list is the mapping you need.

Use sparse labels or one-hot labels intentionally

If you use sparse integer targets, pair them with sparse_categorical_crossentropy. If you one-hot encode the targets, pair them with categorical_crossentropy.

Example with integer labels:

python
1model.compile(
2    optimizer="adam",
3    loss="sparse_categorical_crossentropy",
4    metrics=["accuracy"],
5)

Example with one-hot labels:

python
1model.compile(
2    optimizer="adam",
3    loss="categorical_crossentropy",
4    metrics=["accuracy"],
5)

The numeric class IDs still exist in both cases. One-hot encoding simply expands each ID into a vector representation.

Build the mapping explicitly when labels come from arrays

If your labels come from CSV files, DataFrames, or Python lists rather than folders, define the mapping yourself so it stays reproducible.

python
1class_names = ["cat", "dog", "rabbit"]
2class_to_id = {name: i for i, name in enumerate(class_names)}
3
4labels = ["dog", "cat", "rabbit", "dog"]
5label_ids = [class_to_id[label] for label in labels]
6
7print(class_to_id)
8print(label_ids)

This is often clearer than relying on incidental ordering from a set or unsorted input source.

StringLookup is a good Keras-native option

If you want the label mapping inside the TensorFlow pipeline, StringLookup is useful:

python
1import tensorflow as tf
2
3lookup = tf.keras.layers.StringLookup(vocabulary=["cat", "dog", "rabbit"], mask_token=None)
4labels = tf.constant(["dog", "cat", "rabbit"])
5label_ids = lookup(labels)
6
7print(label_ids.numpy())

This keeps preprocessing in the model or dataset graph, which can be helpful for exported pipelines and reproducibility.

Track the reverse mapping too

You usually need both directions:

  • class name to ID for training
  • ID back to class name for interpreting predictions

For a manual mapping:

python
id_to_class = {i: name for name, i in class_to_id.items()}
print(id_to_class[1])

For directory-based datasets, the reverse mapping is just the class_names list indexed by prediction argmax.

Common Pitfalls

The most common mistake is letting class ordering be implicit and then forgetting how IDs were assigned later.

Another common issue is mixing sparse integer labels with categorical_crossentropy, or one-hot labels with sparse_categorical_crossentropy. The target format and loss function must match.

People also assume the numeric ID has some semantic meaning beyond class indexing. Usually it does not. The ordering is just a mapping.

Finally, when evaluating predictions, remember to keep the reverse mapping so model outputs can be converted back into human-readable class names.

Summary

  • Keras trains on numeric labels, not class-name strings.
  • For folder-based datasets, class_names tells you the label ID mapping.
  • Use sparse or one-hot targets intentionally and pair them with the right loss.
  • For manual datasets, define the class-to-ID mapping explicitly.
  • Keep a reverse mapping so predictions can be interpreted correctly.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design