首页 > 解决方案 > 如何实现 One-Hot 编码?

问题描述

我在做一些机器学习练习,一些数据有定性变量,比如性别:男性,女性。

在建立模型时,我们知道定性变量应该设置为数字,比如男性为 1,女性为 0。

但这还不够好,因为模型总是将数字视为连续数字,但是,因子不是连续的,它们是离散的。像1>0,不代表男>女。

因此,我们使用 One-Hot Encoding 将男性设置为 01,女性设置为 10。

比如scikit-learn官网的代码:

>>> from sklearn.preprocessing import OneHotEncoder
>>> enc = OneHotEncoder(handle_unknown='ignore')
>>> X = [['Male', 1], ['Female', 3], ['Female', 2]]
>>> enc.fit(X)
... 
OneHotEncoder(categorical_features=None, categories=None,
       dtype=<... 'numpy.float64'>, handle_unknown='ignore',
       n_values=None, sparse=True)

>>> enc.categories_
[array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)]
>>> enc.transform([['Female', 1], ['Male', 4]]).toarray()
array([[1., 0., 1., 0., 0.],
       [0., 1., 0., 0., 0.]])
>>> enc.inverse_transform([[0, 1, 1, 0, 0], [0, 0, 0, 1, 0]])
array([['Male', 1],
       [None, 2]], dtype=object)
>>> enc.get_feature_names()
array(['x0_Female', 'x0_Male', 'x1_1', 'x1_2', 'x1_3'], dtype=object)

根据这段代码,假设原来的 Pandas Dataframe(tran_data2) 可能是这样的:

      Sex  ProductID  Age  Result
0    male          1   25       1
1  female          2   21       0
2  female          3   23       1

我们现在知道:

Sex

male:01

female:10

ProductID

1:100

2:010

3:001

例如 ['Female', 1]=[1., 0., 1., 0., 0.]。但是如何使用这些编码的代码呢?这是否意味着我应该将原始数据帧转换为(tran_data1)之类的格式:

   x0_Female  x0_Male  x1_1  x1_2  x1_3  Age  Result
0          0        1     1     0     0   25       1
1          1        0     0     1     0   21       0
2          1        0     0     0     1   23       1

然后开始使用新的 Dataframe 构建模型?

例如,

from sklearn import tree
features1=['x0_Female', 'x0_Male', 'x1_1', 'x1_2', 'x1_3', 'Age']
features2=['Sex', 'ProductID', 'Age']
y_pred=list()
clf=tree.DecisionTreeClassifier(criterion='entropy')
clf.fit(tran_data1[features1],tran_data1['Result'])
#clf.fit(tran_data2[features2],tran_data2['Result'])
y_pred=clf.predict(test_data[features1])

这是否意味着我应该使用 features1 而不是 features2?

标签: pythonpandasmachine-learningscikit-learnone-hot-encoding

解决方案


推荐阅读