使用graphviz显示此决策树

问题描述 投票:0回答:2

我正在学习如何使用python v3.6使用scikit-learn进行机器学习的决策树。

这是代码;

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

python python-3.x scikit-learn graphviz decision-tree
2个回答
3
投票

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

g = graphviz.Source(dot_graph)

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

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


0
投票

您可以使用IPython.display中的显示。这是一个例子:

from sklearn.tree import DecisionTreeClassifier
from sklearn import tree

model = DecisionTreeClassifier()
model.fit(X, y)

from IPython.display import display
display(graphviz.Source(tree.export_graphviz(model)))
© www.soinside.com 2019 - 2024. All rights reserved.