Pengantar Data Sains

UAS


Kontak : \(\downarrow\)
Email
Instagram https://www.instagram.com/arifin.alicia/
RPubs https://rpubs.com/aliciaarifin/
Nama Alicia Arifin
NIM 20214920001
Prodi Statistika, 2021

Ujian Akhir Semester Pengantar Data Sains

Kelompok 1 :
1. Alicia Arifin
2. Diyas Arya Nugroho
3. Dhela Asafiani Agatha

Problem

Pak Bakti telah memulai perusahaan selulernya sendiri. Pak Bakti ingin memperluas pasar perdagannya dan bercita-cita untuk dapat bersaing dengan besar seperti Apple, Samsung, dll. Tetapi Dia tidak tahu bagaimana memperkirakan harga ponsel yang sesuai untuk setiap produk yang dibuat perusahaannya. Oleh karena itu, perusahaan Pak Bakti bermaksud untuk melakukan analisis berdasarkan data penjualan ponsel dari berbagai perusahaan.

Soal

  1. Lakukan Analisis Deskriptive untuk mendapatkan beberapa informasi penting dari data tersebut!
  2. Buatlah Model Data Science yang sudah kalian pelajari untuk mengetahui beberapa hubungan antara fitur ponsel (misalnya: - RAM, Memori Internal dll) dan harga jualnya!
  3. Buatlah perbandingan prediksi harga ponsel menggunakan Regression, Decision Tree, dan Random Forest!
  4. Lakukan proses Cross Validation dan Fine Tune untuk menemukan model terbaik.

library & keterangan kolom

library(tidyverse)
library(tidymodels)
library(gridExtra)
library(Hmisc)
library(corrplot)
library(ggplot2)
library(PerformanceAnalytics)
library(ggcorrplot)
library(parallel)
library(caret)
library(doSNOW)
library(ggplot2)
library(GGally)
library(rpart)
library(randomForest)
library(DT)
library(rpart.plot)
library(rpart)
library(rattle)
library(caret)
library(doSNOW)
library(parallel)
library(doSNOW)

battery_power: total energy a battery can store in one time measured in mAh
blue: has bluetooth or not
clock_speed: speed at which microprocessor executes instructions
dual_sim: support dual sim or not
fc: front camera megapixel
four_g: support 4G or not
int_memory: Internal Memory in Gigabytes
m_dep: Mobile Depth in cm
mobile_wt: weight of mobile phone
n_cores: number of core processor
pc: primary camera megapixels
px_weight: pixel resolution height
px_width: pixel resolution width
ram: random access memory in megabytes
sc_h: screen height of mobile in cm
sc_w: screen width of mobile in cm
talk_time: longest time that a single battery charge will last when you are on call
three_g: support 3G or not
touch_screen: has touch screen or not
wifi: has wifi or not
price_range: this is the target variable with value of 0(low cost), 1(medium cost), 2(high cost) and 3(very high cost).

Jawaban

1

Lakukan Analisis Deskriptive untuk mendapatkan beberapa informasi penting dari data tersebut!

setwd(getwd())
train = read.csv("train.csv")
test  = read.csv("test.csv")

datatable(train) # data train
datatable(test) # data test
chart.Correlation(train, histogram = F)

ggcorr(train,label = T, size=3, label_size = 3, hjust=0.95,palette="RdGy",
       layout.exp = 3)+
  labs(
    title=""
  )+
  theme_minimal()+
  theme(
    plot.title = element_text(hjust = 0.5),
    axis.title=element_text(size=8,face="bold"), 
    axis.text.y=element_blank()
  )

Note : Untuk menyelesaikan masalah ini, langkah pertama yang perlu kita lakukan adalah mengimport data train dan data test nya. Nah, untuk mengetahui apakah data yang kita import memiliki korelasi atau tidak, kita perlu untuk memplot data tersebut. Kita perlu memerlukan library ggplot2 dan juga GGally.
Setelah kita plot, bisa kita beberapa variable dari plot tersebut memiliki korelasi atau saling mempengaruhi. Akan tetapi, pada kasus ini kita ingin mengetahui prediksi dari price_range nya. Jadi, kita hanya perlu fokus pada variable apa saja yang berkolerasi dan memiliki pengaruh terhadap price_range.
Bisa kita lihat, variable ram, px_width, px_height, dan battery_power memiliki korelasi terhadap price range nya. Sedangkan yang lain memiliki korelasi yang lemah. Jadi, bisa kita simpulkan bahwa 4 variable tersebut memiliki korelasi terhadap price range berdasarkan plot korelasi yang kita buat.

2

Buatlah Model Data Science yang sudah kalian pelajari untuk mengetahui beberapa hubungan antara fitur ponsel (misalnya: - RAM, Memori Internal dll) dan harga jualnya!
Dari hasil korelasi, di dapat ada 4 variabel (ram, px_width, px_height dan battery_power) dependence yang memiliki hubungan yang kuat dengan variabel independece (price_range). Akan tetapi untuk memastikan lagi model tersebut adalah yang terbaik, kita lakukan uji regresi untuk mengetahui jika kita menggunakan variabel itu udh cocok atau belum atau masih ada variabel tambahan yang berhubungan?

names <- lm(data =train, price_range ~ .)
names1 <- lm(data =train, price_range ~battery_power+int_memory +mobile_wt +px_height +px_width + ram )
names2 <- lm(data =train, price_range ~battery_power +mobile_wt +px_height +px_width + ram )
names3 <- lm(data =train, price_range ~blue +clock_speed+dual_sim+fc+four_g+m_dep+n_cores+pc+sc_h +sc_w+talk_time+three_g+touch_screen+wifi     )            

