如何在sklearn中使用OneHotEncoder的输出?

时间:2016-07-21 21:28:59

标签: python pandas scikit-learn classification one-hot-encoding

我有一个带有2个分类变量的Pandas Dataframe,以及ID变量和目标变量(用于分类)。我设法用OneHotEncoder转换分类值。这导致稀疏矩阵。

ohe = OneHotEncoder()
# First I remapped the string values in the categorical variables to integers as OneHotEncoder needs integers as input
... remapping code ...

ohe.fit(df[['col_a', 'col_b']])
ohe.transform(df[['col_a', 'col_b']])

但我不知道如何在DecisionTreeClassifier中使用这个稀疏矩阵?特别是当我想稍后在我的数据帧中添加一些其他非分类变量时。谢谢!

修改 在回复miraculixx的评论时:我还尝试了sklearn-pandas中的DataFrameMapper

mapper = DataFrameMapper([
    ('id_col', None),
    ('target_col', None),
    (['col_a'], OneHotEncoder()),
    (['col_b'], OneHotEncoder())
])

t = mapper.fit_transform(df)

但后来我收到了这个错误:

  

TypeError:类型不支持转换:(dtype(' O'),   dtype(' int64'),dtype(' float64'),dtype(' float64'))。

2 个答案:

答案 0 :(得分:13)

我发现你已经在使用Pandas了,为什么不使用它的get_dummies函数?

import pandas as pd
df = pd.DataFrame([['rick','young'],['phil','old'],['john','teenager']],columns=['name','age-group'])

结果

   name age-group
0  rick     young
1  phil       old
2  john  teenager

现在使用get_dummies进行编码

pd.get_dummies(df)

结果

name_john  name_phil  name_rick  age-group_old  age-group_teenager  \
0          0          0          1              0                   0   
1          0          1          0              1                   0   
2          1          0          0              0                   1   

   age-group_young  
0                1  
1                0  
2                0

您实际上可以在Sklearn的DecisionTreeClassifier中使用新的Pandas DataFrame。

答案 1 :(得分:1)

从scikit-learn看这个例子: http://scikit-learn.org/stable/auto_examples/ensemble/plot_feature_transformation.html#example-ensemble-plot-feature-transformation-py

问题是你没有使用稀疏矩阵xx.fit()。您正在使用原始数据。