Business Case

Dataset ini adalah dataset tentang riwayat penyakit diabetes dari 768 pasien. Dalam kasus ini kita akan mengaplikasikan berbagai machine learning seperti naive bayes, decision tree, Random Forest

Library

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(e1071)
library(randomForest) 
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## Attaching package: 'randomForest'
## The following object is masked from 'package:dplyr':
## 
##     combine
library(caret)
## Loading required package: ggplot2
## 
## Attaching package: 'ggplot2'
## The following object is masked from 'package:randomForest':
## 
##     margin
## Loading required package: lattice
library(partykit)
## Loading required package: grid
## Loading required package: libcoin
## Loading required package: mvtnorm
library(rsample)
## 
## Attaching package: 'rsample'
## The following object is masked from 'package:e1071':
## 
##     permutations

Load Data

diab <- read.csv("data_input/diabetes.csv",stringsAsFactors = T)
head(diab, 5)

Data Pre-Processing

glimpse(diab)
## Rows: 768
## Columns: 9
## $ pregnant <int> 6, 1, 8, 1, 0, 5, 3, 10, 2, 8, 4, 10, 10, 1, 5, 7, 0, 7, 1, 1…
## $ glucose  <int> 148, 85, 183, 89, 137, 116, 78, 115, 197, 125, 110, 168, 139,…
## $ pressure <int> 72, 66, 64, 66, 40, 74, 50, 0, 70, 96, 92, 74, 80, 60, 72, 0,…
## $ triceps  <int> 35, 29, 0, 23, 35, 0, 32, 0, 45, 0, 0, 0, 0, 23, 19, 0, 47, 0…
## $ insulin  <int> 0, 0, 0, 94, 168, 0, 88, 0, 543, 0, 0, 0, 0, 846, 175, 0, 230…
## $ mass     <dbl> 33.6, 26.6, 23.3, 28.1, 43.1, 25.6, 31.0, 35.3, 30.5, 0.0, 37…
## $ pedigree <dbl> 0.627, 0.351, 0.672, 0.167, 2.288, 0.201, 0.248, 0.134, 0.158…
## $ age      <int> 50, 31, 32, 21, 33, 30, 26, 29, 53, 54, 30, 34, 57, 59, 51, 3…
## $ diabetes <fct> pos, neg, pos, neg, pos, neg, pos, neg, pos, pos, neg, pos, n…

Deskripsi data:

pregnant: Number of times pregnant

glucose: Plasma glucose concentration (glucose tolerance test)

pressure: Diastolic blood pressure (mm Hg)

triceps: Triceps skin fold thickness (mm)

insulin: 2-Hour serum insulin (mu U/ml)

mass: Body mass index (weight in kg/(height in m)^2)

pedigree: Diabetes pedigree function

age: Age (years)

diabetes: Test for Diabetes

Apakah data kita memiliki missing value atau tidak?

colSums(is.na(diab))
## pregnant  glucose pressure  triceps  insulin     mass pedigree      age 
##        0        0        0        0        0        0        0        0 
## diabetes 
##        0

Ternyata data kita tidak memiliki missing value

summary(diab)
##     pregnant         glucose         pressure         triceps     
##  Min.   : 0.000   Min.   :  0.0   Min.   :  0.00   Min.   : 0.00  
##  1st Qu.: 1.000   1st Qu.: 99.0   1st Qu.: 62.00   1st Qu.: 0.00  
##  Median : 3.000   Median :117.0   Median : 72.00   Median :23.00  
##  Mean   : 3.845   Mean   :120.9   Mean   : 69.11   Mean   :20.54  
##  3rd Qu.: 6.000   3rd Qu.:140.2   3rd Qu.: 80.00   3rd Qu.:32.00  
##  Max.   :17.000   Max.   :199.0   Max.   :122.00   Max.   :99.00  
##     insulin           mass          pedigree           age        diabetes 
##  Min.   :  0.0   Min.   : 0.00   Min.   :0.0780   Min.   :21.00   neg:500  
##  1st Qu.:  0.0   1st Qu.:27.30   1st Qu.:0.2437   1st Qu.:24.00   pos:268  
##  Median : 30.5   Median :32.00   Median :0.3725   Median :29.00            
##  Mean   : 79.8   Mean   :31.99   Mean   :0.4719   Mean   :33.24            
##  3rd Qu.:127.2   3rd Qu.:36.60   3rd Qu.:0.6262   3rd Qu.:41.00            
##  Max.   :846.0   Max.   :67.10   Max.   :2.4200   Max.   :81.00

Cross Validation

Pada split data kali ini kita akan membagi 2 data yaitu data_train dan data_test dimana 80% sebagai data_train dan 20% sebagai data_test

RNGkind(sample.kind = "Rounding")
## Warning in RNGkind(sample.kind = "Rounding"): non-uniform 'Rounding' sampler
## used
set.seed(100)

