본문 바로가기
머신러닝 알아보기

[머신러닝] 3. Random Forest

by 빈이름 2024. 11. 27.
1.  Random Forest 
    1.1. Random Forest의 알고리즘
2. Random Forest의 특징
    2.1. 장점
    2.2. 단점
3. Random Forest 코드 구현
    3.1. scikit-learn에서의 Random Forest
    3.2. Random Forest 모델 실험
          A. n_estimators 
          B. criterion
          C. Pruning 

1. Random Forest

Random Forest는 여러 개의 Decision Tree를 학습한 뒤, 앙상블을 통해 결과를 예측하는 머신러닝 기법입니다.

Random Forest

따라서 더 자세히 알고 싶다면 Decision Tree를 먼저 알고 오는 것이 좋습니다. Decision Tree에 대한 설명은 아래 글에서 확인할 수 있습니다.

https://all-the-meaning.tistory.com/69?category=1235363

 

[머신러닝] 2. Decision Tree

1. Decision Tree     1.1. CART 알고리즘         A. 분류 문제         B. 회귀 문제2. Pruning     2.1. 소제목    2.2. 소제목3. Decision Tree의 주요 특징    3.1. Decision Tree의 장점    3.2. Decision Tree의

all-the-meaning.tistory.com

1.1. Random Forest의 알고리즘

  1. 데이터 샘플링
    • 학습 데이터에서 중복을 포함하여 랜덤 샘플링해 새로운 데이터셋들을 구성합니다.
    • 만들고자 하는 Tree의 수만큼 데이터셋을 샘플링합니다.
  2. Decision Tree 학습
    • 추출한 각 샘플 데이터셋마다 Decision Tree를 학습합니다.
  3. 예측
    • 분류 문제 : 각 트리가 예측한 클래스들의 다수결 투표를 통해 최종 클래스를 예측합니다.
    • 회귀 문제 : 각 트리가 예측한 값들을 평균 내어 최종 예측값을 계산합니다.

2. Random Forest의 특징

2.1. 장점

  • Decision Tree의 성능을 개선
    • 여러 개의 Decision Tree를 결합하기 때문에 Decision Tree의 장점도 그대로 가져가며, Decision Tree가 가질 수 있는 과적합 문제를 완화할 수 있으며, 더 안정적이고 높은 성능을 낼 수 있습니다.
  • Outlier에 영향을 적게 받습니다.
  • 병렬 학습으로 학습 시간을 단축할 수 있습니다.

2.2. 단점

  • 계산 비용이 큽니다.
    • 여러 개의 Decision Tree를 학습해야 하기 때문에 학습 시간이 길어지고 메모리도 많이 차지할 수 있습니다.
  • 해석이 어렵습니다.
    • 하나의 Decision Tree는 시각화도 가능하고 해석 가능하지만, 여러 개가 모여서 결과를 도출하는 Random Forest는 해석이 불가능합니다.

3. Random Forest 코드 구현

3.1. scikit-learn에서의 Random Forest

https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html

 

RandomForestClassifier

Gallery examples: Release Highlights for scikit-learn 1.4 Release Highlights for scikit-learn 0.24 Release Highlights for scikit-learn 0.22 Comparison of Calibration of Classifiers Probability Cali...

scikit-learn.org

from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline

clf = RandomForestClassifier(
    n_estimators=100,
    criterion='gini',
    min_samples_split=2,
    max_features=None,
    ccp_alpha=0
)

clf.fit(train_x, train_y)

Decision Tree를 기반으로 하기 때문에 파라미터는 크게 다르지 않습니다.

  • n_estimator : 몇 개의 Decision Tree를 학습할 지를 결정합니다.

3.2.  Random Forest 모델 실험

breast cancer 데이터셋을 Random Forest를 이용해 학습해 보도록 하겠습니다.

https://colab.research.google.com/drive/1-d6MuNRtpr2bSthgE59FtugbXfeCe1iN?usp=sharing

 

Random Forest.ipynb

Colab notebook

colab.research.google.com

 

A. n_estimators

from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline

n_estimators = [5, 20, 50, 100, 150]