models = data.frame("model" = c("price_range ~ .",
                           "price_range ~battery_power +mobile_wt +px_height +px_width + ram",
                           "price_range ~battery_power+int_memory +mobile_wt +px_height +px_width + ram",
                           "price_range ~blue +clock_speed+dual_sim+fc+four_g+m_dep+n_cores+pc+sc_h +sc_w+talk_time+three_g+touch_screen+wifi"),
                    "adjR2"= c(summary(names)$adj, summary(names2)$adj, summary(names1)$adj,summary(names3)$adj))
models

Ada 4 model pengujiannya
1. Independence (price_range) dan Dependence (semua variabel kecuali price_range).
2. Independence (price_range) dan Dependence (battery_power +mobile_wt +px_height +px_width + ram).
3. Independence (price_range) dan Dependence (battery_power+int_memory +mobile_wt +px_height +px_width + ram).
4. Independence (price_range) dan Dependence (blue +clock_speed+dual_sim+fc+four_g+m_dep+n_cores+pc+sc_h +sc_w+talk_time+three_g+touch_screen+wifi).

Setelah melakukan uji regresi, kita gunakan R adjusted yang paling tinggi untuk menentukan model terbaiknya.Maka, kita simpulkan bawha model terbaik yang digunakan adalah names1 yaitu price_range ~battery_power+int_memory +mobile_wt +px_height +px_width + ram .

summary(names1)
## 
## Call:
## lm(formula = price_range ~ battery_power + int_memory + mobile_wt + 
##     px_height + px_width + ram, data = train)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.01985 -0.25167  0.00551  0.24740  0.81025 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   -1.575e+00  4.559e-02 -34.552  < 2e-16 ***
## battery_power  5.108e-04  1.631e-05  31.315  < 2e-16 ***
## int_memory     8.570e-04  3.954e-04   2.167   0.0303 *  
## mobile_wt     -8.826e-04  2.025e-04  -4.358 1.38e-05 ***
## px_height      2.753e-04  1.879e-05  14.650  < 2e-16 ***
## px_width       2.796e-04  1.929e-05  14.493  < 2e-16 ***
## ram            9.469e-04  6.612e-06 143.206  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3204 on 1993 degrees of freedom
## Multiple R-squared:  0.9182, Adjusted R-squared:  0.9179 
## F-statistic:  3727 on 6 and 1993 DF,  p-value: < 2.2e-16
reg_hape = function(battery_power, int_memory  ,  mobile_wt   ,  px_height   ,  px_width    ,  ram    )
{
  hoot = -1.575e+00  + battery_power*  5.108e-04  + int_memory*8.570e-04  + mobile_wt    * -8.826e-04  + px_height    *  2.753e-04  + px_width     *  2.796e-04  + ram* 9.469e-04 
  
  paste(cat("price range hape dengan battery power",battery_power, "internal memori", int_memory,"berat", mobile_wt, "dengan pixel", px_height, "x",px_width, "dan ram",ram, "adalah",hoot))
}

Setelah mendapatkan model yang terbaik, kita cari apakah variabel pada model tersebut memiliki hubungan? Dari output summary(names1) di dapat nilai p-value modelnya adalah < 2.2e-16 yang dimana nilai p-value itu lebih kecil dari a (tingkat signifikansi) = 0,05. Maka, dapat disimpulkan bahwa model tersebut memiliki variabel yang saling berhubungan.

3

Buatlah perbandingan prediksi harga ponsel menggunakan Regression, Decision Tree, dan Random Forest!
Dari soal nomor 1 dan 2, kita sudah menentukan variabel apa saja yang berpengaruh terhadap price range. variabel-variabel tersebut adalah battery_power, int_memory , mobile_wt , px_height , px_width , dan ram. Lalu, kita akan membuat model berdasarkan train dataset, lalu mengaplikasikan ke test dataset.

Regression

Selain cara membuat model regresi seperti nomor 2, kita juga bisa membuatnya dengan cara lain dengan membangun spec, recipe, dan fit. Pada cara 1, kita menggunakan for untuk memasukkan hasil prediksi ke dataset hello yang isinya sudah di pilih sesuai keenam variabel yang berpengaruh terhadap price range.

# cara 1
hello = test%>%
  select(battery_power, int_memory  ,  mobile_wt   ,  px_height   ,  px_width    ,  ram )
hello$predictR <- NA

for (i in 1: nrow(hello)){
  hello$predictR[i] <- round(-1.575e+00  + hello$battery_power[i] *  5.108e-04  + hello$int_memory[i] *8.570e-04  + hello$mobile_wt[i]     * -8.826e-04  + hello$px_height [i]    *  2.753e-04  + hello$px_width[i]      *  2.796e-04  + hello$ram[i] * 9.469e-04 )}
hello
## yg lebih ribet
lm_spec <- linear_reg() |>
  set_engine("lm") |>
  set_mode("regression")

lm_recipe <- recipe(price_range ~ battery_power + int_memory + mobile_wt + 
    px_height + px_width + ram, data = train)

lm_fit <- workflow()|>
  add_recipe(lm_recipe)|>
  add_model(lm_spec)|>
  fit(data= train)

lm_fit
## == Workflow [trained] ==========================================================
## Preprocessor: Recipe
## Model: linear_reg()
## 
## -- Preprocessor ----------------------------------------------------------------
## 0 Recipe Steps
## 
## -- Model -----------------------------------------------------------------------
## 
## Call:
## stats::lm(formula = ..y ~ ., data = data)
## 
## Coefficients:
##   (Intercept)  battery_power     int_memory      mobile_wt      px_height  
##    -1.5751895      0.0005108      0.0008570     -0.0008826      0.0002753  
##      px_width            ram  
##     0.0002796      0.0009469