# your code here
index <- sample(nrow(diab), nrow(diab)*0.8)

diab_train <- diab[index,] # untuk pelatihan
diab_test <- diab[-index,]

Selanjutnya mari kita mengecek proporsi

prop.table(table(diab_train$diabetes))
## 
##       neg       pos 
## 0.6449511 0.3550489

proporsi tabel diatas menurut saya balance, oleh karena itu mari kita lanjutkan analisisnya O

Pembuatan Model

Setelah itu mari kita membuat sebuah model klasifikasi untuk membantu kita menyelesaikan masalah bisnis ini mari kita membuat 3 model yaitu : 1. Naive Bayes 2. Decision Tree 3. Random Forest

Naive Bayes

Selanjutnya mari kita membuat sebuah model yang pertama adalah model Naive Bayes

naive <- naiveBayes(diabetes~., diab_train, laplace = 1)
naive_label <- predict(naive, newdata = diab_test,type = "class")
confusionMatrix(data = naive_label, reference  = diab_test$diabetes, positive = "pos")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction neg pos
##        neg  83  22
##        pos  21  28
##                                         
##                Accuracy : 0.7208        
##                  95% CI : (0.6429, 0.79)
##     No Information Rate : 0.6753        
##     P-Value [Acc > NIR] : 0.131         
##                                         
##                   Kappa : 0.3599        
##                                         
##  Mcnemar's Test P-Value : 1.000         
##                                         
##             Sensitivity : 0.5600        
##             Specificity : 0.7981        
##          Pos Pred Value : 0.5714        
##          Neg Pred Value : 0.7905        
##              Prevalence : 0.3247        
##          Detection Rate : 0.1818        
##    Detection Prevalence : 0.3182        
##       Balanced Accuracy : 0.6790        
##                                         
##        'Positive' Class : pos           
## 

Hasil dari ConfusionMatrix menunjukkan bahwa model naive bayes ini memperkirakan bahwa ada 83 kasus yang termasuk orang sehat dengan benar dan terdapat 22 prediksi yang salah, Sedangkan Orang yang terkena diabetes terdapat 28 orang sedangkan terdapat 21 prediksi yang salah. Jika kita mengecek ternyata akurasi yang kita dapatkan sekitar 72%

Decision Tree

Setelah kita membuat model naive bayes, mari kita membuat model dengan decision tree, mengingat bahwa akurasi yang kita dapatkan sekitar 72% dan juga ada beberapa prediksi yang kurang tepat.

diab_tree <- ctree(formula = diabetes~., data=diab_train)
diab_tree
## 
## Model formula:
## diabetes ~ pregnant + glucose + pressure + triceps + insulin + 
##     mass + pedigree + age
## 
## Fitted party:
## [1] root
## |   [2] glucose <= 127
## |   |   [3] pregnant <= 4
## |   |   |   [4] mass <= 30.9
## |   |   |   |   [5] age <= 40: neg (n = 129, err = 1.6%)
## |   |   |   |   [6] age > 40: neg (n = 8, err = 50.0%)
## |   |   |   [7] mass > 30.9: neg (n = 130, err = 20.0%)
## |   |   [8] pregnant > 4
## |   |   |   [9] pedigree <= 0.878: neg (n = 108, err = 27.8%)
## |   |   |   [10] pedigree > 0.878: pos (n = 8, err = 12.5%)
## |   [11] glucose > 127
## |   |   [12] glucose <= 157
## |   |   |   [13] mass <= 29.9: neg (n = 44, err = 25.0%)
## |   |   |   [14] mass > 29.9: pos (n = 98, err = 36.7%)
## |   |   [15] glucose > 157: pos (n = 89, err = 14.6%)
## 
## Number of inner nodes:    7
## Number of terminal nodes: 8
# plot(diabetes_tree, type='simple')

Setelah itu mari kita lakukan prediksi dengan model kita

# prediksi kelas di data test
tree_label <- predict(diab_tree, diab_test, type="response")

# confusion matrix data test
confusionMatrix(tree_label, diab_test$diabetes, positive = "pos")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction neg pos
##        neg  85  25
##        pos  19  25
##                                          
##                Accuracy : 0.7143         
##                  95% CI : (0.636, 0.7841)
##     No Information Rate : 0.6753         
##     P-Value [Acc > NIR] : 0.1722         
##                                          
##                   Kappa : 0.3275         
##                                          
##  Mcnemar's Test P-Value : 0.4510         
##                                          
##             Sensitivity : 0.5000         
##             Specificity : 0.8173         
##          Pos Pred Value : 0.5682         
##          Neg Pred Value : 0.7727         
##              Prevalence : 0.3247         
##          Detection Rate : 0.1623         
##    Detection Prevalence : 0.2857         
##       Balanced Accuracy : 0.6587         
##                                          
##        'Positive' Class : pos            
## 

