在jupyter笔记本中显示scikit决策树图

时间:2019-01-25 17:24:25

标签: python scikit-learn jupyter-notebook decision-tree

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

因此,我想问一问是否有一种方法可以直接显示我的决策树,而无需导出和加载图形。

4 个答案:

答案 0 :(得分:3)

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

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()

因为视图= True,您的图形将在渲染后立即打开,但是如果您不希望这样做而只想保存图形,则可以使用view = False

希望这会有所帮助

答案 1 :(得分:2)

从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笔记本中输出。
enter image description here

该代码改编自此post

答案 2 :(得分:2)

我知道有四种绘制scikit学习决策树的方法:

  • 使用FlatList方法打印树的文本表示形式
  • 使用sklearn.tree.export_text方法进行绘图(需要sklearn.tree.plot_tree
  • 使用matplotlib方法进行绘图(需要sklearn.tree.export_graphviz
  • 使用graphviz包进行绘图(需要dtreevizdtreeviz

您可以在此博客文章link中找到sklearn决策树与代码段的不同可视化效果的比较。

使用Jupiter笔记本电脑时,请记住使用图显示变量。 graphviz的示例:

dtreeviz

答案 3 :(得分:1)

您可以使用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)))