label encoder
label mappings
data preprocessing
machine learning
scikit-learn

Get the label mappings from label encoder

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

LabelEncoder maps class labels to integer IDs, which is useful for target preprocessing in machine learning workflows. To interpret model outputs correctly, you need access to the mapping in both directions. This guide shows how to inspect mappings, decode predictions, and persist label metadata safely.

Fit Encoder and Read classes_

LabelEncoder stores sorted unique labels in classes_. Index positions are encoded IDs.

python
1from sklearn.preprocessing import LabelEncoder
2
3labels = ["cat", "dog", "fish", "cat", "dog"]
4
5le = LabelEncoder()
6encoded = le.fit_transform(labels)
7
8print("encoded:", encoded)
9print("classes:", le.classes_)

If classes_ is ['cat', 'dog', 'fish'], then mapping is cat to 0, dog to 1, and fish to 2.

Create Explicit Mapping Dictionaries

For reporting and APIs, explicit dictionaries are clearer.

python
1label_to_id = {label: i for i, label in enumerate(le.classes_)}
2id_to_label = {i: label for i, label in enumerate(le.classes_)}
3
4print(label_to_id)
5print(id_to_label)

These mappings make downstream code independent of encoder internals.

Decode Model Predictions

Always decode IDs back to labels before presenting output to users.

python
pred_ids = [2, 0, 1, 1]
pred_labels = le.inverse_transform(pred_ids)
print(pred_labels)

inverse_transform is the safest decode method because it uses the exact fitted class ordering.

Persist Encoder with Model Artifacts

Never refit a new encoder in inference unless you control class order identically. Persist encoder alongside model.

python
1import joblib
2
3joblib.dump(le, "label_encoder.joblib")
4
5loaded = joblib.load("label_encoder.joblib")
6print(loaded.classes_)

Version the encoder artifact with model version so deployment remains reproducible.

Export Mapping as DataFrame

Analysts and dashboards may need a tabular mapping artifact.

python
1import pandas as pd
2
3mapping_df = pd.DataFrame({
4    "label": le.classes_,
5    "encoded": range(len(le.classes_)),
6})
7
8print(mapping_df)
9mapping_df.to_csv("label_mapping.csv", index=False)

This helps non-Python consumers interpret prediction IDs.

LabelEncoder Scope and Alternatives

LabelEncoder is mainly for target labels in supervised tasks. For feature columns:

  • Use OrdinalEncoder for ordinal integer encoding.
  • Use OneHotEncoder for categorical feature expansion.

Using LabelEncoder directly on feature columns with unseen categories at inference often causes brittle behavior.

Handling Unknown Labels

For target labels, unknown values usually indicate data contract issues. Validate before transform.

python
1def validate_labels(values, known):
2    unknown = sorted(set(values) - set(known))
3    if unknown:
4        raise ValueError(f"Unknown labels found: {unknown}")
5
6validate_labels(["cat", "dog"], le.classes_)

Failing fast is better than silent remapping.

Mapping Consistency Across Data Splits

A good practice is to fit LabelEncoder only on training targets, then transform validation and test targets with the same fitted encoder. This mirrors real deployment behavior and prevents accidental class-order differences.

python
# y_train_enc = le.fit_transform(y_train)
# y_valid_enc = le.transform(y_valid)

During evaluation, decode predictions before presenting confusion matrices or classification reports to non-technical audiences. Human-readable labels reduce interpretation errors and make model diagnostics easier to review with domain experts.

python
# pred_labels = le.inverse_transform(pred_ids)

Common Pitfalls

A common pitfall is fitting one encoder in training and a different encoder in inference, which changes numeric IDs and corrupts interpretation.

Another issue is assuming class order equals business order. LabelEncoder sorts labels, which may differ from domain-defined ranking.

Developers also forget to decode IDs when producing user-facing outputs and reports. Raw IDs are often meaningless to stakeholders.

Finally, encoding feature columns with LabelEncoder can hide categorical semantics and break with unseen values.

Operational Checklist

Before shipping a model, verify three items: encoder artifact version matches model version, class list is documented, and inference service decodes predictions before returning responses. A short checklist prevents subtle but costly label interpretation bugs in production dashboards and APIs.

Summary

  • classes_ defines authoritative label-to-id mapping.
  • Build forward and reverse mapping dictionaries for clarity.
  • Decode predictions with inverse_transform.
  • Persist encoder artifact with the model for reproducibility.
  • Use encoder types that match target versus feature use cases.

Related reading
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
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

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

All Rights Reserved.