使用Graphviz显示此诊断树 [英] Display this decision tree with Graphviz

查看:49
本文介绍了使用Graphviz显示此诊断树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习一个教程,该教程介绍了如何使用pythonv3.6来使用SCRICKIT-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中的内容?大概应该是这样的;

推荐答案

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

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

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

这篇关于使用Graphviz显示此诊断树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