DataRockie

Hello World 04 – Classification Models in R

28 ธ.ค. 2563 – เราเริ่มเรียนเวลา 21.00 น. นะครับ ใช้เวลาประมาณ 1.5 ชั่วโมง ก่อนเรียนคืนนี้ปรับ Keyboard ให้พิมพ์ตัว ~ ได้ด้วยนะครับ ใน R เราใช้ tilde ~ ตอนเทรนโมเดลเยอะมาก (formula)

Enjoy the class!

Note – ไม่มีพื้นฐานก็เข้าเรียนได้นะครับ : ) นักเรียนต้องมี Google Account ด้วยนะครับ วันนี้เราสอนด้วย RStudio Cloud สมัคร Free Account รอเรียนได้เลยครับ (เรียนเขียน Code บนเว็บเบราเซอร์)

ตัวอย่างข้อมูล penguins ที่เราจะสอนคืนนี้ ทำนาย species etc.

R code in this lecture

Code template สำหรับการทำ train test split ง่ายๆ เราสามารถเปลี่ยน train ratio ได้ใน function sample()

# train test split example
set.seed(42)
n <- nrow(data)
train_id <- sample(1:n, size = 0.8*n)
train_data <- data[train_id, ]
test_data <- data[-train_id, ]

Code สำหรับเทรนโมเดล linear และ logistic regression

# train linear regression
lm(y ~ x1 + x2 + x3, data = train_data)

# train logistic regression
glm(y ~ x1 + x2 + x3, data = train_data, family = "binomial")

Code สำหรับเทรนโมเดล decision tree

# install packages
install.packages(c("rpart", "rpart.plot"))
library(rpart)
library(rpart.plot)

# train decision tree
treeModel <- rpart(y ~ x1 + x2 + x3, data = data, method = "class")

# plot decision tree (image shown below)
rpart.plot(treeModel)

Code template สำหรับการเทรนโมเดลด้วย K-Fold Cross Validation (แอดไม่มีเวลาสอนเรื่องนี้ใน Class ไว้เรามาต่อกันครั้งหน้านะครับ)

# install packages
install.packages(("caret", "mlbench"))
library(caret)
library(mlbench)

# split data before training phase
# use the train test split code above

# train model with 5 folds cross validation
ctrl <- trainControl(method = "cv",
                     number = 5,
                     verboseIter = TRUE)

model <- train(diabetes ~ ., 
               data = PimaIndiansDiabetes,
               method = "rpart",
               trControl = ctrl)  

# model accuracy
p <- predict(model)
mean(p == PimaIndiansDiabetes$diabetes)

# confusion matrix
table(p, PimaIndiansDiabetes$diabetes, dnn = c("predicted", "actual"))

Decision Tree Model

Google Slide

Leave a Reply