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.
Let's Code
- Start with importing the following libraries:
import pandas as pd
from sklearn import preprocessing
- Import the iris dataset, and initialize it for usage:
from sklearn.datasets import load_iris
iris = load_iris()
- Now, we need to select the data that we want Encode, we will be encoding the species names for the irises.
species = iris.target_names
print(species)
Output:
array(['setosa', 'versicolor', 'virginica'], dtype='<U10')
- Let's instantiate the class LabelEncoder from preprocessing:
label_encoder = preprocessing.LabelEncoder()
- Now, we are ready to fit the data using the label encoder:
label_encoder.fit(species)
You will output similar to this:
SOCIAL SHARE CARD GENERATOR