天天看點

sklearn 決策樹可視化生成決策樹可視化Tips of 安裝graphviz

來自google developer 的Machine Learning Recipes with Josh Gordon

Youtube連結

https://www.youtube.com/watch?v=cKxRvEZd3Mw&list=PLOU2XLYxmsIIuiBfYad6rFYQU_jL2ryal&index=1

生成決策樹

這裡使用了lris_flower_data_set

生成了一個認花的小樹

import numpy as np
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
test_idx=[,,]

#train data
train_target =np.delete(iris.target,test_idx)
train_data = np.delete(iris.data,test_idx,axis = )

#testing fata
test_target = iris.target[test_idx]
test_data = iris.data[test_idx]
clf = tree.DecisionTreeClassifier()
clf.fit(train_data,train_target)
print(clf.predict(test_data))
           

這裡總共有3類鸢尾花,每類50條資料,每組的第一個資料作為測試資料,剩餘所有的資料作為訓練資料

輸出:

[  ]
           

可視化

使用pydot

可以pip安裝

from sklearn.externals.six import StringIO
import pydot

dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data,
                        feature_names=iris.feature_names,
                        class_names=iris.target_names,
                        filled=True, rounded=True,
                        special_characters=True)
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph[].write_pdf("iris.pdf")
           

iris.pdf:

sklearn 決策樹可視化生成決策樹可視化Tips of 安裝graphviz

Tips of 安裝graphviz

首先需要pip安裝graphviz包

pip install graghviz
           

但是僅僅安裝python包會産生

解決方案:安裝了anaconda可以

conda install graphviz
           

然後将anaconda\Library\bin\graphviz加入Path可以使用

繼續閱讀