我是Python的新手,对于如何使用分类变量实现决策树非常困惑,因为它们在 R 中由 party 和 ctree 自动编码 .
我想制作一个具有两个分类独立特征和一个依赖类的决策树 .
我使用的数据框如下所示:
data
title_overlap_quartile sales_rank_quartile rank_grp
0 Q4 Q2 GRP 1
1 Q4 Q3 GRP 1
2 Q2 Q1 GRP 1
3 Q4 Q1 GRP 1
5 Q2 Q1 GRP 2
我知道分类特征需要使用labelencoder和/或一个热编码器在scikit中进行编码 .
首先我尝试使用标签编码器,但这并没有解决问题,因为 DecisionTreeClassifier 开始将编码变量视为连续变量 . 然后我从这篇文章中读到:Issue with OneHotEncoder for categorical features该变量应首先使用标签编码器进行编码,然后使用一个热编码器再次编码 .
我尝试以下列方式在此数据集上实现它,但是收到错误 .
def encode_features(df, columns):
le = preprocessing.LabelEncoder()
ohe = preprocessing.OneHotEncoder(sparse=False)
for i in columns:
le.fit(df[i].unique())
df[i+'_le'] = le.transform(df[i])
df[i+'_le'] = df[i+'_le'].values.reshape(-1, 1)
df[i+'_le'+'_ohe'] = ohe.fit_transform(df[i+'_le'])
return(df)
data = encode_features(data, ['title_overlap_quartile', 'sales_rank_quartile'])
File "/Users/vaga/anaconda2/envs/py36/lib/python3.5/site-packages/pandas/core/series.py", line 2800, in _sanitize_index
raise ValueError('Length of values does not match length of ' 'index')
ValueError: Length of values does not match length of index
当我从函数中删除 ohe 部分并在外部运行时,它会运行,但结果看起来很奇怪:
def encode_features(df, columns):
le = preprocessing.LabelEncoder()
ohe = preprocessing.OneHotEncoder(sparse=False)
for i in columns:
le.fit(df[i].unique())
df[i+'_le'] = le.transform(df[i])
# df[i+'_le'] = df[i+'_le'].values.reshape(-1, 1)
# df[i+'_le'+'_ohe'] = ohe.fit_transform(df[i+'_le'])
return(df)
data = encode_features(data, ['title_overlap_quartile', 'sales_rank_quartile'])
data['title_overlap_quartile_le'] = data['title_overlap_quartile_le'].values.reshape(-1, 1)
print(ohe.fit_transform(data['title_overlap_quartile_le']))
[[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.
1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]
我也尝试使用 pandas.get_dummies ,它将变量转换为多列并使用二进制编码并使用它,但是它再次被决策树分类器视为连续变量 .
有人可以帮助我如何使用分类变量作为分类来拟合决策树并输出树形图?
用于拟合和绘制我正在使用的树的代码是:
clf = tree.DecisionTreeClassifier()
clf = clf.fit(data[['title_overlap_score', 'sales_rank_quartile']], data[['rank_grp']])
dot_data = tree.export_graphviz(clf, out_file=None, feature_names=data[['title_overlap_score', 'sales_rank_quartile']].columns,
filled=True, rounded=True,
special_characters=True)
graph = graphviz.Source(dot_data)
graph.render("new_tree")