Ketika kita melihat dari confusion matrix, tingkat akurasi pada model decision tree ini mendapatkan akurasi sekitar 71.43%, yang mana jika kita mengingat bahwa model naive bayes malah memiliki nilai akurasi yang lebih besar sekitar 72%

Random Forest

Random Forest adalah salah satu jenis Ensemble Method yang terdiri dari banyak Decision Tree. Oleh karena itu mari kita coba membuat model dari random forest ini dengan k-fold cross validation dan set k-fold yang akan kita buat akan dilakukan 3 kali

# set.seed(100)
# ctrl <- trainControl(method="repeatedcv", number=5, repeats=3)
# 
# model_rforest <- train(diabetes~ ., data=diab_train, method="rf", trControl = ctrl)
# 
# saveRDS(model_rforest, file = "m_forest.rds")
fb_forest <- readRDS("m_forest.rds")
fb_forest
## Random Forest 
## 
## 614 samples
##   8 predictor
##   2 classes: 'neg', 'pos' 
## 
## No pre-processing
## Resampling: Cross-Validated (5 fold, repeated 3 times) 
## Summary of sample sizes: 491, 491, 492, 491, 491, 491, ... 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy   Kappa    
##   2     0.7671198  0.4755991
##   5     0.7627749  0.4693801
##   8     0.7606024  0.4637852
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.

Penjelasan dari random forest ini terdapat : 1. 614 samples pada data_train yang nanti akan kita gunakan dalam pembuatan model 2. 8 prediktor yang terdapat pada data_train kita 3. 2 classes yang akan kita jadikan sebagai variabel target

fb_forest$finalModel
## 
## Call:
##  randomForest(x = x, y = y, mtry = param$mtry) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 2
## 
##         OOB estimate of  error rate: 23.13%
## Confusion matrix:
##     neg pos class.error
## neg 338  58   0.1464646
## pos  84 134   0.3853211

Kita lihat prediktor mana saja yang penting digunakan dalam pembuatan model random forest ini

varImp(fb_forest)
## rf variable importance
## 
##          Overall
## glucose  100.000
## mass      43.641
## pedigree  28.609
## age       28.313
## pressure  10.682
## pregnant   6.930
## insulin    2.617
## triceps    0.000
predict_forest <- predict(fb_forest, diab_test)
confusionMatrix(predict_forest, diab_test$diabetes, positive = "pos")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction neg pos
##        neg  84  18
##        pos  20  32
##                                           
##                Accuracy : 0.7532          
##                  95% CI : (0.6774, 0.8191)
##     No Information Rate : 0.6753          
##     P-Value [Acc > NIR] : 0.02201         
##                                           
##                   Kappa : 0.4431          
##                                           
##  Mcnemar's Test P-Value : 0.87113         
##                                           
##             Sensitivity : 0.6400          
##             Specificity : 0.8077          
##          Pos Pred Value : 0.6154          
##          Neg Pred Value : 0.8235          
##              Prevalence : 0.3247          
##          Detection Rate : 0.2078          
##    Detection Prevalence : 0.3377          
##       Balanced Accuracy : 0.7238          
##                                           
##        'Positive' Class : pos             
## 

Dengan metode cross validation k-fold akurasi yang dihasilkan lebih baik yaitu sekitar 75%, jika kita membandingkan antara 2 model seperti decision tree dan naive bayes.

Selanjutnya mari kita coba random forest dengan menggunakan fungsi randomforest langsung

model_rf <- randomForest(diabetes ~ ., data = diab_train, importance=TRUE, 
                         ntree = 500)

model_rf
## 
## Call:
##  randomForest(formula = diabetes ~ ., data = diab_train, importance = TRUE,      ntree = 500) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 2
## 
##         OOB estimate of  error rate: 23.45%
## Confusion matrix:
##     neg pos class.error
## neg 339  57   0.1439394
## pos  87 131   0.3990826
pred <- predict(model_rf, diab_test) 
confusionMatrix(pred, diab_test$diabetes, positive = "pos")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction neg pos
##        neg  85  18
##        pos  19  32
##                                           
##                Accuracy : 0.7597          
##                  95% CI : (0.6844, 0.8248)
##     No Information Rate : 0.6753          
##     P-Value [Acc > NIR] : 0.01408         
##                                           
##                   Kappa : 0.4549          
##                                           
##  Mcnemar's Test P-Value : 1.00000         
##                                           
##             Sensitivity : 0.6400          
##             Specificity : 0.8173          
##          Pos Pred Value : 0.6275          
##          Neg Pred Value : 0.8252          
##              Prevalence : 0.3247          
##          Detection Rate : 0.2078          
##    Detection Prevalence : 0.3312          
##       Balanced Accuracy : 0.7287          
##                                           
##        'Positive' Class : pos             
## 

