Label Encoding is one of the most used techniques in machine learning. It is used to convert the categorial data in numerical form. So, data can be fitted into the model.
Let us understand why we use the Label Encoding. Imagine having the data, containing the essential columns in the form of string. But, you cannot fit this data in the model, because modelling only works on numerical data, what do we do? Here comes the life-saving technique which is evaluated at the preprocessing step when we ready the data for fitting, which is Label Encoding.
We will use the iris dataset from Scikit-Learn library, to understand the workings of Label Encoder. Make sure you have the following libraries installed.
pandas scikit-learn
For installing as libraries, run the following command:
$ python install -U pandas scikit-learn
Now open Google Colab Notebook, and dive into coding and learning Label Encoder.
import pandas as pd from sklearn import preprocessing
from sklearn.datasets import load_iris iris = load_iris()
species = iris.target_names print(species)
Output:
array(['setosa', 'versicolor', 'virginica'], dtype='<U10')
label_encoder = preprocessing.LabelEncoder()
label_encoder.fit(species)
You will output similar to this:
If you get this output, you have successfully fitted the data. But, the question is how you will find out what values are assigned to each species and in which order.
The order in which Label Encoder fits the data is stored in classes_ attribute. Encoding starts from 0 to data_length-1.
label_encoder.classes_
Output:
array(['setosa', 'versicolor', 'virginica'], dtype='<U10')
The label encoder will automatically sort the data, and start the encoding from the left side. Here:
setosa -> 0 versicolor -> 1 virginica -> 2
label_encoder.transform(['setosa'])
Output: array([0])
Again, if you transform the specie virginica.
label_encoder.transform(['virginica'])
Output: array([2])
You can also input the list of species, such as ["setosa", "virginica"]
Scikit Learn documentation for label encoder >>>
The above is the detailed content of Label Encoding in ML. For more information, please follow other related articles on the PHP Chinese website!