第一个问题:
是的,你的逻辑是正确的。左节点为真,右节点为假。这可能是违反直觉的; true 可以等同于较小的样本。
第二个问题:
这个问题最好通过使用 pydotplus 将树可视化为图形来解决。
tree.export_graphviz() 的 'class_names' 属性将为每个节点的多数类添加一个类声明。代码在 iPython 笔记本中执行。
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
clf2 = tree.DecisionTreeClassifier()
clf2 = clf2.fit(iris.data, iris.target)
with open("iris.dot", 'w') as f:
f = tree.export_graphviz(clf, out_file=f)
import os
os.unlink('iris.dot')
import pydotplus
dot_data = tree.export_graphviz(clf2, out_file=None)
graph2 = pydotplus.graph_from_dot_data(dot_data)
graph2.write_pdf("iris.pdf")
from IPython.display import Image
dot_data = tree.export_graphviz(clf2, out_file=None,
feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True, rounded=True, # leaves_parallel=True,
special_characters=True)
graph2 = pydotplus.graph_from_dot_data(dot_data)
## Color of nodes
nodes = graph2.get_node_list()
for node in nodes:
if node.get_label():
values = [int(ii) for ii in node.get_label().split('value = [')[1].split(']')[0].split(',')];
color = {0: [255,255,224], 1: [255,224,255], 2: [224,255,255],}
values = color[values.index(max(values))]; # print(values)
color = '#{:02x}{:02x}{:02x}'.format(values[0], values[1], values[2]); # print(color)
node.set_fillcolor(color )
#
Image(graph2.create_png() )
至于确定叶子的类,您的示例没有像 iris 数据集那样具有单个类的叶子。这很常见,可能需要过度拟合模型才能获得这样的结果。对于许多交叉验证的模型来说,类的离散分布是最好的结果。