Naive Bayes Classification

2021. 6. 24. 13:18R 공부/지도학습

 조건부 확률

P(X=1) : 확률 변수 X가 1일 확률

X=1 은 이벤트 라고 부른다.

P(X=1 | Y=1) : Y=1일떄, X가 1일 확률

 

예를 들면 축구를 할때

X 가 승리가 될수도 있고 패배가 될확률이 라고 하자

Y는 선제골을 넣는것과 선제골을 먹히는것으로 정의하면

P(X = 승리) = 승리할 확률

P(X = 승리 | Y = 선제골넣음) = 선제골을 넣었을때, 승리할 확률

P(X= 승리 |  Y = 선제골먹힘) = 선제골을 먹혔을때, 승리할 확률

여기서 P(X)는 사전확률로써 이벤트 발생 전 확률이다.

P(X|Y)는 사후확률로써 이벤트 발생 후 확률이다.

 

그리고 조건부 독립이 있는데

 

P(X1,X2|Y) = P(X1|Y)P(X2|Y) 이다

 

실제로 나이브 베이즈 실습을 해보자

 

오늘쓸 데이터는 와인데이터이다.

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

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

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]

데이터를 가져와서 트레이닝-테스트 셋으로 나눈다.

 

ctrl <- trainControl(method = "repeatedcv",repeats = 5) #어떤식으로 훈련시킬건지

nbFit <- train(Class~.,
               data = train,
               method = "naive_bayes",
               trControl = ctrl,
               preProcess = c("center","scale"),
               metric = "Accuracy"
  
)
nbFit

트레이닝을 시키고 결과를 확인한다.

Naive Bayes 

124 samples
 13 predictor
  3 classes: '1', '2', '3' 

Pre-processing: centered (13), scaled (13) 
Resampling: Cross-Validated (10 fold, repeated 5 times) 
Summary of sample sizes: 111, 112, 112, 111, 110, 112, ... 
Resampling results across tuning parameters:

  usekernel  Accuracy   Kappa    
  FALSE      0.9808142  0.9708775
   TRUE      0.9756810  0.9631746

Tuning parameter 'laplace' was held constant at a value of
 0
Tuning parameter 'adjust' was held constant at a value of 1
Accuracy was used to select the optimal model using
 the largest value.
The final values used for the model were laplace =
 0, usekernel = FALSE and adjust = 1.

laplace는 laplace smoothing 에서 알파 값이고 0 이면 값을 더하지 않았다.

userkernel은 커널의 사용유무,

adjust는 bandwidth 값을 수정할때 사용한다, 그리고 usekernerl이 TRUE일때만 유효한 값이다.

 

kernel을 사용하지 않았을때 정확도가 더 높다.

 

 

전체 데이터를 train , test로 나누고 train의 결과로 모형을 만들고 test를 하는과정이 예측이다.

pred_test <- predict(nbFit,newdata = test)

confusionMatrix(pred_test,test$Class)


Confusion Matrix and Statistics

          Reference
Prediction  1  2  3
         1 14  1  0
         2  0 24  0
         3  0  2 13

Overall Statistics
                                          
               Accuracy : 0.9444          
                 95% CI : (0.8461, 0.9884)
    No Information Rate : 0.5             
    P-Value [Acc > NIR] : 1.459e-12       
                                          
                  Kappa : 0.913           
                                          
 Mcnemar's Test P-Value : NA              

Statistics by Class:

                     Class: 1 Class: 2 Class: 3
Sensitivity            1.0000   0.8889   1.0000
Specificity            0.9750   1.0000   0.9512
Pos Pred Value         0.9333   1.0000   0.8667
Neg Pred Value         1.0000   0.9000   1.0000
Prevalence             0.2593   0.5000   0.2407
Detection Rate         0.2593   0.4444   0.2407
Detection Prevalence   0.2778   0.4444   0.2778
Balanced Accuracy      0.9875   0.9444   0.9756

변수 중요도를 보자

importance_nb <- varImp(nbFit,scale=FALSE) #ROC커브의 밑 면적이 넓을수록 좋다
plot(importance_nb)

'R 공부 > 지도학습' 카테고리의 다른 글

Decision Tree 와 Random_Forest  (0) 2021.06.25
Logistic Regression  (0) 2021.06.24
KNN(K-Nearest Neighbor)  (2) 2021.06.23