나이브 베이즈(Naive Bayes)

ddoddo·2023년 1월 12일
0

데이터분석 with R

목록 보기
15/21

나이브 베이즈

나이브 베이즈(Naive Bayes)는 베이즈 정리를 적용한 확률 분류 기법이다. 베이즈 정리는 조건부 확률을 구하는 공식으로 생각하면 된다. 조건부 확률이란 사건 B가 일어났다는 조건하에 사건 A가 일어날 확률을 P(AB)P(A|B) 라고 한다.

  • P(AB)=P(AB)/P(B)=P(BA)P(A)/P(B)P(A|B)=P(A\cap B)/P(B)=P(B|A)P(A)/P(B)
  • Posterior=LikelihoodPrior/evidencePosterior=Likelihood * Prior/evidence

패키지 설치

> install.packages('e1071')
> library(e1071)

Data Load

> train <- read.csv('ch6-2_train.csv', header=TRUE)
> test <- read.csv('ch6-2_test.csv', header=TRUE)

> str(train)
'data.frame':	240 obs. of  4 variables:
 $ wing_length: int  238 236 256 240 246 233 235 241 232 234 ...
 $ tail_length: int  63 67 65 63 65 65 66 66 64 64 ...
 $ comb_height: int  34 30 34 35 30 30 30 35 31 30 ...
 $ breeds     : chr  "a" "a" "a" "a" ...
 
 > str(test)
'data.frame':	60 obs. of  4 variables:
 $ wing_length: int  258 260 251 248 254 230 248 250 235 241 ...
 $ tail_length: int  67 64 63 63 62 64 65 65 62 67 ...
 $ comb_height: int  32 34 31 30 32 33 35 33 35 30 ...
 $ breeds     : chr  "a" "a" "a" "a" ...

나이브 베이즈

병아리 품종을 종속변수로, 나머지 변수를 독립변수로 활용한다.
naiveBayes() 함수를 통해 나이브 베이즈 알고리즘을 수행할 수 있다.

> nb <- naiveBayes(breeds ~ ., data=train)

나이브 베이즈 모델에 테스트용 데이터 셋을 이용해 품종 분류를 실시한다.

> test$pred <- predict(nb, newdata=test, type='class')
> head(test)
  wing_length tail_length comb_height breeds pred
1         258          67          32      a    a
2         260          64          34      a    a
3         251          63          31      a    a
4         248          63          30      a    a
5         254          62          32      a    a
6         230          64          33      a    a

정오분류표

> confusionMatrix(test$pred, test$breeds)
Error: `data` and `reference` should be factors with the same levels.

다음과 같은 오류가 발생한다. 왜일까?

> str(test)
'data.frame':	60 obs. of  5 variables:
 $ wing_length: int  258 260 251 248 254 230 248 250 235 241 ...
 $ tail_length: int  67 64 63 63 62 64 65 65 62 67 ...
 $ comb_height: int  32 34 31 30 32 33 35 33 35 30 ...
 $ breeds     : chr  "a" "a" "a" "a" ...
 $ pred       : Factor w/ 3 levels "a","b","c": 1 1 1 1 1 1 1 1 1 1 ...

breeds는 chr형이고, pred는 factor형이다.
breeds도 factor형으로 변환 후 다시 진행한다.

test$breeds <- as.factor(test$breeds)
> confusionMatrix(test$pred, test$breeds)
Confusion Matrix and Statistics

          Reference
Prediction  a  b  c
         a 20  1  0
         b  0 17  1
         c  0  2 19

Overall Statistics
                                         
               Accuracy : 0.9333         
                 95% CI : (0.838, 0.9815)
    No Information Rate : 0.3333         
    P-Value [Acc > NIR] : < 2.2e-16      
                                         
                  Kappa : 0.9            
                                         
 Mcnemar's Test P-Value : NA             

Statistics by Class:

                     Class: a Class: b Class: c
Sensitivity            1.0000   0.8500   0.9500
Specificity            0.9750   0.9750   0.9500
Pos Pred Value         0.9524   0.9444   0.9048
Neg Pred Value         1.0000   0.9286   0.9744
Prevalence             0.3333   0.3333   0.3333
Detection Rate         0.3333   0.2833   0.3167
Detection Prevalence   0.3500   0.3000   0.3500
Balanced Accuracy      0.9875   0.9125   0.9500
  • Accuracy : 0.9333

0개의 댓글