1.Decision Tree
yes/no로 class 분류(if문 덩어리)
최상위 노드를 루트 노드(root node)하고 한다.
그리고 끝나는 지점의 노드는 리프 노드(leaf node)라고 한다.
중간에 있는 건 그냥 노드.
임포트
from sklearn.tree import DecisionTreeClassifier
dt = DecisionTreeClassifier(max_depth=3) # depth로 어디까지 노드 내려갈 수 있는지
알고리즘 훈련 및 정확도 테스트 ( 이 예제는 데이터빨로 정확도가 over-fit 되어있다. 100% 정확도는 오히려 좋지 않다.)
dt.fit(X_train, y_train)
y_pred = dt.predict(X_test)
print('tree 정확도: {:.2f}%'.format(accuracy_score(y_test, y_pred)*100))
출력>
tree 정확도: 100.00%
트리 구조를 그려주는 모듈 임포트
from sklearn.tree import export_graphviz # 트리의 구조 출력
export_graphviz(dt, out_file='tree.dot') # (model, out_file)을 써준다. model은 방금 우리가 학습시킨 모델 dt.fit을 넣고 파일을 'tree.dot'으로 저장한다.
파일 저장
from subprocess import call # dot 파일을 그림으로 그려 저장
call(['dot','-Tpng','tree.dot','-o', 'decistion-tree.png','-Gdpi=600']) # 파일저장: 포멧: dot, 선이 선명하게 나오는 png파일로 열기: Tpng(투명한 png), 그려줄 파일명 : tree.dot,저장할 이름 : decistion-tree.png, 그래픽해상도: '-Gdpi=600', 그리고 이제 잘 안먹히면 '-o'를 파일명 뒤에 붙여주면 된다.
그림으로 나타내주기
from IPython.display import Image
Image(filename = 'decistion-tree.png')

2. Random Forest
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier()
rf.fit(X_train, y_train)
y_pred = rf.predict(X_test)
print('랜덤 포레스트 정확도: {:.2f}'.format(accuracy_score(y_test, y_pred) * 100))
출력>
랜덤 포레스트 정확도: 100.00'machine_learning' 카테고리의 다른 글
| sklearn_regression 1. 예시용 당뇨병 데이터 정리 (0) | 2023.04.28 |
|---|---|
| sklearn_classification 평가 방법 (0) | 2023.04.28 |
| sklearn_classification 3. Support Vector Machine (0) | 2023.04.28 |
| sklearn_classification 2. Logistic Regression (0) | 2023.04.28 |
| sklearn_classification 1. 예시용 붓꽃 데이터 정리 과정 (0) | 2023.04.28 |