Decision tree 방법은 회귀(regression) 및 분류(classification)에 사용되는 방법이다. Tree-based method는 여러가지 방법이 있지만 여기서는 세 가지 방법을 소개하고자 한다.

tree 패키지를 이용하는 방법

첫번째 방법은 An introduction to statistical learning 책에 소개되어 있는 방법이다. 예를 들기 위해 붓꽃(iris)의 데이타를 이용하고자 한다. 붓꽃의 데이타는 R에 내장되어 있는 세 종류의 붓꽃 종(Species)에 따른 꽃잎 및 꽃받침의 길이 및 넓이에 대한 데이타로 Iris setosa, versicolor 그리고 virginica 종 각각 50개체의 데이타이다.

data(iris)
str(iris)
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
table(iris$Species)

    setosa versicolor  virginica 
        50         50         50 

먼저 tree 라이브러리를 불러온다. iris 자료를 training set(70%)와 testing set(30%) 로 나누어 training set 자료를 이용하여 classification tree 를 만든후 이 tree를 이용하여 testing data에서 Species를 예측해보고 실제의 Species와 비교하여 classification tree의 예측의 정확도를 평가해본다

library(tree)
set.seed(2)
train=sample(1:nrow(iris),nrow(iris)*0.7)
training=iris[train,]
testing=iris[-train,]
itree =tree(Species~.,training)
itree
node), split, n, deviance, yval, (yprob)
      * denotes terminal node

 1) root 105 200 versicolor ( 0.34 0.35 0.30 )  
   2) Petal.Length < 2.45 36   0 setosa ( 1.00 0.00 0.00 ) *
   3) Petal.Length > 2.45 69 100 versicolor ( 0.00 0.54 0.46 )  
     6) Petal.Width < 1.75 41  30 versicolor ( 0.00 0.90 0.10 )  
      12) Petal.Length < 4.95 36   9 versicolor ( 0.00 0.97 0.03 )  
        24) Sepal.Length < 5.15 5   5 versicolor ( 0.00 0.80 0.20 ) *
        25) Sepal.Length > 5.15 31   0 versicolor ( 0.00 1.00 0.00 ) *
      13) Petal.Length > 4.95 5   7 virginica ( 0.00 0.40 0.60 ) *
     7) Petal.Width > 1.75 28   0 virginica ( 0.00 0.00 1.00 ) *
plot(itree)
text(itree,pretty=0)

plot of chunk unnamed-chunk-2

ipredict=predict(itree,testing,type="class")
table(ipredict,testing$Species)
            
ipredict     setosa versicolor virginica
  setosa         14          0         0
  versicolor      0         12         0
  virginica       0          1        18

caret 패키지에 있는 confusionMatrix 함수를 쓰면 자세한 결과를 알수 있다.

library(caret)
Loading required package: lattice
Loading required package: ggplot2
confusionMatrix(ipredict, testing$Species)
Confusion Matrix and Statistics

            Reference
Prediction   setosa versicolor virginica
  setosa         14          0         0
  versicolor      0         12         0
  virginica       0          1        18

Overall Statistics
                                        
               Accuracy : 0.978         
                 95% CI : (0.882, 0.999)
    No Information Rate : 0.4           
    P-Value [Acc > NIR] : <2e-16        
                                        
                  Kappa : 0.966         
 Mcnemar's Test P-Value : NA            

Statistics by Class:

                     Class: setosa Class: versicolor Class: virginica
Sensitivity                  1.000             0.923            1.000
Specificity                  1.000             1.000            0.963
Pos Pred Value               1.000             1.000            0.947
Neg Pred Value               1.000             0.970            1.000
Prevalence                   0.311             0.289            0.400
Detection Rate               0.311             0.267            0.400
Detection Prevalence         0.311             0.267            0.422
Balanced Accuracy            1.000             0.962            0.981

이 모델을 이용한 예측은 97.8%의 정확도를 보였다.

caret패키지의 rpart 를 이용한 방법

두번째 방법은 caret 패키지의 rpart method를 이용한 방법이다. 이 부분은 cousera의 온라인 강의 중 practical machine learnig 부분에 있는 내용이다. 먼저 전체 데이타의 70%를 training set, 30%를 testing set를 나눈다. 여기서는 createDataPartition 함수를 이용하여 데이타를 traing set, testing set로 나누었다.

inTrain=createDataPartition(y=iris$Species,p=0.7,list=FALSE)
training=iris[inTrain,]
testing=iris[-inTrain,]
dim(training);dim(testing)
[1] 105   5
[1] 45  5

caret 패키지의 rpart method를 이용해 training set에서 model을 만든다. finalModel을 plot 해본다.

modFit=train(Species~.,method="rpart",data=training)
print(modFit$finalModel)
n= 105 

