[英]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
包繪圖(需要dtreeviz
和graphviz
)您可以在此博客文章中找到 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.