Issue
I have predicted some data using model and getting this kind of results
[[0 0 0 ... 0 0 1]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
...
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 1]
[0 0 0 ... 0 0 0]]
which are basically one-hot encoded labels of target column. Now I want to go somehow back to a single column of original values. I used these lines to do my encoding. How can I go back to sinle column?
le_candidate = LabelEncoder()
df['candidate_encoded'] = le_candidate.fit_transform(df.Candidate)
candidate_ohe = OneHotEncoder()
Y = candidate_ohe.fit_transform(df.candidate_encoded.values.reshape(-1, 1)).toarray()
Solution
Use inverse_transform
of LabelEncoder
and OneHotEncoder
:
import pandas as pd
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
s = pd.Series(['a', 'b', 'c'])
le = LabelEncoder()
ohe = OneHotEncoder(sparse=False)
s1 = le.fit_transform(s)
s2 = ohe.fit_transform(s.to_numpy().reshape(-1, 1))
What you have:
# s1 from LabelEncoder
array([0, 1, 2])
# s2 from OneHotEncoder
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
What you should do:
inv_s1 = le.inverse_transform(s1)
inv_s2 = ohe.inverse_transform(s2).ravel()
Output:
# inv_s1 == inv_s2 == s
array(['a', 'b', 'c'], dtype=object)
Answered By - Chris
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.