決定木とかグラフ構造(dotファイル)をJupyter上で表示する

決定木とかグラフ構造(dotファイル)をJupyter上で表示する

わざわざコマンドプロンプト上で「dot -T png graph.dot > graph.png」しなくても,Jupyter上で完結できるらしいと知ったので.試してみる.

参考:

[1] CNNの図をPythonで描く-Qiita

データは

https://funmatu.wordpress.com/2017/04/23/%E7%84%A1%E9%A1%8C%E3%81%AE%E3%83%89%E3%82%AD%E3%83%A5%E3%83%A1%E3%83%B3%E3%83%88/

を参考に.取り敢えず,ツリーを作りたいだけなので,ボストンデータをロードして,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')

null

するしかないのか……(´・ω・`)

と思ったけど,

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())

boston_tree.pngboston_tree.png

カテゴリー: 未分類 パーマリンク

決定木とかグラフ構造(dotファイル)をJupyter上で表示する への3件のフィードバック

  1. ピンバック: 決定木を可視化する | 粉末@それは風のように (日記)

  2. ピンバック: 平方フィートから家の価格を予測 | 粉末@それは風のように (日記)

  3. ピンバック: RandomForestの可視化 | 粉末@それは風のように (日記)

コメントは受け付けていません。