python - 决策树重复类名

标签 python python-3.x decision-tree sklearn-pandas

我有一个非常简单的数据/标签样本,我遇到的问题是生成的决策树 (pdf) 重复类名:

from sklearn import tree
from sklearn.externals.six import StringIO  
import pydotplus

features_names = ['weight', 'texture']
features = [[140, 1], [130, 1], [150, 0], [110, 0]]
labels = ['apple', 'apple', 'orange', 'orange']

clf = tree.DecisionTreeClassifier()
clf.fit(features, labels)

dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data, 
                         feature_names=features_names,  
                         class_names=labels,  
                         filled=True, rounded=True,  
                         special_characters=True,
                         impurity=False)

graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) 
graph.write_pdf("apples_oranges.pdf")

生成的 pdf 如下所示:

enter image description here

所以,问题很明显,这两种可能性都是苹果。我做错了什么?

来自DOCS :

list of strings, bool or None, optional (default=None)
Names of each of the target classes in ascending numerical order. Only relevant for classification and not supported for multi-output. If True, shows a symbolic representation of the class name.

“...升序数字顺序”这对我来说意义不大,如果我将 kwarg 更改为:

class_names=sorted(labels)

结果是一样的(在本例中很明显)。

最佳答案

类名就是类名。这不是每个示例的标签。

所以一个类是'apple',另一个是'orange',所以你只需要传入['apple', 'orange']即可。

关于顺序,要使其正确一致,您可以使用 LabelEncoder要将目标转换为整数 int_labels = labelEncoder.fit_transform(labels),请使用 int_labels 来拟合您的决策树,然后使用 labelEncoder.classes_ 属性传递到您的图形即。

关于python - 决策树重复类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49134216/

相关文章:

python-3.x - Python EasyGUI 模块 : how to change the font

C-Python asyncio : running discord. py 在线程中

machine-learning - 有没有一种方法可以使用带有分类变量的决策树而无需进行单热编码?

python - 思考特征重要性的不同方式

python - Beautifulsoup 显示重复项

python - 用python解码二维码

python - Azure ML 错误 : AADSTS70016: OAuth 2. 0 设备流错误。授权正在等待中。继续投票

python - 根据数据框中组内的条件替换值

python - 在 python 中将 pcolormesh 与 3 个一维数组一起使用

matlab - 决策树中的一组结果