決定木とかグラフ構造(dotファイル)をJupyter上で表示する
わざわざコマンドプロンプト上で「dot -T png graph.dot > graph.png」しなくても,Jupyter上で完結できるらしいと知ったので.試してみる.
参考:
データは
を参考に.取り敢えず,ツリーを作りたいだけなので,ボストンデータをロードして,kmeansして,ツリーを作る.
import numpy as np import matplotlib, matplotlib.pyplot as plt import seaborn as sns from sklearn import datasets from sklearn.cluster import MiniBatchKMeans from sklearn import tree %matplotlib inline boston = datasets.load_boston() kmeans = MiniBatchKMeans(n_clusters=7, max_iter=300) kmeans_result = kmeans.fit_predict(boston.data) clf = tree.DecisionTreeClassifier() clf.classes_ = np.max(kmeans_result) + 1 clf.fit(boston.data, kmeans_result) # graphvizのdotファイルを生成する with open("boston_tree.dot", 'w') as f: tree.export_graphviz( clf, out_file=f, feature_names=boston.feature_names, filled=True, rounded=True, special_characters=True, impurity=False, proportion=False, class_names=list(map(str, range(0, np.max(kmeans_result)+1))) )
import pydotplus from IPython.display import Image graph = pydotplus.graphviz.graph_from_dot_file('boston_tree.dot') graph.write_png('boston_tree.png') Image(graph.create_png())
InvocationException: GraphViz’s executables not found
うーん.エラー.
!dot -T png boston_tree.dot > boston_tree.png
して,
Image('boston_tree.png')
するしかないのか……(´・ω・`)
と思ったけど,
Python3でscikit-learnの決定木を日本語フォントで画像出力する方法のまとめ-自調自考の旅
Graphviz’s executables are not found (Python 3.4)-StackOverflow
を参考に,結局PATHに追加してあげたらちゃんと動いた.
import pydotplus from IPython.display import Image graph = pydotplus.graphviz.graph_from_dot_file('boston_tree.dot') graph.write_png('boston_tree.png') Image(graph.create_png())
ピンバック: 決定木を可視化する | 粉末@それは風のように (日記)
ピンバック: 平方フィートから家の価格を予測 | 粉末@それは風のように (日記)
ピンバック: RandomForestの可視化 | 粉末@それは風のように (日記)