라일락 꽃이 피는 날

[R] k-Nearest Neighbor (KNN) 본문

데이터 분석/R

[R] k-Nearest Neighbor (KNN)

eunki 2021. 6. 30. 19:07
728x90

패키지 설치

caret 패키지는 다른 패키지들을 이용하기때문에 dependencies = TRUE 옵션이 필요하다.

install.packages("caret", dependencies = TRUE) 
library(caret)

 

 

 

데이터 불러오기

as.factor() : 데이터는 숫자 형식이지만 명목 변수이기 때문에 숫자로 다루지 않기 위해 Factor 타입으로 변환

rawdata <- read.csv("wine.csv", header = TRUE)

rawdata$Class <- as.factor(rawdata$Class)
str(rawdata)

 

 


트레이닝-테스트 셋 분리 (7:3) 

sample(a, b) : 1부터 a까지 숫자 중에 b개 추출 
nrow() : 데이터 행(row) 수 
sort() : 오름차순 정렬 

analdata <- rawdata

set.seed(2020)  # 시드

datatotal <- sort(sample(nrow(analdata), nrow(analdata)*0.7))
train <- rawdata[datatotal,]
test <- rawdata[-datatotal,]

train_x <- train[,1:13]
train_y <- train[,14]

test_x <- test[,1:13]
test_y <- test[,14]

 



모형학습

1. 데이터 훈련(train) 과정의 파라미터(parameter) 설정

method = "repeatedcv" : cross-validation (cv) 반복 
number : 훈련 데이터 fold 개수 
repeats : cv 반복 횟수 

ctrl <- trainControl(method = "repeatedcv",
                     number = 10,
                     repeats = 5)

 

 

 

2. 모든 벡터 혹은 인자(factor) 조합인 데이터 프레임 생성

customGrid <- expand.grid(k=1:10)

 

 

 

3. 머신러닝 알고리즘 이용해 데이터학습을 통한 모델 생성

Class~., : 타겟 ~ 피쳐 (. = all) 

data : 학습 데이터
method : 사용하고 싶은 머신러닝 방법 
trControl : 학습 방법 
preProcess = c("center", "scale") : 데이터 전처리 = 표준화 (평균을 빼고 표준편차로 나눔)
tuneGrid : 튜닝 파라미터 값 목록 
metric : 모형 평가 방식 

knnFit <- train(Class~.,
                data = train, 
                method = "knn",
                trControl = ctrl,
                preProcess = c("center", "scale"),
                tuneGrid = customGrid,
                metric = "Accuracy")
              
knnFit

 

 → k = 5일 때, 가장 높은 정확도를 가진다.

 

 

 

plot(knnFit) 

 

 


예측

pred_test <- predict(knnFit, newdata = test) 

 

 


분할표

confusionMatrix(pred_test, test$Class)

 

→ Accuracy : 0.944, Kappa : 0.913 

 

 


변수중요도

각 피쳐들의 중요도를 나타낸다.

importance_knn <- varImp(knnFit, scale = FALSE) 
importance_knn

 

 

 

plot(importance_knn)

728x90

'데이터 분석 > R' 카테고리의 다른 글

[R] Naive Bayes Classification (나이브 베이즈 분류)  (0) 2021.07.02
[R] Logistic Regression (로지스틱 회귀)  (0) 2021.06.30
[R] 카이제곱 검정  (0) 2021.06.27
[R] ANOVA 검정  (0) 2021.06.27
[R] z-test (z-검정)  (0) 2021.06.27