DecisionTree : 의사결정나무

  • 어떤 항목에 대한 관측값과 목표값을 연결시켜주는 예측모델
  • 시각적이고 명시적인 방법으로 의사 결정 과정과 결정된 의사를 보여주는 데 사용
  • 데이터 분할을 하기 위해, 가장 훌륭한 변수가 무엇인지 찾아야함

 

간단한 파이썬으로 iris 데이터를 의사결정나무로 에측해본 것입니다.

 

# Decision Tree

# 필요 모듈 import
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
from sklearn import tree
from sklearn.model_selection import train_test_split

# 사이킷런의 iris 데이터 불러오기
iris_dataset = load_iris()

# data split
X = iris_dataset.data
y = iris_dataset.target
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3, random_state = 25)

# 객체 생성
# max_depth : 사용자 설정에 따라 tree의 레벨 조정 가능
clf = tree.DecisionTreeClassifier(max_depth=None, random_state=0)

# 모델링
clf.fit(X_train, y_train)

print("훈련 세트 점수 {:3f}".format(clf.score(X_train, y_train)))
print("테스트 세트 점수 {:3f}".format(clf.score(X_test, y_test)))

 

 

여기서 해당 모델에 대해 시각적으로 확인하고 싶으면

# 아나콘다에서 설치 필요
#conda install graphviz
#conda install python-graphviz



import os

# 환경변수 조정
os.environ['PATH']+=os.pathsep+'C:/Anaconda3/Library/bin/graphviz/'

# 모델 저장
export_graphviz(clf, out_file = "iris.dot",
               feature_names=cancer.feature_names,
               class_names=cancer.target_names,
               rounded=True, proportion=False,
               filled=True, precision=2)

# 파일로 불러오기
with open("iris.dot") as f:
    dot_graph=f.read()

dot_graph

graphviz.Source(dot_graph)

 

 

소스를 돌리면 위와 같은 트리 그래프가 출력되게 됩니다.

'머신러닝 in Python' 카테고리의 다른 글

[Python] RandomForest 예제  (0) 2019.08.27
[Python] RandomForest  (0) 2019.08.27
[Python] k-nearest neighbor 예제  (0) 2019.08.26
[Python]k-nearest neighbor  (0) 2019.08.26
텍스트 분석_BOW  (0) 2019.08.14

+ Recent posts