Ternyata akurasi yang dihasilkan bertambah menjadi 76%. dan juga prediksi yang dihasilkan sedikit demi sedikit mulai terlihat.

Balancing Data

Selanjutnya mari kita coba membuat 3 model dengan data yang akan kita balancing menjadi 50:50

down_diab <- downSample(x = diab_train %>% select(-diabetes), 
           y= diab_train$diabetes,  
           yname = "diabetes")
prop.table(table(down_diab$diabetes))
## 
## neg pos 
## 0.5 0.5

Naive bayes

naive1 <- naiveBayes(diabetes~., down_diab, laplace = 1)
naive_labelD <- predict(naive1, newdata = diab_test,type = "class")
confusionMatrix(data = naive_labelD, reference  = diab_test$diabetes, positive = "pos")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction neg pos
##        neg  74  20
##        pos  30  30
##                                           
##                Accuracy : 0.6753          
##                  95% CI : (0.5953, 0.7485)
##     No Information Rate : 0.6753          
##     P-Value [Acc > NIR] : 0.5382          
##                                           
##                   Kappa : 0.2962          
##                                           
##  Mcnemar's Test P-Value : 0.2031          
##                                           
##             Sensitivity : 0.6000          
##             Specificity : 0.7115          
##          Pos Pred Value : 0.5000          
##          Neg Pred Value : 0.7872          
##              Prevalence : 0.3247          
##          Detection Rate : 0.1948          
##    Detection Prevalence : 0.3896          
##       Balanced Accuracy : 0.6558          
##                                           
##        'Positive' Class : pos             
## 

Decision Tree

diab_tree1 <- ctree(formula = diabetes~., data=down_diab)
# prediksi kelas di data test
tree_label1 <- predict(diab_tree1, diab_test, type="response")

# confusion matrix data test
confusionMatrix(tree_label1, diab_test$diabetes, positive = "pos")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction neg pos
##        neg  90  29
##        pos  14  21
##                                         
##                Accuracy : 0.7208        
##                  95% CI : (0.6429, 0.79)
##     No Information Rate : 0.6753        
##     P-Value [Acc > NIR] : 0.13103       
##                                         
##                   Kappa : 0.3095        
##                                         
##  Mcnemar's Test P-Value : 0.03276       
##                                         
##             Sensitivity : 0.4200        
##             Specificity : 0.8654        
##          Pos Pred Value : 0.6000        
##          Neg Pred Value : 0.7563        
##              Prevalence : 0.3247        
##          Detection Rate : 0.1364        
##    Detection Prevalence : 0.2273        
##       Balanced Accuracy : 0.6427        
##                                         
##        'Positive' Class : pos           
## 

Random Forest

model_rf1 <- randomForest(diabetes ~ ., data = down_diab, importance=TRUE, 
                         ntree = 500)

model_rf1
## 
## Call:
##  randomForest(formula = diabetes ~ ., data = down_diab, importance = TRUE,      ntree = 500) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 2
## 
##         OOB estimate of  error rate: 24.54%
## Confusion matrix:
##     neg pos class.error
## neg 165  53   0.2431193
## pos  54 164   0.2477064
pred1 <- predict(model_rf1, diab_test) 
confusionMatrix(pred1, diab_test$diabetes,positive = "pos")
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction neg pos
##        neg  75   9
##        pos  29  41
##                                           
##                Accuracy : 0.7532          
##                  95% CI : (0.6774, 0.8191)
##     No Information Rate : 0.6753          
##     P-Value [Acc > NIR] : 0.022011        
##                                           
##                   Kappa : 0.4902          
##                                           
##  Mcnemar's Test P-Value : 0.002055        
##                                           
##             Sensitivity : 0.8200          
##             Specificity : 0.7212          
##          Pos Pred Value : 0.5857          
##          Neg Pred Value : 0.8929          
##              Prevalence : 0.3247          
##          Detection Rate : 0.2662          
##    Detection Prevalence : 0.4545          
##       Balanced Accuracy : 0.7706          
##                                           
##        'Positive' Class : pos             
## 

Kesimpulan

Ketika kita membandingkan keseluruhan model tentunya model Random Forest memiliki nilai akurasi dan recall yang terbaik diantara model yang lain dengan catatan Data yang digunakan bukan data yang setelah diupsampling. Ada beberapa variabel yang sangat mempengaruhi diabetes seperti glucose, mass, pedigre, dan yang lain. Pada kasus ini metrics yang saya perhatikan adalah metriks recall dikarenakan jika pasien tersebut sehat tapi pada saat dideteksi positif maka akan diarahkan untuk konsultasi, supaya kita bisa meminimalisir orang yang terkena diabetes supaya tidak semakin berbahaya.