Summary

caret 패키지를 사용한 기계학습을 사용해본다. spam의 data set은 스팸의 특성(feature)을 변수로 가지고 있으며, 스팸 여부는 type 컬럼에 저장된다. 여기서는 스팸의 특성을 이용해서 스팸여부(type)를 예측하기 위해 모델링하는 과정을 기술한다.

caret 패키지를 로딩한다. kernlab 패키지에는 spam 데이터 셋트가 있다.

library(caret)
## Loading required package: lattice
## Loading required package: ggplot2
library(kernlab)
data(spam)

사전작업: 데이터 셋트 분리(훈련용, 테스트용)

# spam$type: spam, nonspam 구분값
inTrain <- createDataPartition(y = spam$type, p = 0.75, list = FALSE)
training <- spam[inTrain, ]
testing <- spam[-inTrain, ]

학습 및 모델 생성

psedo 랜덤값을 설정한다. train() 함수를 이용해서 훈련용 데이터셋트(training)에 glm 모델을 적용한다.

set.seed(32343)
modelFit <- train(type ~ ., data = training, method = "glm")
# modelFit$finalModel

모델 성능 평가: 모델의 예측 결과와 실제값을 비교

predict(모델, 테스트 데이터셋트) 함수를 이용해서 testing 데이터셋트의 스팸 여부를 예측한다.

confusionMatrix(예측값, 결과값) 함수를 이용하면 정확도를 알 수 있다.

predictions <- predict(modelFit, newdata = testing)
confusionMatrix(predictions, testing$type)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction nonspam spam
##    nonspam     667   49
##    spam         30  404
##                                           
##                Accuracy : 0.9313          
##                  95% CI : (0.9151, 0.9452)
##     No Information Rate : 0.6061          
##     P-Value [Acc > NIR] : < 2e-16         
##                                           
##                   Kappa : 0.8551          
##  Mcnemar's Test P-Value : 0.04285         
##                                           
##             Sensitivity : 0.9570          
##             Specificity : 0.8918          
##          Pos Pred Value : 0.9316          
##          Neg Pred Value : 0.9309          
##              Prevalence : 0.6061          
##          Detection Rate : 0.5800          
##    Detection Prevalence : 0.6226          
##       Balanced Accuracy : 0.9244          
##                                           
##        'Positive' Class : nonspam         
##