LoginSignup
5
10

More than 5 years have passed since last update.

jupyter notebookで決定木の可視化を行う

Last updated at Posted at 2017-06-01

jupyter notebook で決定木の可視化を行う

import numpy as np
import pydotplus
from sklearn.feature_extraction.text import TfidfVectorizer
from IPython import display
from sklearn import tree
from io import StringIO
from operator import itemgetter
%matplotlib inline
%load_ext autoreload
%autoreload 2



input_text=np.array([
    '物理 数学 国語  ', # ドキュメント1
    'パン ライス  チョコ', #ドキュメント2
    'ビル アパート マンション ', #ドキュメント3
    '北海道 福岡 神奈川' #ドキュメント4
])

#ドキュメント1は1
#ドキュメント2は2
#ドキュメント3は3
#ドキュメント4は4

target_data = np.array([
    1,2,3,4
    ])

#文書をtf-idfのベクトルへ変換
vectorizer=TfidfVectorizer()

input_data=vectorizer.fit_transform(input_text)

np.set_printoptions(precision=2) # 有効表示桁数を2桁へ変更
print(input_data.toarray())

#決定木モデルを生成
model = tree.DecisionTreeClassifier(max_depth=5)
model = model.fit(input_data, target_data)

model.predict(input_data)

feature_names = list(map(itemgetter(0),
sorted(vectorizer.vocabulary_.items(), key=itemgetter(1))))

data = StringIO()
tree.export_graphviz(model, out_file=data, feature_names=feature_names)
graph = pydotplus.graph_from_dot_data(data.getvalue())

display.display(display.Image(graph.create_png()))

こんな感じで見える。
ジニ計数も見えていい感じ!

スクリーンショット 2017-06-02 14.19.14.png

5
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
10