Persamaan regresi yang kita dapat adalah price_range = -1.575189 + battery_power* 0.000511 + int_memory*0.000857 + mobile_wt * -0.000883 + px_height * 0.000275 + px_width * 0.000280 + ram * .000947. Pada cara 1, kita juga sudah measukkan semua data ke kolom predictR dengan predict$R <- NA. kita menggunakan NA agar datanya bisa dimasukkan ke fungsi for.

Decision Tree

Kita membuat model decision tree menggunakan rpart(). Kita akan memprediksi hasil dari model menggunakanpredict. Setelah itu, kita bandingkan dengan data price_range aslinya yang berasal dari data train.

# model
modelDT <- rpart(price_range ~ battery_power + int_memory + mobile_wt + 
    px_height + px_width + ram, data = train, method ="class")

options(digits=4)

Predict_modelDT <- predict(modelDT, train, type = "class")

conMatDT <- confusionMatrix(as.factor(Predict_modelDT), as.factor(train$price_range))

conMatDT$table
##           Reference
## Prediction   0   1   2   3
##          0 477  70   0   0
##          1  23 365  58   0
##          2   0  65 354  68
##          3   0   0  88 432
conMatDT$overall["Accuracy"]
## Accuracy 
##    0.814

Setelah kita bandingkan hasil prediksi dengan data aslinya, hasil prediksi yang didapat adalah 81.4%. Lalu, pada coding di bawah ini, kita menggunakan model tersebut untuk di masukkan prediksi decision tree kedalam dataset hello.

predictDT <- predict(modelDT, test, type = "class")
hello$predictDT = predictDT
datatable(hello)

Random Forest

Langkah untuk membuat model random forest diawali dengan membuat variabel independen atau variabel yang ingin dicari (Y) menjadi factor. Lalu, kita menggunakan randomForest untuk membuat model random forest. Pada model ini, ntree dan mtry sudah dipilihkan secara otomatis oleh package tersebut.

train$price_range <- as.factor(train$price_range)

modelRF <- randomForest(price_range ~ battery_power + int_memory + mobile_wt + 
    px_height + px_width + ram, data = train, importance = T)
modelRF
## 
## Call:
##  randomForest(formula = price_range ~ battery_power + int_memory +      mobile_wt + px_height + px_width + ram, data = train, importance = T) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 2
## 
##         OOB estimate of  error rate: 7.95%
## Confusion matrix:
##     0   1   2   3 class.error
## 0 477  23   0   0       0.046
## 1  23 455  22   0       0.090
## 2   0  33 440  27       0.120
## 3   0   0  31 469       0.062

Dari hasil model di atas, ntree, dan mtry yang terpilih adalah mtry = 2 dan ntree = 500. Pada random forest ini ada 500 pohon yang dibuat, dan split menjadi 2. Model random forest ini memiliki overall akurasi 91.3% (100-8,7), estimasi error OOB nya adalah 8.7%

# prediksi dengan train dataset
RF_predict <- predict(modelRF, train)
conMatRF <- confusionMatrix(RF_predict, train$price_range)
conMatRF
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   0   1   2   3
##          0 500   0   0   0
##          1   0 500   0   0
##          2   0   0 500   0
##          3   0   0   0 500
## 
## Overall Statistics
##                                     
##                Accuracy : 1         
##                  95% CI : (0.998, 1)
##     No Information Rate : 0.25      
##     P-Value [Acc > NIR] : <2e-16    
##                                     
##                   Kappa : 1         
##                                     
##  Mcnemar's Test P-Value : NA        
## 
## Statistics by Class:
## 
##                      Class: 0 Class: 1 Class: 2 Class: 3
## Sensitivity              1.00     1.00     1.00     1.00
## Specificity              1.00     1.00     1.00     1.00
## Pos Pred Value           1.00     1.00     1.00     1.00
## Neg Pred Value           1.00     1.00     1.00     1.00
## Prevalence               0.25     0.25     0.25     0.25
## Detection Rate           0.25     0.25     0.25     0.25
## Detection Prevalence     0.25     0.25     0.25     0.25
## Balanced Accuracy        1.00     1.00     1.00     1.00

Setelah kita bandingkan dengan hasil prediksi dengan data train, model kita mempunyai akurasi 100% atau tidak ada error, pada data train. Setelah itu kita prediksi pada data test.

RF_prediction <- predict(modelRF, test)
hello$preictRF<- RF_prediction

Hasil

hello$predictR = as.factor(hello$predictR)
datatable(hello) 
summary(hello)
##  battery_power    int_memory     mobile_wt     px_height       px_width   
##  Min.   : 500   Min.   : 2.0   Min.   : 80   Min.   :   0   Min.   : 501  
##  1st Qu.: 895   1st Qu.:18.0   1st Qu.:110   1st Qu.: 264   1st Qu.: 832  
##  Median :1246   Median :34.5   Median :139   Median : 564   Median :1250  
##  Mean   :1248   Mean   :33.6   Mean   :140   Mean   : 627   Mean   :1240  
##  3rd Qu.:1629   3rd Qu.:49.0   3rd Qu.:170   3rd Qu.: 903   3rd Qu.:1638  
##  Max.   :1999   Max.   :64.0   Max.   :200   Max.   :1907   Max.   :1998  
##       ram       predictR predictDT preictRF
##  Min.   : 263   -1: 11   0:269     0:256   
##  1st Qu.:1237   0 :210   1:223     1:231   
##  Median :2154   1 :264   2:246     2:253   
##  Mean   :2139   2 :290   3:262     3:260   
##  3rd Qu.:3066   3 :217                     
##  Max.   :3989   4 :  8

