python one-hot符号化を実現
6738 ワード
''' one-hot '''
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import LabelBinarizer
from sklearn.preprocessing import MultiLabelBinarizer
testdata = pd.DataFrame({'pet': ['chinese', 'english', 'english', 'math'],
'age': [6 , 5, 2, 2],
'salary':[7, 5, 2, 5]})
''' OneHotEncoder '''
result:
>>> testdata
age pet salary
0 6 chinese 7
1 5 english 5
2 2 english 2
3 2 math 5
OneHotEncoder(sparse = False).fit_transform(testdata[['age']])
result;
>>> OneHotEncoder(sparse = False).fit_transform(testdata[['age']])
array([[ 0., 0., 1.],
[ 0., 1., 0.],
[ 1., 0., 0.],
[ 1., 0., 0.]])
''' one-hot '''
>>> OneHotEncoder(sparse = False).fit_transform( testdata[['age', 'salary']])
array([[ 0., 0., 1., 0., 0., 1.],
[ 0., 1., 0., 0., 1., 0.],
[ 1., 0., 0., 1., 0., 0.],
[ 1., 0., 0., 0., 1., 0.]])
''' one-hot '''
>>> LabelEncoder().fit_transform(testdata['pet'])
array([0, 1, 1, 2], dtype=int64)
>>> testdata
age pet salary
0 6 chinese 7
1 5 english 5
2 2 english 2
3 2 math 5
>>> LabelEncoder().fit_transform(testdata['pet'])
array([0, 1, 1, 2], dtype=int64)
>>> a = LabelEncoder().fit_transform(testdata['pet'])
>>> OneHotEncoder( sparse=False ).fit_transform(a.reshape(-1,1))
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
########### ############
>>> LabelBinarizer().fit_transform(testdata['pet'])
array([[1, 0, 0],
[0, 1, 0],
[0, 1, 0],
[0, 0, 1]])