What is Random Forest

  • 여러개의 Decision Tree를 사용하는 앙상블 분류모형의 일종
  • 앙상블의 사전적 의미 : 1.음악 ( 2인 이상에 의한 가창이나 연주) 2.음악 ( 주로 실내악을 연주하는 소인원의 합주단*합창단)
  • 앙상블 러닝이 생겨난 배경 : 실제 데이터는 상당히 복잡하고, 여러 다양한 컨셉을 포함한. 따라서, 하나의 모델로 제대로 설명해내는데 어려움이 있음
  • 앙상블은 여러 다른 모델의 결과를 결합하여 사용함으로써, 일반적으로 하나의 모델을 사용한 것보다 분석 결과가 좋음

 

 

랜덤포레스트를 위해 파이썬에서 임의의 데이터 셋을 만들어 확인해보겠습니다.

from sklearn.ensemble import RandomForestClassifier
from sklearn import datasets
from sklearn.model_selection import train_test_split
import numpy as np
import matplotlib.pyplot as plt

# 1. toy 데이터 생성하기
X, y = datasets.make_moons(n_samples=100, noise=0.25, random_state=3)

# 1.1 데이터 확인
X.shape

plt.scatter(X[:,0],X[:,1],edgecolors='red',s=50,c=y)

# 1.2 데이터 분할
X_train,X_test,y_train,y_test = train_test_split(X,y, test_size = 0.2, random_state = 1234)

# 1.3 분할 데이터 확인
X_train.shape, y_train.shape

# 2. random forest 모델링을 위할 객체 생성
# n_estimators : 만들 의사결정나무 개수
forest = RandomForestClassifier(n_estimators=5, random_state=5)

# 3. 모델 적합
forest.fit(X_train, y_train)

# 4. 결과 확인
print("train accuracy {:.2f}".format(forest.score(X_train, y_train)))
print("test accuracy {:.2f}".format(forest.score(X_test, y_test)))

# 5 트리 확인
forest.estimators_

# 5-1 트리 일부 확인
export_graphviz(forest.estimators_[0], out_file = "rf{}.dot".format(0),
                rounded=True, proportion=False,
                filled=True, precision=2)
with open("rf{}.dot".format(0)) as f1:
    dot_graph1 = f1.read()
graphviz.Source(dot_graph1)

 

소스를 작동하면 다음과 같은 의사결정나무0 이 출력되게 됩니다!

 

랜덤포레스트가 어떤 의사결정나무로 구성되었는지 확인하고 싶으면 

export_graphviz(forest.estimators_[0], out_file = "rf{}.dot".format(0),
                rounded=True, proportion=False,
                filled=True, precision=2)
with open("rf{}.dot".format(0)) as f1:
    dot_graph1 = f1.read()
graphviz.Source(dot_graph1)

여기서 0을 5까지 변경시켜보면서 확인할 수 있습니다.

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

[Python] Gradient Boosting  (0) 2019.08.28
[Python] RandomForest 예제  (0) 2019.08.27
[Python] DecisionTree  (0) 2019.08.27
[Python] k-nearest neighbor 예제  (0) 2019.08.26
[Python]k-nearest neighbor  (0) 2019.08.26

+ Recent posts