Dari hasil regresi, decision tree, dan random forest, akurasi yang paling tinggi merupakan metode random forest. Pada hasil random forest, price_range yang paling dominan ada di range 3 atau yang paling mahal. Apakah hasil semua model di atas ini merupakan model yang terbaik? Untuk memastikan lebih lanjut, kita bisa gunakan cross-validation dan fine tune untuk menentukan model terbaik.

4

Lakukan proses Cross Validation dan Fine Tune untuk menemukan model terbaik.

Cross Validation

Cross-validation (CV) adalah metode statistik yang dapat digunakan untuk mengevaluasi kinerja model atau algoritma dimana data dipisahkan menjadi dua subset yaitu data proses pembelajaran dan data validasi / evaluasi. Model atau algoritma dilatih oleh subset pembelajaran dan divalidasi oleh subset validasi. Selanjutnya pemilihan jenis CV dapat didasarkan pada ukuran dataset. Biasanya CV K-fold digunakan karena dapat mengurangi waktu komputasi dengan tetap menjaga keakuratan estimasi.
Terdapat metode pada langkah cross validation, seperti contoh nya dengan metode decision tree dan random forest. Nah, pada kali ini kita akan menggunakan cross validation untuk mengolah data lebih akurat.

Decition Tree 6 Predictor

#setup model's train and valid dataset
set.seed(1000)
samp <- sample(nrow(train), 0.8 * nrow(train))
trainData <- train[samp, ]
validData <- train[-samp, ]

# set random for reproduction
set.seed(3214)
# specify parameters for cross validation
control <- trainControl(method = "repeatedcv", 
                        number = 10, # number of folds
                        repeats = 5, # repeat times
                        search = "grid")

Pada tahap ini, untuk mengawali pengujian silang kita perlu memanggil library caret, rpart, rpart.plot. Pertama kita membagi data train menjadi trainData dan validData. Setelah itu, kita perlu men-set parameter nya secara spesifik untuk uji silang ini. Disini kita melakukan set berupa jumlah lipatannya, pengulangan nya, dan metode yang digunakan. Kita menggunakan fungsi trainControl.

set.seed(1010)
# Create model from cross validation train data
cl <- makeCluster(6, type = "SOCK")
registerDoSNOW(cl)

Tree_model2_cv <- train(price_range ~battery_power+int_memory +mobile_wt +px_height +px_width + ram, 
                        data =trainData,
                      method = "rpart",
                    trControl = control)
 # Due to the computation cost once a model is trained. 
# # it is better to save it and load later rather than compute a gain
# save(Tree_model2_cv, file = "./data/Tree_model2_cv.rda")

stopCluster(cl)
print.train(Tree_model2_cv)
## CART 
## 
## 1600 samples
##    6 predictor
##    4 classes: '0', '1', '2', '3' 
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold, repeated 5 times) 
## Summary of sample sizes: 1439, 1441, 1439, 1439, 1441, 1441, ... 
## Resampling results across tuning parameters:
## 
##   cp      Accuracy  Kappa 
##   0.1595  0.7128    0.6169
##   0.1889  0.5507    0.3985
##   0.3392  0.4061    0.2037
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was cp = 0.1595.

Setelah itu, kita akan melakukan validasi silang dengan 6 prediktor. Prediktor tersebut adalah battery_power, int_memory, mobile_wt, px_height,px_width dan ram. Kita menggunakan metode rpart untuk decision tree.

model_accuracy <- format(Tree_model2_cv$results$Accuracy[1], digits = 4)
paste("Estimated accuracy:", model_accuracy)
## [1] "Estimated accuracy: 0.7128"

Setelah itu, kita mencari estimasi akurasi nya.

#Visualize cross validation tree

plot.train(Tree_model2_cv)

Pada tahap ini kita memplot data train nya dalam bentuk cross validation tree.

predict_train <-predict(Tree_model2_cv, train)
conMat <- confusionMatrix(predict_train, train$price_range)
conMat$table
##           Reference
## Prediction   0   1   2   3
##          0 406  54   0   0
##          1  94 384 107   0
##          2   0   0   0   0
##          3   0  62 393 500

Pada tahap ini, kita ingin mencari akurasi dari trainData nya. Kita menggunakan function predict untuk memprediksi dan confusionMatrix untuk mencari akurasi nya.

predict_train_accuracy <- format(conMat$overall["Accuracy"], digits=4)
paste("trainData Accuracy:", predict_train_accuracy)
## [1] "trainData Accuracy: 0.645"

Terdapat akurasi dari trainData

plot.train(Tree_model2_cv)

# prediction's Confusion Matrix on the validData
predict_valid <-predict(Tree_model2_cv, validData)
conMat <- confusionMatrix(predict_valid, validData$price_range)
conMat$table
##           Reference
## Prediction  0  1  2  3
##          0 72  8  0  0
##          1 19 84 28  0
##          2  0  0  0  0
##          3  0 18 75 96

Pda tahap ini, kita ingin mencari akurasi dari validData nya. Kita menggunakan function predict untuk memprediksi dan confusionMatrix untuk mencari akurasi nya.

predict_valid_accuracy <- format(conMat$overall["Accuracy"], digits=4)
paste("validData Accuracy:", predict_valid_accuracy)
## [1] "validData Accuracy: 0.63"

