Skip to content

Instantly share code, notes, and snippets.

@enujo
Created July 27, 2017 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enujo/62c08ed06de5b4aa8662c0b1e2c1f786 to your computer and use it in GitHub Desktop.
Save enujo/62c08ed06de5b4aa8662c0b1e2c1f786 to your computer and use it in GitHub Desktop.
getwd()
#R에서 제공하는 기본 데이터인 iris를 이용하여 분류분석
# fix(iris)
str(iris)
# 분류분석을 위해서 필요한 라이브러리 설치/로드
#install.packages("party")
#library(party)
# 분류분석 : ctree()
iris.all <- ctree(Species ~Sepal.Length + Sepal.Width + Petal.Length + Sepal.Width, data=iris)
# 분류분석한 결과를(데이터 모델)를 출력
print(iris.all)
# 결과를 그래프로 출력
plot(iris.all)
# iris 데이터를 training 데이터 셋과 test 데이터 셋을 구분
# iris 데이터를 2가지 종류의 데이터로 구분하는데 조건은 7:3으로 함
tmpData <- sample(2, nrow(iris), replace=T, prob = c(0.7,0.3))
tmpData
# tmpData의 값이 1인 인덱스와 같은 iris데이터의 인덱스는 training 데이터
trainData <- iris[tmpData == 1,]
testData <- iris[tmpData == 2,]
trainData
testData
# trainData를 분류분석 : ctree()
iris.train <- ctree(Species~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data=trainData)
print(iris.train)
plot(iris.train)
# training 데이터로 생성된 모델의 평가를 위해 test데이터를 입력 ->예측
# predict()
testPred <- predict(iris.train, testData)
testPred
table(testPred, testData$Species)
# 예측결과와 실제 데이터의 정확도를 확인
sum(testPred == testData$Species) / length(testPred) *100
# 위에서 사용한 ctree() 함수와 다른 알고리즘으로 분류분석을 하는 rpart()
install.packages("rpart")
library(rpart)
# . 찍으면 안에있는 것 알아서 하라는 것
rpartTree <- rpart(Species~., data=iris)
# rpart분석에 있어서 Petal.Length, Petal.Width, Sepal.Length를 대상으로 분류
rpartTree <- rpart(Species~ Petal.Length+Petal.Width+Sepal.Length+, data=iris)
rpartTree
plot(rpartTree, compress=TRUE)
text(rpartTree, cex=1.0)
# rpart.plot 패키지에 있는 prp() 함수를 이용해서 플로팅
install.packages("rpart.plot")
library(rpart.plot)
prp(rpartTree, type=3, extra=2, digit=3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment