search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to

Comprehensive Guide on sklearn's LabelEncoder

schedule Aug 11, 2023
Last updated
local_offer
Machine LearningPython
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

The LabelEncoder module in Python's sklearn is used to encode the target labels into categorical integers (e.g. 0, 1, 2, ...).

Encoding numerical target labels

Suppose our target labels are as follows:

raw_y = [6,9,2,5,6]

Our objective is to apply the following mapping:

2: 0
5: 1
6: 2
9: 3

Here, the value 2 gets mapped to 0, the value 5 gets mapped to 1, and so on.

We can make use of LabelEncoder like so:

from sklearn.preprocessing import LabelEncoder

raw_y = [6,9,2,5,6]
encoder = LabelEncoder()
y = encoder.fit_transform(raw_y) # returns a NumPy array
y
array([2, 3, 0, 1, 2])

Here, y is the encoded values.

We can access the classes, that is, the unique values in our target like so:

encoder.classes_
array([2, 5, 6, 9])

We can also get the original raw_y using the inverse_transform(~) function:

encoder.inverse_transform(y)
array([6, 9, 2, 5, 6])

Encoding categorical string target labels

The LabelEncoder also works when the target label is categorical:

from sklearn.preprocessing import LabelEncoder

raw_y = ["A","B","A","C"]
encoder = LabelEncoder()
y = encoder.fit_transform(raw_y)
y
array([0, 1, 0, 2])

We can see all our classes like so:

encoder.classes_
array(['A', 'B', 'C'], dtype='<U1')

We can retrieve the original raw_y like so:

encoder.inverse_transform(y)
array(['A', 'B', 'A', 'C'], dtype='<U1')
robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!