Terdapat akurasi dari validData

P_testDT <- predict(Tree_model2_cv,test)
hello$P_testDT <- P_testDT


conMat <- confusionMatrix(P_testDT, hello$P_testDT)
conMat
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   0   1   2   3
##          0 225   0   0   0
##          1   0 296   0   0
##          2   0   0   0   0
##          3   0   0   0 479
## 
## Overall Statistics
##                                     
##                Accuracy : 1         
##                  95% CI : (0.996, 1)
##     No Information Rate : 0.479     
##     P-Value [Acc > NIR] : <2e-16    
##                                     
##                   Kappa : 1         
##                                     
##  Mcnemar's Test P-Value : NA        
## 
## Statistics by Class:
## 
##                      Class: 0 Class: 1 Class: 2 Class: 3
## Sensitivity             1.000    1.000       NA    1.000
## Specificity             1.000    1.000        1    1.000
## Pos Pred Value          1.000    1.000       NA    1.000
## Neg Pred Value          1.000    1.000       NA    1.000
## Prevalence              0.225    0.296        0    0.479
## Detection Rate          0.225    0.296        0    0.479
## Detection Prevalence    0.225    0.296        0    0.479
## Balanced Accuracy       1.000    1.000       NA    1.000
## test accuracy 1

Terakhir, kita ingin mencari akurasi dari data test nya.

printcp(modelDT)
## 
## Classification tree:
## rpart(formula = price_range ~ battery_power + int_memory + mobile_wt + 
##     px_height + px_width + ram, data = train, method = "class")
## 
## Variables actually used in tree construction:
## [1] battery_power px_width      ram          
## 
## Root node error: 1500/2000 = 0.75
## 
## n= 2000 
## 
##      CP nsplit rel error xerror  xstd
## 1 0.333      0      1.00   1.05 0.012
## 2 0.194      1      0.67   0.67 0.015
## 3 0.158      2      0.47   0.47 0.014
## 4 0.018      3      0.31   0.33 0.013
## 5 0.012      6      0.26   0.28 0.012
## 6 0.010      7      0.25   0.28 0.012
plotcp(modelDT)

Note :

# accumulate model's accuracy
name <- c("Esti Accu", "Train Accu", "Valid Accu", "Test Accu")
Tree_model2_CV_accuracy <- c(model_accuracy, predict_train_accuracy, predict_valid_accuracy, 1)
names(Tree_model2_CV_accuracy) <- name
Tree_model2_CV_accuracy
##  Esti Accu Train Accu Valid Accu  Test Accu 
##   "0.7128"    "0.645"     "0.63"        "1"

Terdapat hasil akurasi nya

ptree<- prune(modelDT,
 cp= modelDT$cptable[which.min(modelDT$cptable[,"xerror"]),"CP"])
fancyRpartPlot(ptree, uniform=TRUE, main="Pruned Classification Tree")

Decition Tree 5 Predictor

set.seed(1010)
# Create model from cross validation train data
cl <- makeCluster(6, type = "SOCK")
registerDoSNOW(cl)
Tree_model3_cv <- train(price_range ~battery_power +mobile_wt +px_height +px_width + ram, 
                        data =trainData,
                      method = "rpart",
                    trControl = control)

stopCluster(cl)
print.train(Tree_model3_cv)
## CART 
## 
## 1600 samples
##    5 predictor
##    4 classes: '0', '1', '2', '3' 
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold, repeated 5 times) 
## Summary of sample sizes: 1439, 1441, 1439, 1439, 1441, 1441, ... 
## Resampling results across tuning parameters:
## 
##   cp      Accuracy  Kappa 
##   0.1595  0.7128    0.6169
##   0.1889  0.5507    0.3985
##   0.3392  0.4061    0.2037
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was cp = 0.1595.

Setelah itu, kita akan melakukan validasi silang dengan 6 prediktor. Prediktor tersebut adalah battery_power, mobile_wt, px_height,px_width dan ram. Kita menggunakan metode rpart untuk decision tree. Kita ingin melihat apakah terdapat perbedaan yang signifikan atau justru hanya berbeda sedikit antara 6 prediktor dan 5 prediktor. Kita membuat model uji validasi silang model 2.

model_accuracy <- format(Tree_model3_cv$results$Accuracy[1], digits = 4)
paste("Estimated accuracy:", model_accuracy)
## [1] "Estimated accuracy: 0.7128"

Terdapat estimasi akurasi nya.

#Visualize cross validation tree
plot.train(Tree_model3_cv)

predict_train <-predict(Tree_model3_cv, train)
conMat <- confusionMatrix(predict_train, train$price_range)
conMat$table
##           Reference
## Prediction   0   1   2   3
##          0 406  54   0   0
##          1  94 384 107   0
##          2   0   0   0   0
##          3   0  62 393 500

Pada tahap ini, kita ingin mencari akurasi dari trainData nya. Kita menggunakan function predict untuk memprediksi dan confusionMatrix untuk mencari akurasi nya.

predict_train_accuracy <- format(conMat$overall["Accuracy"], digits=4)
paste("trainData Accuracy:", predict_train_accuracy)
## [1] "trainData Accuracy: 0.645"

Terdapat akurasi dari trainData nya.

plot.train(Tree_model3_cv)

# prediction's Confusion Matrix on the validData
predict_valid <-predict(Tree_model3_cv, validData)
conMat <- confusionMatrix(predict_valid, validData$price_range)
conMat$table
##           Reference
## Prediction  0  1  2  3
##          0 72  8  0  0
##          1 19 84 28  0
##          2  0  0  0  0
##          3  0 18 75 96

