在 jupyter notebook 中显示 scikit 决策树图

Jür*_*rdt 12 python decision-tree scikit-learn jupyter-notebook

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

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

hel*_*err 8

您可以使用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)))
Run Code Online (Sandbox Code Playgroud)


Mic*_*nyk 6

从 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')
Run Code Online (Sandbox Code Playgroud)

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

代码改编自这篇文章


Lak*_*tai 4

有一个名为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()
Run Code Online (Sandbox Code Playgroud)

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

希望这可以帮助