데이터분석/R

[ADP] 랜덤 포레스트 (Random Forest)

버섯도리 2022. 1. 15. 18:04

> # 07. 랜덤 포레스트 (Random Forest)


> # 1. 랜덤 포레스트 분류

> library(randomForest)

> m <- randomForest(Species~., data = iris)
> m

Call:
 randomForest(formula = Species ~ ., data = iris) 
               Type of random forest: classification
                     Number of trees: 500
No. of variables tried at each split: 2

        OOB estimate of  error rate: 4%
Confusion matrix:
           setosa versicolor virginica class.error
setosa         50          0         0        0.00
versicolor      0         47         3        0.06
virginica       0          3        47        0.06
> # 매 분할마다 2개의 변수를 샘플링해 디폴트로 500개의 각기 다른 트리를 랜덤하게 생성 후 분석을 수행한다.
> # 모델 훈련에 사용되지 않은 데이터를 사용한 에러 추정치가 4%이다.

plot(m)

> # plot() 함수는 트리수에 따른 종속변수의 범주별 오분류율을 나타낸다. 검은색은 전체 오분류율을 나타낸다. 이 그림을 보면 단지 트리 몇 개만으로도 최소오차와 표준오차의 최저값을 얻을 수 있다는 것을 알 수 있다.


> # importance() vamImPlot() 함수로 변수의 중요성을 확인한다.
importance(m) # 각 변수들의 지니 지수 평균 감소에 대한 기여도이다.
             MeanDecreaseGini
Sepal.Length        10.721880
Sepal.Width          2.681942
Petal.Length        42.901395
Petal.Width         42.923237
varImpPlot(m) # 시각화

> # Petal.Width > Petal.Length > Sepal.Length > Sepal.Width 순서로 중요한 변수이다.


> # 2. 랜덤 포레스트 회귀

> library(ElemStatLearn)
> data("prostate")
> prostate$gleason <- ifelse(prostate$gleason == 6, 0, 1)
> pros.train <- subset(prostate, train==TRUE)[,1:9]
> pros.test <- subset(prostate, train==FALSE)[,1:9]

> rf.pros <- randomForest(lpsa~., data = pros.train)
> rf.pros

Call:
 randomForest(formula = lpsa ~ ., data = pros.train) 
               Type of random forest: regression
                     Number of trees: 500
No. of variables tried at each split: 2

          Mean of squared residuals: 0.680013
                    % Var explained: 52.68
> # 매 분할마다 2개의 변수를 샘플링해 500개의 각기 다른 트리를 랜덤 생성해 수행한다. 결과값은 MSE가 약 0.68이고 설명분산은 약 52.7%이다.
> # 트리가 너무 많아지면 과적합이 될 수 있다. 그 트리 수를 정하는 방법은 2가지가 있다. plot() 함수와 최소 MSE이다.

plot(rf.pros)

> # plot() 해당 모형에서 트리수에 따른 MES의 값을 나타내고 있다. 트리수가 늘어나는 초반에 MSE가 크게 개선되는 모습을 볼 수 있다. 생성한 트리수가 100개 넘어가면서 큰 변화없이 유지되는 결과가 나왔다.

 

 

 

 

 

출처 : 2020 데이터 분석 전문가 ADP 필기 한 권으로 끝내기