Pada tahap ini, kita ingin mencari akurasi dari validData nya. Kita menggunakan function predict untuk memprediksi dan confusionMatrix untuk mencari akurasi nya.

predict_valid_accuracy <- format(conMat$overall["Accuracy"], digits=4)
paste("validData Accuracy:", predict_valid_accuracy)
## [1] "validData Accuracy: 0.63"
P_testDT <- predict(Tree_model2_cv,test)
hello$P_testDT <- P_testDT


conMat <- confusionMatrix(P_testDT, hello$P_testDT)
conMat$table
##           Reference
## Prediction   0   1   2   3
##          0 225   0   0   0
##          1   0 296   0   0
##          2   0   0   0   0
##          3   0   0   0 479
## test accuracy 1
printcp(modelDT)
## 
## Classification tree:
## rpart(formula = price_range ~ battery_power + int_memory + mobile_wt + 
##     px_height + px_width + ram, data = train, method = "class")
## 
## Variables actually used in tree construction:
## [1] battery_power px_width      ram          
## 
## Root node error: 1500/2000 = 0.75
## 
## n= 2000 
## 
##      CP nsplit rel error xerror  xstd
## 1 0.333      0      1.00   1.05 0.012
## 2 0.194      1      0.67   0.67 0.015
## 3 0.158      2      0.47   0.47 0.014
## 4 0.018      3      0.31   0.33 0.013
## 5 0.012      6      0.26   0.28 0.012
## 6 0.010      7      0.25   0.28 0.012
plotcp(modelDT)

# accumulate model's accuracy
name <- c("Esti Accu", "Train Accu", "Valid Accu", "Test Accu")
Tree_model2_CV_accuracy <- c(model_accuracy, predict_train_accuracy, predict_valid_accuracy, 1)
names(Tree_model2_CV_accuracy) <- name
Tree_model2_CV_accuracy
##  Esti Accu Train Accu Valid Accu  Test Accu 
##   "0.7128"    "0.645"     "0.63"        "1"

Dan dapat kita lihat ke 4 hasil akurasi yang telah kita cari akurasi nya tadi.

ptree<- prune(modelDT,
 cp= modelDT$cptable[which.min(modelDT$cptable[,"xerror"]),"CP"])
fancyRpartPlot(ptree, uniform=TRUE, main="Pruned Classification Tree")

Random Forest 6 Predictor

# set seed for reproduction
set.seed(2307)
cl <- makeCluster(6, type = "SOCK")
registerDoSNOW(cl)

RF_model1_cv <- train(price_range ~battery_power+int_memory +mobile_wt +px_height +px_width + ram, 
                        data =train,
                       method = "rf",
                       trControl = control)
stopCluster(cl)
# Show CV mdoel's details
print(RF_model1_cv)
## Random Forest 
## 
## 2000 samples
##    6 predictor
##    4 classes: '0', '1', '2', '3' 
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold, repeated 5 times) 
## Summary of sample sizes: 1800, 1800, 1800, 1800, 1800, 1800, ... 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy  Kappa 
##   2     0.9147    0.8863
##   4     0.9106    0.8808
##   6     0.9009    0.8679
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.

Pada tahap ini, kita melakukan uji silang dengan metode Random Forest dengan 6 prediktor. Kita menggunakan 6 prediktor yang sama dengan desicion tree tadi. Hanya saja ketika kita melakukan coding ini, kita menggunakan metode rf untuk random forest.

# Record model's accuracy
model_accuracy <- format(RF_model1_cv$results$Accuracy[2], digits = 4)
paste("Estimated accuracy:", model_accuracy)
## [1] "Estimated accuracy: 0.9106"

Terdapat hasil dari estimasi akurasi nya

### Access accuracy on different datasets
# prediction's Confusion Matrix on the trainData 
predict_train <-predict(RF_model1_cv, trainData)
conMat <- confusionMatrix(predict_train, trainData$price_range)
conMat$table
##           Reference
## Prediction   0   1   2   3
##          0 409   0   0   0
##          1   0 390   0   0
##          2   0   0 397   0
##          3   0   0   0 404

Pada tahap ini, kita ingin mencari akurasi dari trainData nya. Kita menggunakan function predict untuk memprediksi dan confusionMatrix untuk mencari akurasi nya.

# prediction's Accuracy on the trainData 
predict_train_accuracy <- format(conMat$overall["Accuracy"], digits=4)
paste("trainData Accuracy:", predict_train_accuracy)
## [1] "trainData Accuracy: 1"
# prediction's Confusion Matrix on the validData
predict_valid <-predict(RF_model1_cv, validData)
conMat <- confusionMatrix(predict_valid, validData$price_range)
conMat$table
##           Reference
## Prediction   0   1   2   3
##          0  91   0   0   0
##          1   0 110   0   0
##          2   0   0 103   0
##          3   0   0   0  96

Pada tahap ini, kita ingin mencari akurasi dari validData nya. Kita menggunakan function predict untuk memprediksi dan confusionMatrix untuk mencari akurasi nya

# prediction's Accuracy on the validData 
predict_valid_accuracy <- format(conMat$overall["Accuracy"], digits=4)
paste("validData Accuracy:", predict_valid_accuracy)
## [1] "validData Accuracy: 1"
P_test <- predict(RF_model1_cv,test)
hello$P_test <- P_test


