💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน
ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:
Correlation
t-tests
ANOVA
Reliability
Factor analysis
🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ
ID Name Age Grade CursedEnergy Technique Missions
Min. : 1.00 Length:10 Min. :15.00 Length:10 Min. : 60.00 Length:10 Min. : 20.00
1st Qu.: 3.25 Class :character 1st Qu.:16.25 Class :character 1st Qu.: 76.25 Class :character 1st Qu.: 28.50
Median : 5.50 Mode :character Median :17.00 Mode :character Median : 90.00 Mode :character Median : 37.50
Mean : 5.50 Mean :19.80 Mean :236.40 Mean : 52.30
3rd Qu.: 7.75 3rd Qu.:24.75 3rd Qu.:275.00 3rd Qu.: 73.75
Max. :10.00 Max. :28.00 Max. :999.00 Max. :120.00
.
💠 dim()
dim() ใช้แสดงจำนวน rows และ columns ใน data frame:
# Create a new data frame
new_sorcerer <- data.frame(
ID = 11,
Name = "Hajime Kashimo",
Age = 25,
Grade = "Special",
CursedEnergy = 500,
Technique = "Lightning",
Missions = 60
)
# Bind the data frames by rows
jjk_df <- rbind(jjk_df, new_sorcerer)
# View the result
jjk_df
ผลลัพธ์:
ID Name Age Grade CursedEnergy Technique Missions
1 1 Yuji Itadori 15 1st Year 80 Divergent Fist 25
2 2 Megumi Fushiguro 16 1st Year 95 Ten Shadows 30
3 3 Nobara Kugisaki 16 1st Year 70 Straw Doll 20
4 4 Satoru Gojo 28 Special 999 Limitless 120
5 5 Maki Zenin 17 2nd Year 60 Heavenly Restriction 35
6 6 Toge Inumaki 17 2nd Year 85 Cursed Speech 28
7 7 Panda 18 2nd Year 75 Gorilla Mode 40
8 8 Kento Nanami 27 Special 200 Ratio Technique 90
9 9 Yuta Okkotsu 17 Special 300 Rika 55
10 10 Suguru Geto 27 Special 400 Cursed Spirit Manipulation 80
11 11 Hajime Kashimo 25 Special 500 Lightning 60
💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน
ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:
Correlation
t-tests
ANOVA
Reliability
Factor analysis
🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ
ในบทความนี้ เราจะมาเรียนรู้ 7 วิธีการทำงานกับ time series data หรือข้อมูลที่จัดเรียงด้วยเวลา ในภาษา R ผ่านการทำงานกับ Bitcoin Historical Data ซึ่งมีข้อมูล Bitcoin ในช่วงปี ค.ศ. 2010–2024 กัน:
Converting: การแปลงข้อมูลเป็น datetime และ time series
Missing values: การจัดการ missing values ใน time series data
Plotting: การสร้างกราฟ time series data
Subsetting: การเลือกข้อมูลจาก time series data
Aggregating: การสรุป time series data
Rolling window: การทำ rolling window
Expanding window: การทำ expanding window
ถ้าพร้อมแล้วไปเริ่มกันเลย
🏁 Getting Started
ในการเริ่มทำงานกับ time series ในภาษา R เราจะเริ่มต้นจาก 2 อย่าง ได้แก่:
Install and load packages
Load dataset
.
1️⃣ Install & Load Packages
ในภาษา R เรามี 3 packages ที่ใช้ทำงานกับ time series data บ่อย ๆ ได้แก่:
Base R packages ที่มาพร้อมกับภาษา R
lubridate: ใช้แปลงข้อมูลและจัด format ของ date-time data
เรามาดูวิธีแรกในการทำงานกับ time series data กัน นั่นคือ:
การแปลงข้อมูลให้เป็น datetime
การแปลงข้อมูลให้เป็น time series
.
1️⃣ การแปลงข้อมูลให้เป็น Datetime
ในการทำงานกับ time series data เราจะต้องแปลงข้อมูลประเภทอื่น ๆ เช่น character และ numeric ให้เป็น datetime ก่อน เช่น date (เช่น “Feb 09, 2024”) ใน Bitcoin dataset
เราสามารถแปลงข้อมูลจาก character เป็น Date ได้ 2 วิธี ดังนี้:
.
วิธีที่ 1. ใช้ as.Date() ซึ่งเป็น base R function และต้องการ input 2 อย่าง ได้แก่:
x: ข้อมูลที่ต้องการแปลงเป็น Date
format: format ของวันเวลาของข้อมูลต้นทาง (เช่น วัน-เดือน-ปี, ปี-เดือน-วัน, เดือน-วัน-ปี)
# Convert `date` to Date
btc_cleaned$date <- as.Date(btc_cleaned$date,
format = "%b %d, %Y")
# Plot the time series
autoplot.zoo(btc_zoo[, "close"]) +
## Adjust line colour
geom_line(color = "blue") +
## Add title and labels
labs(title = "Bitcoin Closing Price Over Time (2010–2024)",
x = "Time",
y = "Closing Price (USD)") +
## Use minimal theme
theme_minimal()
# Example 1. View yearly mean closing price
btc_yr_mean <- apply.yearly(btc_zoo[, "close"],
FUN = mean)
# Plot the results
autoplot.zoo(btc_yr_mean) +
## Adjust line colour
geom_line(color = "blue") +
## Add title and labels
labs(title = "Bitcoin Yearly Mean Closing Price (2010–2024)",
x = "Time",
y = "Closing (USD)") +
## Use minimal theme
theme_minimal()
ผลลัพธ์:
หรือหาราคาปิดสูงสุดในแต่ละไตรมาส:
# Example 2. View quarterly max closing price
btc_qtr_max <- apply.quarterly(btc_zoo[, "close"],
FUN = max)
# Plot the results
autoplot.zoo(btc_qtr_max) +
## Adjust line colour
geom_line(color = "blue") +
## Add title and labels
labs(title = "Bitcoin Quarterly Maximum Closing Price (2010–2024)",
x = "Time",
y = "Closing (USD)") +
## Use minimal theme
theme_minimal()
# Create the window for mean price
btc_30_days_roll_mean <- rollmean(x = btc_zoo,
k = 30,
align = "right",
fill = NA)
# Plot the results
autoplot.zoo(btc_30_days_roll_mean[, "close"]) +
## Adjust line colour
geom_line(color = "blue") +
## Add title and labels
labs(title = "Bitcoin 30-Day Rolling Mean Price (2010–2024)",
x = "Time",
y = "Closing (USD)") +
## Use minimal theme
theme_minimal()
# Creating a rolling window with min() function
btc_30_days_roll_min <- rollapply(data = btc_zoo,
width = 30,
FUN = min,
align = "right",
fill = NA)
# Plot the results
autoplot.zoo(btc_30_days_roll_min[, "close"]) +
## Adjust line colour
geom_line(color = "blue") +
## Add title and labels
labs(title = "Bitcoin 30-Day Rolling Minimum Price (2010–2024)",
x = "Time",
y = "Closing (USD)") +
## Use minimal theme
theme_minimal()
ผลลัพธ์:
➡️ Expanding Window
Expanding window เป็นการสรุปข้อมูลแบบสะสม เช่น:
Date
Average
2024-01-01
หาค่าเฉลี่ยของวันที่ 1
2024-01-02
หาค่าเฉลี่ยของวันที่ 1 + 2
2024-01-03
หาค่าเฉลี่ยของวันที่ 1 + 2 + 3
2024-01-04
หาค่าเฉลี่ยของวันที่ 1 + 2 + 3 + 4
2024-01-05
หาค่าเฉลี่ยของวันที่ 1 + 2 + 3 + 4 + 5
ในภาษา R เราสามารถสร้าง expanding window ได้ด้วย rollapply() โดยเราต้องกำหนดให้:
# Subset for Jan 2024 data
btc_jan_2024 <- window(x = btc_zoo,
start = as.Date("2024-01-01"),
end = as.Date("2024-01-31"))
# Create a sequence of widths
btc_jan_2024_width <- seq_along(btc_jan_2024)
# Create an expanding window for mean price
btc_exp_mean <- rollapply(data = btc_2024,
width = btc_jan_2024_width,
FUN = mean,
align = "right",
fill = NA)
# Plot the results
autoplot.zoo(btc_exp_mean[, "close"]) +
## Adjust line colour
geom_line(color = "blue") +
## Add title and labels
labs(title = "Bitcoin Expanding Mean Price (Jan 2024)",
x = "Time",
y = "Closing (USD)") +
## Use minimal theme
theme_minimal()
ผลลัพธ์:
😎 Summary
ในบทความนี้ เราได้ทำความรู้จักกับ 7 วิธีการทำงานกับ time series ในภาษา R โดยใช้ base R, lubridate, และ zoo package กัน:
💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน
ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:
Correlation
t-tests
ANOVA
Reliability
Factor analysis
🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ
XGBoost เป็น machine learning model ที่จัดอยู่ในกลุ่ม tree-based models หรือ models ที่ทำนายข้อมูลด้วย decision tree อย่าง single decision tree และ random forest
ใน XGBoost, decision trees จะถูกสร้างขึ้นมาเป็นรอบ ๆ โดยในแต่ละรอบ decision trees ใหม่จะเรียนรู้จากความผิดพลาดของรอบก่อน ซึ่งจะทำให้ decision trees ใหม่มีความสามารถที่ดีขึ้นเรื่อย ๆ
เมื่อสิ้นสุดการสร้าง XGBoost ใช้ผลรวมของ decision trees ทุกต้นในการทำนายข้อมูล ดังนี้:
# A tibble: 6 × 11
manufacturer model displ year cyl trans drv cty hwy fl class
<chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>
1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compact
2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compact
3 audi a4 2 2008 4 manual(m6) f 20 31 p compact
4 audi a4 2 2008 4 auto(av) f 21 30 p compact
5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compact
6 audi a4 2.8 1999 6 manual(m5) f 18 26 p compact
จากผลลัพธ์ เราจะเห็นได้ว่า mpg มี columns ที่เราต้องปรับจาก character เป็น factor อยู่ เช่น manufacturer, model ซึ่งเราสามารถปรับได้ดังนี้:
# Convert character columns to factor
## Get character columns
chr_cols <- c("manufacturer",
"model",
"trans",
"drv",
"fl",
"class")
## For-loop through the character columns
for (col in chr_cols) {
mpg[[col]] <- as.factor(mpg[[col]])
}
## Check the results
str(mpg)
# Separate the features from the outcome
## Get the features
x <- mpg[, !names(mpg) %in% "hwy"]
## One-hot encode the features
x <- model.matrix(~ . - 1,
data = x)
## Get the outcome
y <- mpg$hwy
ข้อที่ 2. จากนั้น เราจะแบ่ง dataset เป็น training (80%) และ test sets (20%) ดังนี้:
# Split the data
## Set seed for reproducibility
set.seed(360)
## Get training index
train_index <- sample(1:nrow(x),
nrow(x) * 0.8)
## Create x, y train
x_train <- x[train_index, ]
y_train <- y[train_index]
## Create x, y test
x_test <- x[-train_index, ]
y_test <- y[-train_index]
## Check the results
cat("TRAIN SET", "\\n")
cat("1. Data in x_train:", nrow(x_train), "\\n")
cat("2. Data in y_train:", length(y_train), "\\n")
cat("---", "\\n", "TEST SET", "\\n")
cat("1. Data in x_test:", nrow(x_test), "\\n")
cat("2. Data in y_test:", length(y_test), "\\n")
ผลลัพธ์:
TRAIN SET
1. Data in x_train: 187
2. Data in y_train: 187
---
TEST SET
1. Data in x_test: 47
2. Data in y_test: 47
.
ข้อที่ 3. สุดท้าย เราจะแปลง x, y เป็น DMatrix ซึ่งเป็น object ที่ xgboost ใช้ในการสร้าง XGboost model ดังนี้:
# Convert to DMatrix
## Training set
train_set <- xgb.DMatrix(data = x_train,
label = y_train)
## Test set
test_set <- xgb.DMatrix(data = x_test,
label = y_test)
## Check the results
train_set
test_set
ผลลัพธ์:
TRAIN SET
xgb.DMatrix dim: 187 x 77 info: label colnames: yes
---
TEST SET
xgb.DMatrix dim: 47 x 77 info: label colnames: yes
4️⃣ Train the Model
ในขั้นที่สี่ เราจะสร้าง XGBoost model ด้วย xgb.train() ซึ่งต้องการ 5 arguments ดังนี้:
💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน
ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:
Correlation
t-tests
ANOVA
Reliability
Factor analysis
🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ
💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน
ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:
Correlation
t-tests
ANOVA
Reliability
Factor analysis
🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ
ในการทำ machine learning (ML) ในภาษา R เรามี packages และ functions ที่หลากหลายให้เลือกใช้งาน ซึ่งแต่ละ package และ function มีวิธีใช้งานที่แตกต่างกันไป
ยกตัวอย่างเช่น:
glm() จาก base R สำหรับสร้าง regression models ต้องการ input 3 อย่าง คือ formula, data, และ family:
glm(formula, data, family)
knn() จาก class package สำหรับสร้าง KNN model ต้องการ input 4 อย่าง คือ ตัวแปรต้นของ training set, ตัวแปรต้นของ test set, ตัวแปรตามของ training set, และค่า k:
knn(train_x, test_x, train_y, k)
rpart() จาก rpart package สำหรับสร้าง decision tree model ต้องการ input 2 อย่าง คือ formula และ data:
rpart(formula, data)
…
การใช้งาน function ที่แตกต่างกันทำให้การสร้าง ML models เกิดความซับซ้อนโดยไม่จำเป็น และทำให้เกิดความผิดพลาดในการทำงานได้ง่าย
# Set seed for reproducibility
set.seed(2025)
# Define the training set index
bt_split <- initial_split(data = bt,
prop = 0.8,
strata = medv)
# Create the training set
bt_train <- training(bt_split)
# Create the test set
bt_test <- testing(bt_split)
# Prepare the recipe
rec_prep <- prep(rec,
data = bt_train)
# Bake the training set
bt_train_baked <- bake(rec_prep,
new_data = NULL)
# Bake the test set
bt_test_baked <- bake(rec_prep,
new_data = bt_test)
.
4️⃣ Instantiate a Model
ในขั้นที่ 4 เราจะเรียกใช้ algorithm สำหรับ model ของเรา โดยในตัวอย่าง เราจะลองสร้าง decision tree กัน
ในขั้นนี้ เรามี 3 functions จะเรียกใช้งาน ได้แก่:
No.
Function
For
1
decision_tree()
สร้าง decision tree *
2
set_engine()
กำหนด engine หรือ package ที่ใช้สร้าง model
3
set_mode()
กำหนดประเภท model (classification หรือ regression)
ในขั้นแรก เราจะแบ่ง dataset ออกเป็น 2 ชุด (เหมือนกับ standard flow):
# Set seed for reproducibility
set.seed(2025)
# Define the training set index
bt_split <- initial_split(data = bt,
prop = 0.8,
strata = medv)
# Create the training set
bt_train <- training(bt_split)
จะสังเกตว่า เราจะไม่ได้สร้าง test set ในครั้งนี้
.
2️⃣ Create a Recipe
ในขั้นที่ 2 เราจะสร้าง recipe (เหมือนกับ standard flow):
# Set seed for reproducibility
set.seed(2025)
# Define the training set index
bt_split <- initial_split(data = bt,
prop = 0.8,
strata = medv)
# Create the training set
bt_train <- training(bt_split)
💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน
ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:
Correlation
t-tests
ANOVA
Reliability
Factor analysis
🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ
caret เป็น package ยอดนิยมในภาษา R ในทำ machine learning (ML)
caret ย่อมาจาก Classification And REgression Training และเป็น package ที่ถูกออกแบบมาช่วยให้การทำ ML เป็นเรื่องง่ายโดยมี functions สำหรับทำงานกับ ML workflow เบ็ดเสร็จใน package เดียว
p = สัดส่วนข้อมูลที่เราต้องการแบ่งให้กับ training set
list = ต้องการผลลัพธ์เป็น list (TRUE) หรือ matrix (FALSE)
สำหรับ BostonHousing เราจะแบ่ง 70% เป็น training set และ 30% เป็น test set แบบนี้:
# Set seed for reproducibility
set.seed(888)
# Get train index
train_index <- createDataPartition(BostonHousing$medv, # Specify the outcome
p = 0.7, # Set aside 70% for training set
list = FALSE) # Return as matrix
# Create training set
bt_train <- BostonHousing[train_index, ]
# Create test set
bt_test <- BostonHousing[-train_index, ]
เราสามารถดูจำนวนข้อมลใน training และ test sets ได้ด้วย nrow():
# Check the results
cat("Rows in training set:", nrow(bt_train), "\\n")
cat("Rows in test set:", nrow(bt_test))
ผลลัพธ์:
Rows in training set: 356
Rows in test set: 150
.
🍳 Step 2. Preprocess the Data
ในขั้นที่ 2 เราจะเตรียมข้อมูลเพื่อใช้ในการสร้าง model
# Learn preprocessing on training set
ppc <- preProcess(bt_train[, -14], # Select all predictors
method = c("center", "scale")) # Centre and scale
ตอนนี้ เราจะได้วิธีการเตรียมข้อมูลมาแล้ว ซึ่งเราจะต้องนำไปปรับใช้กับ training และ test sets ด้วย predict() และ cbind() แบบนี้:
Training set:
# Apply preprocessing to training set
bt_train_processed <- predict(ppc,
bt_train[, -14])
# Combine the preprocessed training set with outcome
bt_train_processed <- cbind(bt_train_processed,
medv = bt_train$medv)
Test set:
# Apply preprocessing to test set
bt_test_processed <- predict(ppc,
bt_test[, -14])
# Combine the preprocessed test set with outcome
bt_test_processed <- cbind(bt_test_processed,
medv = bt_test$medv)
ตอนนี้ training และ test sets ก็พร้อมที่จะใช้ในการสร้าง model แล้ว
.
👟 Step 3. Train the Model
ในขั้นที่ 3 เราจะสร้าง model กัน
โดยในตัวอย่าง เราจะลองสร้าง k-nearest neighbor (KNN) model ซึ่งทำนายข้อมูลด้วยการดูข้อมูลที่อยู่ใกล้เคียง
trControl = ค่าที่กำหนดการสร้าง model (ต้องใช้ function ชื่อ trainControl() ในการกำหนด)
tuneGrid = data frame ที่กำหนดค่า hyperparametre เพื่อทำ model tuning และหา model ที่ดีที่สุด
เราสามารถใช้ train() เพื่อสร้าง KNN model ในการทำนายราคาบ้านได้แบบนี้:
# Define training control:
# use k-fold cross-validation where k = 5
trc <- trainControl(method = "cv",
number = 5)
# Define grid:
# set k as odd numbers between 3 and 13
grid <- data.frame(k = seq(from = 3,
to = 13,
by = 2))
# Train the model
knn_model <- train(medv ~ ., # Specify the formula
data = bt_train_processed, # Use training set
method = "kknn", # Use knn engine
trControl = trc, # Specify training control
tuneGrid = grid) # Use grid to tune the model
เราสามารถดูรายละเอียดของ model ได้ดังนี้:
# Print the model
knn_model
ผลลัพธ์:
k-Nearest Neighbors
356 samples
13 predictor
No pre-processing
Resampling: Cross-Validated (5 fold)
Summary of sample sizes: 284, 286, 286, 284, 284
Resampling results across tuning parameters:
k RMSE Rsquared MAE
3 4.357333 0.7770080 2.840630
5 4.438162 0.7760085 2.849984
7 4.607954 0.7610468 2.941034
9 4.683062 0.7577702 2.972661
11 4.771317 0.7508908 3.043617
13 4.815444 0.7524266 3.053415
RMSE was used to select the optimal model using the smallest value.
The final value used for the model was k = 3.
.
📈 Step 4. Evaluate the Model
ในขั้นสุดท้าย เราจะประเมินความสามารถของ model ในการทำนายราคาบ้านกัน
💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน
ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:
Correlation
t-tests
ANOVA
Reliability
Factor analysis
🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ
# A tibble: 6 × 11
manufacturer model displ year cyl trans drv cty hwy fl class
<chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>
1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compact
2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compact
3 audi a4 2 2008 4 manual(m6) f 20 31 p compact
4 audi a4 2 2008 4 auto(av) f 21 30 p compact
5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compact
6 audi a4 2.8 1999 6 manual(m5) f 18 26 p compact
จากผลลัพธ์จะเห็นว่า บาง columns (เช่น manufacturer, model) มีข้อมูลประเภท character ซึ่งเราควระเปลี่ยนเป็น factor เพื่อช่วยให้การสร้าง model มีประสิทธิภาพมากขึ้น:
# Convert character columns to factor
## Get character columns
chr_cols <- c("manufacturer", "model",
"trans", "drv",
"fl", "class")
## For-loop through the character columns
for (col in chr_cols) {
mpg[[col]] <- as.factor(mpg[[col]])
}
## Check the results
str(mpg)
# Split the data
## Set seed for reproducibility
set.seed(123)
## Get training rows
train_rows <- sample(nrow(mpg),
nrow(mpg) * 0.7)
## Create a training set
train <- mpg[train_rows, ]
## Create a test set
test <- mpg[-train_rows, ]
💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน
ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:
Correlation
t-tests
ANOVA
Reliability
Factor analysis
🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ
# Check the distribution of `price`
ggplot(dm,
aes(x = price)) +
## Instantiate a histogram
geom_histogram(binwidth = 100,
fill = "skyblue3") +
## Add text elements
labs(title = "Distribution of Price",
x = "Price",
y = "Count") +
## Set theme to minimal
theme_minimal()
# Check the distribution of logged `price`
ggplot(dm,
aes(x = price_log)) +
## Instantiate a histogram
geom_histogram(fill = "skyblue3") +
## Add text elements
labs(title = "Distribution of Price After Log Transformation",
x = "Price (Logged)",
y = "Count") +
## Set theme to minimal
theme_minimal()
ในขั้นสุดท้ายก่อนใช้ linear regression เราจะแบ่งข้อมูลออกเป็น 2 ชุด:
Training set สำหรับสร้าง linear regression model
Test set สำหรับประเมินความสามารถของ linear regression model
ในบทความนี้ เราจะแบ่ง 80% ของ dataset เป็น training set และ 20% เป็น test set:
# Split the data
## Set seed for reproducibility
set.seed(181)
## Training index
train_index <- sample(nrow(dm),
0.8 * nrow(dm))
## Create training set
train_set <- dm[train_index, ]
## Create test set
test_set <- dm[-train_index, ]
ตอนนี้ เราพร้อมที่จะสร้าง linear regression model กันแล้ว
🏷️ Linear Regression Modelling
การสร้าง linear regression model มีอยู่ 3 ขั้นตอน ได้แก่:
Fit the model
Make predictions
Evaluate the model performance
.
💪 Step 1. Fit the Model
ในขั้นแรก เราจะสร้าง model ด้วย lm() ซึ่งต้องการ input 2 อย่าง:
lm(formula, data)
formula = สูตรการทำนาย โดยเราต้องกำหนดตัวแปรต้นและตัวแปรตาม
data = ชุดข้อมูลที่ใช้สร้าง model
ในการทำนายราคาเพชร เราจะใช้ lm() แบบนี้:
# Fit the model
linear_reg <- lm(price_log ~ .,
data = train_set)
💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน
ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:
Correlation
t-tests
ANOVA
Reliability
Factor analysis
🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ
💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน
ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:
Correlation
t-tests
ANOVA
Reliability
Factor analysis
🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ
Sepal.Length Sepal.Width
Min. :0.0000 Min. :0.0000
1st Qu.:0.2222 1st Qu.:0.3333
Median :0.4167 Median :0.4167
Mean :0.4287 Mean :0.4406
3rd Qu.:0.5833 3rd Qu.:0.5417
Max. :1.0000 Max. :1.0000
Petal.Length Petal.Width
Min. :0.0000 Min. :0.00000
1st Qu.:0.1017 1st Qu.:0.08333
Median :0.5678 Median :0.50000
Mean :0.4675 Mean :0.45806
3rd Qu.:0.6949 3rd Qu.:0.70833
Max. :1.0000 Max. :1.00000
Species
setosa :50
versicolor:50
virginica :50
จะเห็นว่า:
Columns ที่เป็นตัวเลข มีช่วงอยู่ระหว่าง 0 และ 1
เรายังมี column Species อยู่
.
🪓 Split Data
ในการสร้าง KNN model เราควรแบ่ง dataset ที่มีเป็น 2 ส่วน คือ:
Training set: ใช้สำหรับสร้าง model
Test set: ใช้สำหรับประเมิน model
เราเริ่มแบ่งข้อมูลด้วยการสุ่ม row index ที่จะอยู่ใน training set:
# Set seed for reproducibility
set.seed(2025)
# Create a training index
train_index <- sample(1:nrow(iris_normalised),
0.7 * nrow(iris_normalised))
จากนั้น subset ข้อมูลด้วย row index ที่สุ่มไว้:
# Split the data
train_set <- iris_normalised[train_index, ]
test_set <- iris_normalised[-train_index, ]
.
🏷️ Separate Features From Label
ขั้นตอนสุดท้ายในการเตรียมข้อมูล คือ แยก features หรือ X (columns ที่จะใช้ทำนาย) ออกจาก label หรือ Y (สิ่งที่ต้องการทำนาย):
# Separate features from label
## Training set
train_X <- train_set[, 1:4]
train_Y <- train_set$Species
## Test set
test_X <- test_set[, 1:4]
test_Y <- test_set$Species
4️⃣ Step 4. Train a KNN Model
ขั้นที่สี่เป็นขั้นที่เราสร้าง KNN model ขึ้นมา โดยเรียกใช้ knn() จาก class package
ทั้งนี้ knn() ต้องการ input 3 อย่าง:
train: fatures จาก training set
test: feature จาก test set
cl: label จาก training set
k: จำนวนข้อมูลใกล้เคียงที่จะใช้ทำนายผลลัพธ์
# Train a KNN model
pred <- knn(train = train_X,
test = test_X,
cl = train_Y,
k = 5)
ในตัวอย่าง เรากำหนด k = 5 เพื่อทำนายผลลัพธ์โดยดูจากข้อมูลที่ใกล้เคียง 5 อันดับแรก
5️⃣ Step 5. Evaluate the Model
หลังจากได้ model แล้ว เราประเมินประสิทธิภาพของ model ในการทำนายผลลัพธ์ ซึ่งเราทำได้ง่าย ๆ โดยคำนวณ accuracy หรือสัดส่วนของข้อมูลที่ model ตอบถูกต่อจำนวนข้อมูลทั้งหมด:
Accuracy = Correct predictions / Total predictions
จากผลลัพธ์ เราจะเห็นว่า model มีความแม่นยำสูงถึง 96%
🍩 Bonus: Fine-Tuning
ในบางครั้ง ค่า k ที่เราตั้งไว้ อาจไม่ได้ทำให้เราได้ KNN model ที่ดีที่สุด
แทนที่เราจะแทนค่า k ใหม่ไปเรื่อย ๆ เราสามารถใช้ for loop เพื่อหาค่า k ที่ทำให้เราได้ model ที่ดีที่สุดได้
ให้เราเริ่มจากสร้าง vector ที่มีค่า k ที่ต้องการ:
# Create a set of k values
k_values <- 1:20
และ vector สำหรับเก็บค่า accuracy ของค่า k แต่ละตัว:
# Createa a vector for accuracy results
accuracy_results <- numeric(length(k_values))
แล้วใช้ for loop เพื่อหาค่า accuracy ของค่า k:
# For-loop through the k values
for (i in seq_along(k_values)) {
## Set the k value
k <- k_values[i]
## Create a KNN model
predictions <- knn(train = train_X,
test = test_X,
cl = train_Y,
k = k)
## Create a confusion matrix
cm <- table(Predicted = predictions,
Actual = test_Y)
## Calculate accuracy
accuracy_results[i] <- sum(diag(cm)) / sum(cm)
}
# Find the best k and the corresponding accuracy
best_k <- k_values[which.max(accuracy_results)]
best_accuracy <- max(accuracy_results)
# Print best k and accuracy
cat(paste("Best k:", best_k),
paste("Accuracy:", round(best_accuracy, 2)),
sep = "\n")
ผลลัพธ์:
Best k: 12
Accuracy: 0.98
แสดงว่า ค่า k ที่ดีที่สุด คือ 12 โดยมี accuracy เท่ากับ 98%
นอกจากนี้ เรายังสามารถสร้างกราฟ เพื่อช่วยทำความเข้าใจผลของค่า k ต่อ accuracy:
# Plot the results
plot(k_values,
accuracy_results,
type = "b",
pch = 19,
col = "blue",
xlab = "Number of Neighbors (k)",
ylab = "Accuracy",
main = "KNN Model Accuracy for Different k Values")
grid()
ผลลัพธ์:
จะเห็นได้ว่า k = 12 ให้ accuracy ที่ดีที่สุด และ k = 20 ให้ accuracy ต่ำที่สุด ส่วนค่า k อื่น ๆ ให้ accuracy ในช่วง 93 ถึง 96%
💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน
ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:
Correlation
t-tests
ANOVA
Reliability
Factor analysis
🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