如何实现一键编码?

时间:2019-03-22 18:56:37

标签: python pandas machine-learning scikit-learn one-hot-encoding

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

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

但这还不够好,因为该模型始终将数字视为连续数字,但是,这些因素不是连续的,而是离散的。就像1> 0一样,它并不表示male> female。

因此,我们使用一键编码将男性设置为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

然后开始使用新的数据框构建模型吗?

例如,

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?

0 个答案:

没有答案