반응형


R 랜덤포레스트 사용하기


머신러닝 분야에서 많이 쓰이는 예제 데이터셋 Pima Diabetes 자료를 통해 간단한 Random Forest를 사용하는 방법을 알아보겠습니다.


라이브러리 로드

library(MASS) library(randomForest) library(caret)

MASS : 예제 데이터셋이 있는 라이브러리

randomForest : randomForest 이용을 위한 라이브러리

caret : 성능 평가시 confusion matrix를 그리기 위한 라이브러리


데이터 불러오기

data("Pima.tr")
data("Pima.te")

R에서 데이터 불러오는 방법은 라이브러리가 로드된 상태에서 data("데이터이름")이라고 실행하면, 작업공간상에 데이터가 생성됩니다.


> head(Pima.tr)
  npreg glu bp skin  bmi   ped age type
1     5  86 68   28 30.2 0.364  24   No
2     7 195 70   33 25.1 0.163  55  Yes
3     5  77 82   41 35.8 0.156  35   No
4     0 165 76   43 47.9 0.259  26   No
5     0 107 60   25 26.4 0.133  23   No
6     5  97 76   27 35.6 0.378  52  Yes

RandomForest 모형 만들기

set.seed(10)
rf.fit = randomForest(type ~ npreg + glu + bp + skin + bmi + ped + age
                      , data=Pima.tr, mtry = floor(sqrt(7)), ntree = 500, importance = T)
rf.fit

randomForest 모형을 만드는 문법은 위와 같습니다. hyper parameter로 이 모형에서는 mtry와 ntree를 사용하였습니다. mtry는 각각의 tree마다 몇 개의 feature를 사용할 것인지를 정하는 것입니다. 골드스탠다다는 보통, regression의 경우 변수갯수/3, classification의 경우 sqrt(변수갯수)를 사용합니다. 이 데이터셋은 classification 문제이므로, sqrt를 사용하였습니다. ntree는 tree의 총 갯수를 의미합니다.


테스트 데이터 생성

test_x = Pima.te[c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")]
test_y = Pima.te$type

test_y를 불러올 때는 $로 불러와야지 vector로 불러와지므로 아래 confusionMatrix가 잘 실행됩니다.


성능 평가

y_pred = predict(rf.fit, test_x)

confusionMatrix(y_pred, test_y)
Confusion Matrix and Statistics

          Reference
Prediction  No Yes
       No  192  46
       Yes  31  63
                                          
               Accuracy : 0.7681          
                 95% CI : (0.7189, 0.8124)
    No Information Rate : 0.6717          
    P-Value [Acc > NIR] : 7.678e-05       
                                          
                  Kappa : 0.455           
 Mcnemar's Test P-Value : 0.1106          
                                          
            Sensitivity : 0.8610          
            Specificity : 0.5780          
         Pos Pred Value : 0.8067          
         Neg Pred Value : 0.6702          
             Prevalence : 0.6717          
         Detection Rate : 0.5783          
   Detection Prevalence : 0.7169          
      Balanced Accuracy : 0.7195          
                                          
       'Positive' Class : No    


변수 중요도

> importance(rf.fit)
             No       Yes MeanDecreaseAccuracy MeanDecreaseGini
npreg  9.467923  1.762747             9.098049         9.308814
glu   14.543787 16.760373            20.263701        21.771324
bp     4.210273 -8.185459            -1.740227         7.920807
skin   1.370477  1.662921             2.029630         9.350372
bmi    3.431359  7.500978             7.200368        13.322145
ped    4.957824  4.666885             6.778956        13.479470
age   12.162707  6.341079            13.414806        14.528669

변수 중요도 플롯




17페이지에 random forest hyper-parameter 관련한 설명들이 나온다.

https://cran.r-project.org/web/packages/randomForest/randomForest.pdf


Random Forest 관련 튜토리얼

https://machinelearningmastery.com/tune-machine-learning-algorithms-in-r/

반응형
반응형