2017-03-06 76 views
0

我正在学习如何使用scikit-learn使用python v3.6做机器学习的决策树。用graphwiz显示这个决策树

这是代码;

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
import mglearn 
import graphviz 

from sklearn.datasets import load_breast_cancer 
from sklearn.model_selection import train_test_split 

from sklearn.tree import DecisionTreeClassifier 

cancer = load_breast_cancer() 
X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, stratify=cancer.target, random_state=42) 
tree = DecisionTreeClassifier(random_state=0) 
tree.fit(X_train, y_train) 

tree = DecisionTreeClassifier(max_depth=4, random_state=0) 
tree.fit(X_train, y_train) 

from sklearn.tree import export_graphviz 
export_graphviz(tree, out_file="tree.dot", class_names=["malignant", "benign"],feature_names=cancer.feature_names, impurity=False, filled=True) 

import graphviz 
with open("tree.dot") as f: 
    dot_graph = f.read() 
graphviz.Source(dot_graph) 

如何使用graphviz查看dot_graph内部是什么?据推测,它应该看起来像这样;

enter image description here

+1

检查[export_graphviz](http://scikit-learn.org/stable/modules/generated/sklearn.tree.export_graphviz.html)函数,您可以使用该函数将.dot转换为其他格式,例如.png –

回答

2

graphviz.Source(dot_graph)返回graphviz.files.Source对象。

g = graphviz.Source(dot_graph) 

使用g.render()来创建图像文件。当我在没有参数的情况下在代码上运行它时,我得到了一个Source.gv.pdf,但是您可以指定一个不同的文件名。还有一个快捷方式g.view(),它保存文件并在适当的查看器应用程序中打开它。

如果您将代码粘贴到丰富的终端中(例如使用内联图形或Jupyter笔记本的Spyder/IPython),它将自动显示图像而不是对象的Python表示。