conMat <- confusionMatrix(P_test, hello$P_test)
conMat$table
##           Reference
## Prediction   0   1   2   3
##          0 256   0   0   0
##          1   0 231   0   0
##          2   0   0 257   0
##          3   0   0   0 256
## test accuracy 1
paste("Test Accuracy:", 1)
## [1] "Test Accuracy: 1"

Dari sini kita bisa lihat akurasi test yang dihasilkan adalah bernilai 1.

# accumulate model's accuracy
name <- c("Esti Accu", "Train Accu", "Valid Accu", "Test Accu")
RF_model1_cv_accuracy <- c(model_accuracy, predict_train_accuracy, predict_valid_accuracy, 1)
names(RF_model1_cv_accuracy) <- name
RF_model1_cv_accuracy
##  Esti Accu Train Accu Valid Accu  Test Accu 
##   "0.9106"        "1"        "1"        "1"

Random Forest 5 Predictor

# set seed for reproduction
set.seed(2307)
cl <- makeCluster(6, type = "SOCK")
registerDoSNOW(cl)

RF_model2_cv <- train(price_range ~battery_power +mobile_wt +px_height +px_width + ram , 
                        data =trainData,
                       method = "rf",
                       trControl = control)
stopCluster(cl)

# Show CV mdoel's details
print(RF_model2_cv)
## Random Forest 
## 
## 1600 samples
##    5 predictor
##    4 classes: '0', '1', '2', '3' 
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold, repeated 5 times) 
## Summary of sample sizes: 1441, 1441, 1441, 1439, 1439, 1440, ... 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy  Kappa 
##   2     0.9090    0.8787
##   3     0.9068    0.8757
##   5     0.8949    0.8598
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.

Pada tahap ini kita melakukan uji validasi silang metode random forest dengan 5 prediktor. Dari sini kita juga ingin membandingkan model lain dengan 5 prediktor untuk mengetahui apakah akurasi nya berbeda atau hanya sedikit perbedaannya.

# Record model's accuracy
model_accuracy <- format(RF_model2_cv$results$Accuracy[2], digits = 4)
paste("Estimated accuracy:", model_accuracy)
## [1] "Estimated accuracy: 0.9068"
### Access accuracy on different datasets
# prediction's Confusion Matrix on the trainData 
predict_train <-predict(RF_model2_cv, trainData)
conMat <- confusionMatrix(predict_train, trainData$price_range)
conMat$table
##           Reference
## Prediction   0   1   2   3
##          0 409   0   0   0
##          1   0 390   0   0
##          2   0   0 397   0
##          3   0   0   0 404

Pada tahap ini, kita ingin mencari akurasi dari trainData nya. Kita menggunakan function predict untuk memprediksi dan confusionMatrix untuk mencari akurasi nya.

# prediction's Accuracy on the trainData 
predict_train_accuracy <- format(conMat$overall["Accuracy"], digits=4)
paste("trainData Accuracy:", predict_train_accuracy)
## [1] "trainData Accuracy: 1"
# prediction's Confusion Matrix on the validData
predict_valid <-predict(RF_model2_cv, validData)
conMat <- confusionMatrix(predict_valid, validData$price_range)
conMat$table
##           Reference
## Prediction   0   1   2   3
##          0  89   1   0   0
##          1   2 103   3   0
##          2   0   6  94   9
##          3   0   0   6  87

Pda tahap ini, kita ingin mencari akurasi dari validData nya. Kita menggunakan function predict untuk memprediksi dan confusionMatrix untuk mencari akurasi nya.

# prediction's Accuracy on the validData 
predict_valid_accuracy <- format(conMat$overall["Accuracy"], digits=4)
paste("validData Accuracy:", predict_valid_accuracy)
## [1] "validData Accuracy: 0.9325"
P_test <- predict(RF_model2_cv,test)
hello$P_test <- P_test


conMat <- confusionMatrix(P_test, hello$P_test)
conMat$table
##           Reference
## Prediction   0   1   2   3
##          0 254   0   0   0
##          1   0 227   0   0
##          2   0   0 264   0
##          3   0   0   0 255

Tuning

Pada proses sebelumnya (Cross Validation), kita mendapatkan bahwa metode atau model yang terbaik untuk dijadikan prediksi dataset adalah model Random Forest. Pada tahap tuning kita cari parameter terbaik yang dapat digunakan dalam model Random Forest. Dengan Metode manual kita cari parameter mtry dan ntree terbaik.

set.seed(980)
cntrl <- trainControl(method = "repeatedcv", number = 10, repeats = 5, search = "grid")
cl <- makeCluster(6, type = "SOCK")
registerDoSNOW(cl)
set.seed(981)
FT_RF <- train(price_range ~ battery_power + int_memory + mobile_wt + 
    px_height + px_width + ram, data = train, method = "rf", tuneLength = 15, ntree = 500, trControl = cntrl)
## note: only 5 unique complexity parameters in default grid. Truncating the grid to 5 .
stopCluster(cl)
print(FT_RF)
## Random Forest 
## 
## 2000 samples
##    6 predictor
##    4 classes: '0', '1', '2', '3' 
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold, repeated 5 times) 
## Summary of sample sizes: 1800, 1800, 1800, 1800, 1800, 1800, ... 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy  Kappa 
##   2     0.9153    0.8871
##   3     0.9136    0.8848
##   4     0.9114    0.8819
##   5     0.9070    0.8760
##   6     0.9012    0.8683
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.

Pada coding diatas digunakan untuk mencari parameter mtry terbaik yaitu mtry = 2 dengan akurasi 0,9160.