node), split, n, loss, yval, (yprob)
      * denotes terminal node

1) root 105 70 setosa (0.33333 0.33333 0.33333)  
  2) Petal.Length< 2.45 35  0 setosa (1.00000 0.00000 0.00000) *
  3) Petal.Length>=2.45 70 35 versicolor (0.00000 0.50000 0.50000)  
    6) Petal.Length< 4.75 32  1 versicolor (0.00000 0.96875 0.03125) *
    7) Petal.Length>=4.75 38  4 virginica (0.00000 0.10526 0.89474) *
plot(modFit$finalModel,uniform=TRUE, main="Classification Tree")
text(modFit$finalModel, use.n=TRUE, all=TRUE,cex=0.8)

plot of chunk unnamed-chunk-5

이 plot은 모양이 좋지 않기 때문에 rattle 패키지의 fancyRpartPlot을 이용해 그려본다.

library(rattle)
fancyRpartPlot(modFit$finalModel)

plot of chunk unnamed-chunk-6

이모델을 이용하여 testing set에서 결과를 예측해보면 다음과 같다.

predict(modFit,newdata=testing)
 [1] setosa     setosa     setosa     setosa     setosa     setosa    
 [7] setosa     setosa     setosa     setosa     setosa     setosa    
[13] setosa     setosa     setosa     versicolor versicolor versicolor
[19] versicolor versicolor versicolor versicolor versicolor virginica 
[25] virginica  versicolor versicolor versicolor versicolor versicolor
[31] virginica  virginica  virginica  virginica  virginica  virginica 
[37] virginica  virginica  virginica  virginica  virginica  virginica 
[43] virginica  virginica  virginica 
Levels: setosa versicolor virginica
confusionMatrix(predict(modFit,newdata=testing), testing$Species)
Confusion Matrix and Statistics

            Reference
Prediction   setosa versicolor virginica
  setosa         15          0         0
  versicolor      0         13         0
  virginica       0          2        15

Overall Statistics
                                        
               Accuracy : 0.956         
                 95% CI : (0.849, 0.995)
    No Information Rate : 0.333         
    P-Value [Acc > NIR] : <2e-16        
                                        
                  Kappa : 0.933         
 Mcnemar's Test P-Value : NA            

Statistics by Class:

                     Class: setosa Class: versicolor Class: virginica
Sensitivity                  1.000             0.867            1.000
Specificity                  1.000             1.000            0.933
Pos Pred Value               1.000             1.000            0.882
Neg Pred Value               1.000             0.938            1.000
Prevalence                   0.333             0.333            0.333
Detection Rate               0.333             0.289            0.333
Detection Prevalence         0.333             0.289            0.378
Balanced Accuracy            1.000             0.933            0.967

이 모델을 이용한 예측은 95.6%의 정확도를 보인다.

Party 패키지의 ctree를 이용하는 방법

세번째 방법은 party 패키지의 ctree를 이용하는 방법이다. 이 방법은 stack overflow를 검색하는 중 알게 된 내용을 응용한 것이다.

library(party)
library(caret)
gtree <- ctree(Species ~ ., data = iris)
plot(gtree)

plot of chunk unnamed-chunk-8

plot(gtree, inner_panel = node_barplot,
     edge_panel = function(...) invisible(), tnex = 1)

plot of chunk unnamed-chunk-8

table(Predict(gtree), iris$Species)
            
             setosa versicolor virginica
  setosa         50          0         0
  versicolor      0         49         5
  virginica       0          1        45
confusionMatrix(Predict(gtree), iris$Species)
Confusion Matrix and Statistics

            Reference
Prediction   setosa versicolor virginica
  setosa         50          0         0
  versicolor      0         49         5
  virginica       0          1        45

Overall Statistics
                                        
               Accuracy : 0.96          
                 95% CI : (0.915, 0.985)
    No Information Rate : 0.333         
    P-Value [Acc > NIR] : <2e-16        
                                        
                  Kappa : 0.94          
 Mcnemar's Test P-Value : NA            

Statistics by Class:

                     Class: setosa Class: versicolor Class: virginica
Sensitivity                  1.000             0.980            0.900
Specificity                  1.000             0.950            0.990
Pos Pred Value               1.000             0.907            0.978
Neg Pred Value               1.000             0.990            0.952
Prevalence                   0.333             0.333            0.333
Detection Rate               0.333             0.327            0.300
Detection Prevalence         0.333             0.360            0.307
Balanced Accuracy            1.000             0.965            0.945

이 모델은 96.0%의 정확도를 보인다. 이 모델에서 보여주는 Petal.Length 1.9, 4.8 그리고 Petal.Width 1.7의 값을 plot에서 확인해본다.

plot of chunk unnamed-chunk-9