Ala*_* M. 6 python visualization decision-tree scikit-learn
我正在使用scikit-learn 中的DecisionTreeClassifier对一些多类数据进行分类。我发现很多帖子描述了如何显示决策树路径,例如这里,这里和这里。然而,它们都描述了如何显示训练数据的树。这是有道理的,因为export_graphviz只需要一个合适的模型。
我的问题是如何可视化测试样本上的树(最好通过export_graphviz)。即,在拟合模型clf.fit(X[train], y[train]),然后预测测试数据的结果之后clf.predict(X[test]),我想可视化用于预测样本的决策路径X[test]。有没有办法做到这一点?
编辑:
我看到可以使用Decision_path打印路径。如果有一种方法可以获取DOT输出来export_graphviz显示它,那就太好了。
Max*_*ers 10
为了获取决策树中特定样本所采用的路径,您可以使用decision_path. 它返回一个稀疏矩阵,其中包含所提供样本的决策路径。
然后,这些决策路径可用于对通过 生成的树进行着色/标记pydot。这需要覆盖颜色和标签(这会导致一些丑陋的代码)。
笔记
decision_path可以从训练集中获取样本或新值例子
在下面的示例中,访问过的节点为绿色,所有其他节点为白色。
import pydotplus
from sklearn.datasets import load_iris
from sklearn import tree
clf = tree.DecisionTreeClassifier(random_state=42)
iris = load_iris()
clf = clf.fit(iris.data, iris.target)
dot_data = tree.export_graphviz(clf, out_file=None,
feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True, rounded=True,
special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data)
# empty all nodes, i.e.set color to white and number of samples to zero
for node in graph.get_node_list():
if node.get_attributes().get('label') is None:
continue
if 'samples = ' in node.get_attributes()['label']:
labels = node.get_attributes()['label'].split('<br/>')
for i, label in enumerate(labels):
if label.startswith('samples = '):
labels[i] = 'samples = 0'
node.set('label', '<br/>'.join(labels))
node.set_fillcolor('white')
samples = iris.data[129:130]
decision_paths = clf.decision_path(samples)
for decision_path in decision_paths:
for n, node_value in enumerate(decision_path.toarray()[0]):
if node_value == 0:
continue
node = graph.get_node(str(n))[0]
node.set_fillcolor('green')
labels = node.get_attributes()['label'].split('<br/>')
for i, label in enumerate(labels):
if label.startswith('samples = '):
labels[i] = 'samples = {}'.format(int(label.split('=')[1]) + 1)
node.set('label', '<br/>'.join(labels))
filename = 'tree.png'
graph.write_png(filename)
Run Code Online (Sandbox Code Playgroud)