Professional Documents
Culture Documents
L3 - คำสั่งภาษา R เบื้องต้น (Decision Tree, Random Forest) PDF
L3 - คำสั่งภาษา R เบื้องต้น (Decision Tree, Random Forest) PDF
Pang Taithong
ั
คําสงภาษา R เบืองต ้น (Decision Tree, Random Forest)
ตัวอย่างการใช ้คําสัง R เบืองต ้นทีใช ้สําหรับการสร ้างโมเดล Decision Tree และโมเดล Random Forest ต่อเนืองจากบทความการสร ้าง
Classification Model ใน
ตอนที 1 (h p://wp.me/p4UVPR-20) และ ตอนที 2 (h p://wp.me/p4UVPR-2h)
1. ไลบรารีหลักๆทีใช ้ในการสร ้างโมเดล Decision Tree, โมเดล Random Forest และการวาดกราฟต่างๆ มีดงั นี
# สําหรับสร ้างโมเดล Decision Tree
install.packages(“rpart”)
# สําหรับวาด Decision Tree
install.packages(‘ra le’)
install.packages(‘rpart.plot’)
install.packages(‘RColorBrewer’)
# สําหรับสร ้าง Random Forest
install.packages(‘randomForest’)
# สําหรับสร ้าง Bar Chart
install.packages(‘plotly’)
#เรียกใช ้ไลบรารี
library(rpart)
library(ra le)
library(rpart.plot)
library(RColorBrewer)
library(randomForest)
library(plotly)
2. คําสังนํ าเข ้าด ้วยไฟล์ CSV
raw_data <- read.csv( file=”path_to_ file/priceday.csv”,head=TRUE,sep=”,”)
หมายเหตุ head=TRUE หมายถึง ไฟล์ CSV มีชอคอลั ื มภ์ทแถวแรก
ี
sep=”,” หมายถึง ไฟล์ CSV นีใช ้เครืองหมาย “,” ในการแบ่งฟิ ลด์คอลัมภ์
3. คําสังการสุม ่ ข ้อมูล
smp_size <- floor(0.8 * nrow(raw_data))
set.seed(123)
train_ind <- sample(seq_len(nrow(raw_data)), size = smp_size)
4. คําสังการแบ่งข ้อมูลเก็บใส่เวกเตอร์สําหรับ Train และ Test
training_data <- raw_data[train_ind, ] #เก็บข ้อมูลทีสุม ่ 80% ไว ้ใน training_data
testing_data <- raw_data[-train_ind, ] #เก็บข ้อมูลทีสุม ่ 20% ไว ้ใ น test_data
split_data <- list(training_data, testing_data)
5. คําสังหรับโมเดล Decision Tree
1. คําสัง Train Model
#Train ข ้อมูลโดยใช ้ training_data กําหนด ‘price’ เป็ นเฉลย
tree_ fit <- rpart(price ~ ., training_data, method = “class”)
2. คําสัง Test Model
#Test ข ้อมูลโดยใช ้ testing_data และไม่ต ้องกําหนดเฉลย
tree_pred <- predict(tree_fit, testing_data, type=”class”)
3. คําสังวาด Decision Tree
fancyRpartPlot(tree_ t) #วาด Decision Tree (แบบมีสส ั สวยงาม ใช ้ไลบรารี RColorBrewer)
ี น
#rpart.plot(tree_ t, type = 4, extra = 100, fallen.leaves = T) (แบบธรรมดา)
4. คําสังการตัดกิงต ้นไม ้ (แก ้ปั ญหา overfi ing)
ptree <- prune(tree_ t,cp=tree_fit$cptable[which.min(tree_ t$cptable[,”xerror”]),”CP”]) ptree_pred <- predict(ptree,
testing_data, type=”class”)
8. กราฟสถิตต ิ า่ งๆ
plot(table(raw_data$usd), col=rgb(150,100,400,500,maxColorValue=500),
xlab = “USD (Days)”, ylab = “”, main = “USD Frequency”)