for n in n_estimators:
    clf = RandomForestClassifier(
        n_estimators=n,
        criterion='gini',
        min_samples_split=2,
        max_features=None,
        ccp_alpha=0
    )

    pipeline = Pipeline(
        [('scaler', StandardScaler()), ('model', clf)]
    )

    pipeline.fit(train_x, train_y)
    print(f"{n} : {pipeline.score(test_x, test_y)}")
    
'''
5 : 0.956140350877193
20 : 0.9385964912280702
50 : 0.9649122807017544
100 : 0.9649122807017544
150 : 0.9736842105263158
'''

역시 실행할 때마다 결과는 달라지지만 대체로 n_estimators가 커질수록 성능이 높아지는 경향을 보입니다. 또한, 단일 Decision Tree를 사용할 때보다 더 높은 점수를 받는 것을 확인할 수 있습니다.

B. Criterion

criterions = ['gini', 'entropy', 'log_loss']

scores = [0, 0, 0]

for i in range(5):
    for i, criterion in enumerate(criterions):
        clf = RandomForestClassifier(
            n_estimators=100,
            criterion=criterion,
            min_samples_split=2,
            max_features=None,
            ccp_alpha=0
        )

        pipeline = Pipeline(
            [('scaler', StandardScaler()), ('model', clf)]
        )

        pipeline.fit(train_x, train_y)
        score = pipeline.score(test_x, test_y)
        scores[i] += score
        
print(f"gini : {scores[0]/5}")
print(f"entropy : {scores[1]/5}")
print(f"log_loss : {scores[2]/5}")

'''
gini : 0.968421052631579
entropy : 0.9649122807017545
log_loss : 0.9631578947368421
'''

실행할 때마다 결과가 달라지기 때문에 5번 학습하고 평균 점수를 내봤습니다. Decision Tree와 달리 여기선 gini가 더 높은 점수를 받았습니다.

C. Pruning

max_features = [2, 5, 10, 20, 30]

for max_feature in max_features:
    clf = RandomForestClassifier(
        n_estimators=100,
        criterion='gini',
        min_samples_split=2,
        max_features=max_feature,
        ccp_alpha=0
    )

    pipeline = Pipeline(
        [('scaler', StandardScaler()), ('model', clf)]
    )

    pipeline.fit(train_x, train_y)
    print(f"{max_feature} : {pipeline.score(test_x, test_y)}")
    
'''
2 : 0.9649122807017544
5 : 0.9649122807017544
10 : 0.9649122807017544
20 : 0.9736842105263158
30 : 0.9736842105263158
'''

max_features의 경우, Decision Tree에서 조정할 때에 비해 실험할 때마다 점수 차이가 크지 않은 것을 확인할 수 있었습니다. 여러 개의 Decision Tree를 쓰는만큼 안정성이 올라간 것을 알 수 있습니다.

ccp_alphas = [0, 0.01, 0.1, 0.2, 0.5]

scores = [0] * len(ccp_alphas)

for i in range(5):
    for i, ccp_alpha in enumerate(ccp_alphas):
        clf = RandomForestClassifier(
            n_estimators=100,
            criterion='gini',
            min_samples_split=2,
            max_features=None,
            ccp_alpha=ccp_alpha
        )

        pipeline = Pipeline(
            [('scaler', StandardScaler()), ('model', clf)]
        )

        pipeline.fit(train_x, train_y)
        score = pipeline.score(test_x, test_y)
        scores[i] += score
        
for i, ccp_alpha in enumerate(ccp_alphas):
    print(f"{ccp_alpha} : {scores[i]/5}")
    
'''
0 : 0.9719298245614036
0.01 : 0.9543859649122807
0.1 : 0.9508771929824562
0.2 : 0.9543859649122807
0.5 : 0.6666666666666666
'''

ccp_alpha는 이번에도 0일 때 성능이 가장 좋은 것으로 보입니다.

 

1. KNN : https://all-the-meaning.tistory.com/65
2. Decision Tree : https://all-the-meaning.tistory.com/69
4. Linear/Logistic Regression : https://all-the-meaning.tistory.com/71
5. SVM : https://all-the-meaning.tistory.com/72
6. 머신러닝 총정리 : https://all-the-meaning.tistory.com/73