728x90

가장 많이 알려져 있는 데이터인 붓꽃 데이터(iris)를 이용하여 의사결정트리를 실행합니다.

사용되는 패키지는 {rpart} 이고, 사용되는 함수도 rpart()입니다.

뒷부분에 모형 평가를 위해 패키지 caret 사용법을 추가했습니다.

 

1. 의사결정나무 실행 - 패키지 rpart 이용

 

install.packages("rpart")  # 패키지  rpart 설치

library(rpart)                # 패키지 rpart 로딩

rpart(Species ~., data=iris)  # 종속변수 붓꽃의 종류 Species로 하고, 나머지 변수로 의사결정모형을 실행

 

plot(model_rpa,compress=T,margin=0.2)   # 의사결정모형의 결과를 Plot

text(model_rpa, cex=1.5)

# [[ 해석 ]]

꽃받침의 길이가 2.45. 보다 작은 것: (50개 있는데 : Setosa 50)

 

꽃받침의 길이가 2.45. 보다 큰 것 중에서

꽃잎의 길이가 1.75보다 작으면 versicolor

꽃잎의 길이가 1.75보다 크면 virginica

 

post(model_rpa,file="")

2. 혼동행렬( confusion matrix)을 만드는 과정

 

다음은 모형 평가를 위해 혼동행렬( confusion matrix)을 만드는 과정입니다.

 

pred <- predict(model_rpa,iris,type="class")  # 예측값을 변수 pred에 저장

c.table <- table(iris$Species,pred)               # 원래의 값과 예측값 pred, 테이블 만듦

c.table

 

error <- 1-(sum(diag(c.table))/sum(c.table))  # 오류율 계산  (대각성은 맞게 예측한 부분)/(전체 수)

paste("error =",round(error*100,2),"%")

 

3. 패키지 caret 이용 모형 평가

library(rpart)

set.seed(1234)

data(iris)

model_rpart <- rpart(Species~.,data=iris)

pred_rpart <- predict(model_rpart,iris,type='class')

confusionMatrix(pred_rpart,iris$Species)

 

 

+ Recent posts