LabelEncoder in scikit-learn
ML Quickies #24
When we have categorical data in the context of machine learning, it’s common to convert string labels into numerical form. Many (almost all) algorithms expect numbers rather than strings as input, and that’s where LabelEncoder from sklearn.preprocessing comes in.
Get Prathik C’s stories in your inbox
Join Medium for free to get updates from this writer.
However, once you’ve transformed your labels, you might wonder:
What integers did my categories get mapped to?
How do I get back the original labels from these integers?
Let’s walk through how to inspect the mappings created by LabelEncoder and how to reverse them.
1. The Basics: Fitting and Transforming
from sklearn.preprocessing import LabelEncoder
# Example categorical labels
y = ["cat", "dog", "cat", "bird"]
# Create and fit the encoder
le = LabelEncoder()
y_encoded = le.fit_transform(y)
print("Encoded labels:", y_encoded)Output:
Encoded labels: [1 2 1 0]2. Seeing the Mapping: .classes_
After fitting, LabelEncoder stores the unique categories it has seen in the .classes_ attribute, sorted alphabetically.
print("Classes:", le.classes_)Output:
Classes: ['bird' 'cat' 'dog']This tells us:
0→"bird"1→"cat"2→"dog"
The numbers returned by .transform() are simply the indexes into this classes_ array.
3. Getting the Mapping as a Dictionary
If you prefer a dictionary view:
mapping = {cls: idx for idx, cls in enumerate(le.classes_)}
for k,v in mapping.items():
print(f"{k}: {v}")Output:
bird: 0
cat: 1
dog: 24. Reverse Mapping: From Numbers Back to Labels
Sometimes you need to reverse the transformation — e.g., when interpreting predictions.
That’s where .inverse_transform() comes in.
y_decoded = le.inverse_transform(y_encoded)
print("Decoded labels:", y_decoded)Output:
Decoded labels: ['cat' 'dog' 'cat' 'bird']Example
from sklearn.preprocessing import LabelEncoder
y = ["cat", "dog", "cat", "bird"]
le = LabelEncoder()
y_encoded = le.fit_transform(y)
print("Encoded:", y_encoded)
print("Classes:", le.classes_)
mapping = {cls: idx for idx, cls in enumerate(le.classes_)}
print("Mapping:", mapping)
y_decoded = le.inverse_transform(y_encoded)
print("Decoded:", y_decoded)Output:
Encoded: [1 2 1 0]
Classes: ['bird' 'cat' 'dog']
Mapping: {np.str_('bird'): 0, np.str_('cat'): 1, np.str_('dog'): 2}
Decoded: ['cat' 'dog' 'cat' 'bird']Takeaways
LabelEncoderassigns integer values to unique labels based on sorted order..classes_stores the mapping from integers to original labels..inverse_transform()lets you convert encoded integers back to their original categories.- For a dictionary mapping, use
enumerate(le.classes_).
If you use label encoding, its a good practice to always check your .classes_ before making assumptions about how categories are mapped—especially if your data changes or categories get added. This prevents subtle bugs and misinterpretations in your model outputs.
Until next time:)