cntrl1 <- trainControl(method = "repeatedcv", number = 10, repeats = 5, search = "grid")
cl <- makeCluster(6, type = "SOCK")
registerDoSNOW(cl)
tngrd <- expand.grid(.mtry =c(sqrt(ncol(train))))
mdllst <- list()
for (ntree in c(500, 1000, 1500, 2000)) {
  set.seed(980)
  fit <- train(price_range ~ battery_power + int_memory + mobile_wt + 
    px_height + px_width + ram, data = train, methode = "rf", metric= "Accuracy", tuneGrid = tngrd, trControl = cntrl1, ntree=ntree)
  key <- toString(ntree)
  mdllst[[key]] <- fit
  
}
stopCluster(cl)
rslt <- resamples(mdllst)
summary(rslt)
## 
## Call:
## summary.resamples(object = rslt)
## 
## Models: 500, 1000, 1500, 2000 
## Number of resamples: 50 
## 
## Accuracy 
##       Min. 1st Qu. Median   Mean 3rd Qu. Max. NA's
## 500  0.845  0.8950   0.91 0.9075   0.925 0.95    0
## 1000 0.840  0.8962   0.91 0.9083   0.925 0.95    0
## 1500 0.845  0.8950   0.91 0.9085   0.925 0.95    0
## 2000 0.845  0.8950   0.91 0.9084   0.925 0.95    0
## 
## Kappa 
##        Min. 1st Qu. Median   Mean 3rd Qu.   Max. NA's
## 500  0.7933  0.8600   0.88 0.8767     0.9 0.9333    0
## 1000 0.7867  0.8617   0.88 0.8777     0.9 0.9333    0
## 1500 0.7933  0.8600   0.88 0.8780     0.9 0.9333    0
## 2000 0.7933  0.8600   0.88 0.8779     0.9 0.9333    0
dotplot(rslt)

Coding diatas dapat dilihat bahwa ntree terbaik memiliki nilai rata-rata akurasi tertinggi sebesar 0,972 berada paka ntree = 500.
mtry = 2 ntree terbaik pada model RF dengan menggunakan Fine Tune didapat ntree terbaik ada di ntree = 500 dengan nilai akurasi 0,972. Lalu kita gunakan algorithma untuk melakukan tuning dengan parameter yang sudah kita dapatkan sebelumnya.

# Create model with mtry = 2 and ntree = 500
control <- trainControl(method="repeatedcv", number=10, repeats=3)
metric <- "Accuracy"
set.seed(980)
mtrybst <- 2
tunegrid <- expand.grid(.mtry=mtrybst)
cl <- makeCluster(6, type = "SOCK")
registerDoSNOW(cl)
rf_best <- train(price_range ~ battery_power + int_memory + mobile_wt + 
    px_height + px_width + ram, data = train, method="rf", metric="Accuracy", tuneGrid=tunegrid, trControl=control, ntree=500)
stopCluster(cl)
print(rf_best)
## Random Forest 
## 
## 2000 samples
##    6 predictor
##    4 classes: '0', '1', '2', '3' 
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold, repeated 3 times) 
## Summary of sample sizes: 1800, 1800, 1800, 1800, 1800, 1800, ... 
## Resampling results:
## 
##   Accuracy  Kappa
##   0.916     0.888
## 
## Tuning parameter 'mtry' was held constant at a value of 2

Dari tes algorithma dengan parameter mtry = 2 dan ntree = 500 pada model Random Forest didapat nilai akurasi sebesar 0,9133.

Kesimpulan

tabel = data.frame("Model" = c("DT 5 Predictor","DT 6 Predictor","RF 6 Predictor","RF 5 Predictor"),
           "Esti Accu" = c( 0.7128, 0.7128, 0.9106, 0.9068),
           "Train Accu" = c(0.645, 0.645,1,1),
           "Valid Accu" = c(0.645,0.63,1,0.9325),
           "Test Accu"= c(1,1,1,1)
           )
tabel1 = tabel[,-2] 
Dataset= c('Train.Accu','Valid.Accu','Test.Accu')

tabel1
df.long <- gather(tabel1, Dataset, Accuracy, -Model, factor_key =TRUE)
ggplot(data = df.long, aes(x = Model, y = Accuracy, fill = Dataset)) +
  geom_col(position = position_dodge()) 

Dari hasil PLot di atas. memungkinkan model terbaik menggunakan random forest dengan 6 prediktor. Prediktor yang digunakan yaitu battery_power,int_memory , mobile_wt , px_height , px_width , dan ram. Jadi kita memilih model random forest 6 prediktor untuk memprediksi kisaran harga pada data test.

ggplot(hello,
   aes(x = preictRF,
       y = ..count.. / sum(..count..))) +
  geom_bar(fill= rainbow(4), color ="azure4") +
  theme_minimal()+
  labs(title = "Prediksi harga Random Forest",
       x = "kisaran harga",
       y = "persentase")+
  scale_y_continuous(labels = percent)

Dari hasil prediksi random forest yang kita pilih tadi, kebanyakan brand menjual handphone dengan kisaran harga 3 atau harga yang paling tinggi. Jadi berdasarkan prediksi yang telah kita lakukan, Pak Bakti disarankan menjual handphone dengan harga yang paling tinggi juga untuk dapat bersaing dan menyaingi brand-brand handphone yang lain. Pa Bakti bisa menjual handphone brand nya dengan kisaran harga yang tinggi atau terletak pada price_range 3.

Referensi

  1. https://mti.binus.ac.id/2017/11/24/10-fold-cross-validation/#:~:text=Cross%2Dvalidation%20(CV)%20adalah,dan%20divalidasi%20oleh%20subset%20validasi.