original source :Ā https://medium.com/@contactsunny/label-encoder-vs-one-hot-encoder-in-machine-learning-3fc273365621
These two encoders are parts of the SciKit Learn library in Python, and they are used to convert categorical data, or text data, into numbers, which our predictive models can better understand.Ā
nd to convert this kind of categorical text data into model-understandable numerical data, we use the Label Encoder class. So all we have to do, to label encode the first column, is import the LabelEncoder class from the sklearn library, fit and transform the first column of the data, and then replace the existing text data with the new encoded data. Letās have a look at the code.
from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
x[:, 0] = labelencoder.fit_transform(x[:, 0])
Weāve assumed that the data is in a variable called āxā. After running this piece of code, if you check the value of x, youāll see that the three countries in the first column have been replaced by the numbers 0, 1, and 2.
Thatās all label encoding is about. But depending on the data, label encoding introduces a new problem. For example, we have encoded a set of country names into numerical data. This is actually categorical data and there is no relation, of any kind, between the rows.
The problem here is, since there are different numbers in the same column, the model will misunderstand the data to be in some kind of order, 0 < 1 < 2. But this isnāt the case at all. To overcome this problem, we use One Hot Encoder.
If youāre interested in checking out the documentation, you can find it here. Now, as we already discussed, depending on the data we have, we might run into situations where, after label encoding, we might confuse our model into thinking that a column has data with some kind of order or hierarchy, when we clearly donāt have it. To avoid this, we āOneHotEncodeā that column.
What one hot encoding does is, it takes a column which has categorical data, which has been label encoded, and then splits the column into multiple columns. The numbers are replaced by 1s and 0s, depending on which column has what value. In our example, weāll get three new columns, one for each countryāāāFrance, Germany, and Spain.
For rows which have the first column value as France, the āFranceā column will have a ā1ā and the other two columns will have ā0ās. Similarly, for rows which have the first column value as Germany, the āGermanyā column will have a ā1ā and the other two columns will have ā0ās.
The Python code for one hot encoding is also pretty simple:
from sklearn.preprocessing import OneHotEncoder
onehotencoder = OneHotEncoder(categorical_features = [0])
x = onehotencoder.fit_transform(x).toarray()