나중에 내가 보려고 만든 블로그

[python] decision tree 시각화, graphviz 리눅스 설치, 에러 본문

Python

[python] decision tree 시각화, graphviz 리눅스 설치, 에러

winches 2021. 5. 13. 10:50

파이썬에서 decision tree 시각화 하는 방법이다.

어떤 기준으로 분류했는지 결과를 시각화 해준다.

dot 파일로 결과물이 저장되는데 이걸 바로 png로 변환해서 볼 수 있는 코드다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#classifier
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier(max_depth = 3) #depth제한

 
#train, test set 나누기
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    random_state=0,
                                                    test_size=0.33
                                                    shuffle=True)
 
clf.fit(X_train, y_train)
 
pred = clf.predict(X_test)
 
#accracy 확인
(pred == y_test).mean()
 
 
#DT 시각화
from sklearn.tree import export_graphviz
export_graphviz(clf, out_file='tree.dot',
                class_names=['1','2','3','4'],
                feature_names=features,
                impurity=False,
                filled = True#박스마다 컬러 다르게
                rounded=True#박스 모서리
                precision = 3 #소수점 자리수
                )
 
 
from subprocess import call
call(['dot''-Tpng''tree.dot''-o''decistion-tree.png''-Gdpi=600'])
 
 
#png 출력
from IPython.display import Image
Image(filename = 'decistion-tree.png')
 
cs

그런데 이 과정에서 대부분 겪는 에러가 있다. 

1
ExecutableNotFound: failed to execute ['dot''-Tsvg'], make sure the Graphviz executables are on your systems' PATH
cs

나는 리눅스 환경이라 아래 명령어로 graphviz 재설치 해줬더니 해결되었다.

1
sudo apt install python-pydot python-pydot-ng graphviz #graphviz 리눅스 설치 명령
cs