繁体   English   中英

在 jupyter notebook 中显示 scikit 决策树图

[英]displaying scikit decision tree figure in jupyter notebook

我目前正在创建一个机器学习 jupyter 笔记本作为一个小项目,并希望显示我的决策树。 但是,我能找到的所有选项都是导出图形然后加载图片,这是相当复杂的。

所以想问问有没有办法不导出加载图形直接显示我的决策树。

您可以使用IPython.display直接显示树:

import graphviz
from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier,export_graphviz
from sklearn.datasets import make_regression

# Generate a simple dataset
X, y = make_regression(n_features=2, n_informative=2, random_state=0)
clf = DecisionTreeRegressor(random_state=0, max_depth=2)
clf.fit(X, y)
# Visualize the tree
from IPython.display import display
display(graphviz.Source(export_graphviz(clf)))

从 scikit-learn 21.0 版(大约 2019 年 5 月)开始,现在可以使用 scikit-learn 的tree.plot_tree使用 matplotlib 绘制决策树,而无需依赖于 graphviz。

import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree

X, y = load_iris(return_X_y=True)

# Make an instance of the Model
clf = DecisionTreeClassifier(max_depth = 5)

# Train the model on the data
clf.fit(X, y)

fn=['sepal length (cm)','sepal width (cm)','petal length (cm)','petal width (cm)']
cn=['setosa', 'versicolor', 'virginica']

# Setting dpi = 300 to make image clearer than default
fig, axes = plt.subplots(nrows = 1,ncols = 1,figsize = (4,4), dpi=300)

tree.plot_tree(clf,
           feature_names = fn, 
           class_names=cn,
           filled = True);

# You can save your plot if you want
#fig.savefig('imagename.png')

类似于下面的内容将在您的 jupyter notebook 中输出。
在此处输入图片说明

代码改编自这篇文章

有一个名为graphviz的简单库,您可以使用它来查看决策树。 在此您不必导出图形,它会直接为您打开树的图形,您可以稍后决定是否要保存它。 您可以按以下方式使用它 -

import graphviz
from sklearn.tree import DecisionTreeClassifier()
from sklearn import tree

clf = DecisionTreeClassifier()
clf.fit(trainX,trainY)
columns=list(trainX.columns)
dot_data = tree.export_graphviz(clf,out_file=None,feature_names=columns,class_names=True)
graph = graphviz.Source(dot_data)
graph.render("image",view=True)
f = open("classifiers/classifier.txt","w+")
f.write(dot_data)
f.close()

因为 view = True 您的图形将在渲染后立即打开,但如果您不想要那样并且只想保存图形,则可以使用 view = False

希望这可以帮助

我知道有 4 种绘制 scikit-learn 决策树的方法:

  • 使用sklearn.tree.export_text方法打印树的文本表示
  • sklearn.tree.plot_tree方法绘图(需要matplotlib
  • 使用sklearn.tree.export_graphviz方法绘图(需要graphviz
  • 使用dtreeviz包绘图(需要dtreevizgraphviz

您可以在此博客文章中找到 sklearn 决策树的不同可视化与代码片段的比较:链接

使用 Jupiter notebook 时,记得用 plot 显示变量。 dtreeviz示例:

from dtreeviz.trees import dtreeviz # remember to load the package

viz = dtreeviz(clf, X, y,
                target_name="target",
                feature_names=iris.feature_names,
                class_names=list(iris.target_names))

viz # display the tree

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM