[英]Display this decision tree with Graphviz
我正在關注關於使用 python v3.6 使用 scikit-learn 進行機器學習的決策樹的教程。
這是代碼;
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import mglearn
import graphviz
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, stratify=cancer.target, random_state=42)
tree = DecisionTreeClassifier(random_state=0)
tree.fit(X_train, y_train)
tree = DecisionTreeClassifier(max_depth=4, random_state=0)
tree.fit(X_train, y_train)
from sklearn.tree import export_graphviz
export_graphviz(tree, out_file="tree.dot", class_names=["malignant", "benign"],feature_names=cancer.feature_names, impurity=False, filled=True)
import graphviz
with open("tree.dot") as f:
dot_graph = f.read()
graphviz.Source(dot_graph)
如何使用 Graphviz 查看 dot_graph 內部的內容? 據推測,它應該看起來像這樣;
在 jupyter notebook 中,以下繪制了決策樹:
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
model = DecisionTreeClassifier()
model.fit(X, y)
dot_data = tree.export_graphviz(model,
feature_names=feature_names,
class_names=class_names,
filled=True, rounded=True,
special_characters=True,
out_file=None,
)
graph = graphviz.Source(dot_data)
graph
如果要將其保存為 png:
graph.format = "png"
graph.render("file_name")
graphviz.Source(dot_graph)
返回一個graphviz.files.Source
對象。
g = graphviz.Source(dot_graph)
使用g.render()
創建圖像文件。 當我在沒有參數的情況下在您的代碼上運行它時,我得到了Source.gv.pdf
但您可以指定不同的文件名。 還有一個快捷方式g.view()
,它保存文件並在適當的查看器應用程序中打開它。
如果您將代碼原樣粘貼在豐富的終端中(例如帶有內聯圖形的 Spyder/IPython 或 Jupyter 筆記本),它將自動顯示圖像而不是對象的 Python 表示。
您可以使用來自 IPython.display 的顯示。 這是一個例子:
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
model = DecisionTreeClassifier()
model.fit(X, y)
from IPython.display import display
display(graphviz.Source(tree.export_graphviz(model)))
我在 Windows 10 中工作。我通過添加到“路徑”環境變量來解決這個問題。 我添加了錯誤的路徑,我添加了 Drive:\Users\User.Name\AppData\Local\Continuum\anaconda3\envs\MyVirtualEnv\lib\site-packages\graphviz 應該使用 Drive:\Users\User.Name\AppData\最后我使用了 Local\Continuum\anaconda3\envs\MyVirtualEnv\Library\bin\graphviz,然后重新啟動了 python/anaconda。 還添加了 pydotplus 路徑,位於 ....MyVirtualEnv\lib\site-packages\pydotplus。
Jupyter 將按原樣顯示圖表,但如果您想放大更多,可以嘗試保存文件並進一步檢查:
# Draw graph
graph = pydotplus.graph_from_dot_data(dot_data)
# Show graph
Image(graph.create_png())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.