【发布时间】:2019-06-19 13:42:19
【问题描述】:
我目前正在创建一个机器学习 jupyter notebook 作为一个小项目,并希望显示我的决策树。但是,我能找到的所有选项都是导出图形然后加载图片,这相当复杂。
因此,我想问是否有一种方法可以直接显示我的决策树,而无需导出和加载图形。
【问题讨论】:
标签: python scikit-learn jupyter-notebook decision-tree
我目前正在创建一个机器学习 jupyter notebook 作为一个小项目,并希望显示我的决策树。但是,我能找到的所有选项都是导出图形然后加载图片,这相当复杂。
因此,我想问是否有一种方法可以直接显示我的决策树,而无需导出和加载图形。
【问题讨论】:
标签: python scikit-learn jupyter-notebook decision-tree
你可以直接使用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 月)开始,现在可以使用 matplotlib 使用 scikit-learn 的 tree.plot_tree 绘制决策树,而无需依赖 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 笔记本中输出。
代码改编自post。
【讨论】:
有一个名为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 包进行绘图(需要dtreeviz 和graphviz)您可以在这篇博文中找到 sklearn 决策树的不同可视化与代码 sn-ps 的比较:link。
使用 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
【讨论】: