Generalised Linear Model: วิธีใช้ glm() ในภาษา R เพื่อทำนายข้อมูลที่ไม่ปกติ — Linear, Logistic, และ Poisson Regression

ในบทความนี้ เราจะไปทำความรู้จักกับ generalised linear model (GLM) และวิธีทำ GLM ในภาษา R กัน

ถ้าพร้อมแล้ว ไปเริ่มกันเลย


  1. 🤔 GLM คืออะไร?
  2. 💻 GLM ในภาษา R
  3. ☕ ตัวอย่างข้อมูล: coffee_shop
    1. 1️⃣ Linear Regression
    2. 2️⃣ Logistic Regression
    3. 3️⃣ Poisson Regression
  4. 💪 Summary
  5. 😺 GitHub
  6. 📃 References
  7. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

🤔 GLM คืออะไร?

GLM เป็นเทคนิคทางสถิติที่ใช้ทำนายข้อมูลที่มีการกระจายตัวไม่ปกติ (non-normal distribution) เช่น ข้อมูลที่มีผลลัพธ์เพียง 0 และ 1

GLM ทำนายข้อมูลเหล่านี้โดยการต่อยอดจากสมการเส้นตรง (linear model) และมี 3 องค์ประกอบ ได้แก่:

  1. Family: การกระจายตัวของตัวแปรตาม (y)
  2. Linear predictors: สมการเส้นตัวตรงของตัวแปรต้น (x) หรือตัวแปรทำนาย (predictor)
  3. Link function: function ที่เชื่อมตัวแปรต้นกับตัวแปรตามเข้าด้วยกัน

💻 GLM ในภาษา R

ในภาษา R เราสามารถใช้งาน GLM ได้ผ่าน glm() function ซึ่งต้องการข้อมูล 3 อย่าง:

glm(formula, data, family)
  1. formula = ความสัมพันธ์ระหว่างตัวแปรต้นและตัวแปรตาม ในรูปแบบ y ~ x
  2. data = ชุดข้อมูลที่ใช้ในการวิเคราะห์
  3. family = การกระจายตัวของตัวแปรตาม

จะสังเกตว่า glm() ไม่มี parametre สำหรับ link function ทั้งนี้เป็นเพราะ glm() เรียกใช้ link function ให้อัตโนมัติตาม family ที่เรากำหนด

ทั้งนี้ ประเภทข้อมูล, family, และ link function ที่เราสามารถเรียกใช้ glm() ได้มีดังนี้:

DatafamilyLink Function
Normalgaussianlink = "identity”
Binomialbinomiallink = "logit”
Poissonpoissonlink = "log”
Quasi-poissonquasipoissonlink = "log”
GammaGammalink = "inverse”

เราไปดูตัวอย่างการใช้งาน glm() เพื่อทำนายและแปลผลกัน


☕ ตัวอย่างข้อมูล: coffee_shop

เราจะไปดูตัวอย่างการใช้ glm() เพื่อทำนายข้อมูล 3 ประเภทกัน:

  1. Linear regression
  2. Logistic regression
  3. Poisson regression

โดยเราจะใช้ตัวอย่างเป็นข้อมูลจำลองชื่อ coffee_shop ซึ่งประกอบด้วยข้อมูลการขายจากร้านกาแฟแห่งหนึ่ง และมีรายละเอียดดังนี้:

No.ColumnDescription
1dayวันที่
2tempอุณหภูมิโดยเฉลี่ยของวัน
3promoเป็นวันที่มีโปรโมชัน (มี, ไม่มี)
4weekendเป็นวันหยุดสุดสัปดาห์ (วันหยุด, วันธรรมดา)
5salesยอดขาย
6customersจำนวนลูกค้าในแต่ละวัน
7sold_outขายหมด (หมด, ไม่หมด)

ก่อนวิเคราะห์ข้อมูล เราจะสร้าง coffee_shop ตามนี้:

# Generate mock coffee shop dataset (15 days)

## Set seed for reproducibility
set.seed(123)

## Generate
coffee_shop <- data.frame(
  
  ## Generate 15 days
  day = 1:15,
  
  ## Generate daily temperature
  temp = round(rnorm(15,
                     mean = 25,
                     sd = 5),
               1),
  
  ## Generate promotion day
  promo = sample(c(0, 1),
                 15,
                 replace = TRUE),
  
  ## Generate weekend
  weekend = c(0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1),
  
  ## Generate the number of sales
  sales = round(rnorm(15,
                      mean = 300,
                      sd = 50)),
  
  ## Generate the number of daily customers
  customers = rpois(15,
                    lambda = 80),
  
  ## Generate sold-out
  sold_out = sample(c(0, 1),
                    15,
                    replace = TRUE)
)

## Convert binary variables to factors
coffee_shop$promo <- factor(coffee_shop$promo,
                            levels = c(0, 1),
                            labels = c("NoPromo", "Promo"))

coffee_shop$weekend <- factor(coffee_shop$weekend,
                              levels = c(0, 1),
                              labels = c("Weekday", "Weekend"))

coffee_shop$sold_out <- factor(coffee_shop$sold_out,
                               levels = c(0, 1),
                               labels = c("No", "Yes"))

## View the dataset
print(coffee_shop)

ผลลัพธ์:

   day temp   promo weekend sales customers sold_out
1    1 22.2 NoPromo Weekday   246        73      Yes
2    2 23.8   Promo Weekday   296        76      Yes
3    3 32.8 NoPromo Weekday   354        83       No
4    4 25.4   Promo Weekday   293        87       No
5    5 25.6   Promo Weekend   242        78      Yes
6    6 33.6 NoPromo Weekend   259        91      Yes
7    7 27.3 NoPromo Weekday   334        71      Yes
8    8 18.7 NoPromo Weekday   284        76       No
9    9 21.6 NoPromo Weekday   234        72      Yes
10  10 22.8   Promo Weekend   270        79       No
11  11 31.1 NoPromo Weekend   294        82      Yes
12  12 26.8   Promo Weekday   344        79       No
13  13 27.0   Promo Weekday   292        79       No
14  14 25.6 NoPromo Weekday   316        92       No
15  15 22.2 NoPromo Weekend   139        77      Yes

เราไปดูวิธีทำนายข้อมูลกัน

.

1️⃣ Linear Regression

Linear regression เป็นการทำนายข้อมูล numeric เช่น ยอดขาย (sales) ซึ่งเราสามารถใช้ glm() ทำนายได้ดังนี้:

# Create a regression model with glm()
linear_reg <- glm(sales ~ temp + promo + weekend,
                  data = coffee_shop,
                  family = gaussian)

เราสามารถดู model ได้ด้วย summary():

# Get model summary
summary(linear_reg)

ผลลัพธ์:

Call:
glm(formula = sales ~ temp + promo + weekend, family = gaussian, 
    data = coffee_shop)

Coefficients:
               Estimate Std. Error t value Pr(>|t|)   
(Intercept)      96.599     59.669   1.619  0.13375   
temp              7.703      2.283   3.373  0.00621 **
promoPromo       23.014     18.537   1.241  0.24025   
weekendWeekend  -73.444     19.654  -3.737  0.00328 **
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for gaussian family taken to be 1222.243)

    Null deviance: 39702  on 14  degrees of freedom
Residual deviance: 13445  on 11  degrees of freedom
AIC: 154.54

Number of Fisher Scoring iterations: 2

จากผลลัพธ์ เราจะเห็นความสำคัญของตัวแปรต้นและ coefficient ซึ่งระบุการเปลี่ยนแปลงของตัวแปรตามการเปลี่ยนของตัวแปรต้น:

  • ตัวแปรที่สามารถทำนาย sales ได้อย่างมีนัยสำคัญ คือ temp และ weekend (สังเกตจาก **)
  • promo ไม่สามารถทำนาย sales ได้อย่างมีนัยสำคัญ
  • Coefficient ของ temp คือ 7.70 ซึ่งหมายถึง อุณหภูมิเปลี่ยน 1 หน่วย ยอดขายจะเพิ่มขึ้น 7.70 หน่วย
  • Coefficient ของ weekend คือ -73.44 ซึ่งหมายถึง วันหยุดสุดสัปดาห์ ยอดขายจะลดลง 73.44 หน่วย

.

2️⃣ Logistic Regression

Logistic regression เป็นการทำนายข้อมูลที่เป็นมีผลลัพธ์เพียง 2 ค่า เช่น:

  • ใช่, ไม่ใช่
  • ผ่าน, ไม่ผ่าน
  • ตรง, ไม่ตรง

ใน coffee_shop เรามี sold_out ซึ่งเราสามารถทำนายด้วย logistic regression ด้วย glm() ได้แบบนี้:

# Create a logistic regression model
log_reg <- glm(sold_out ~ temp + promo + weekend,
               data = coffee_shop,
               family = binomial)

จากนั้น ดู model ด้วย summary():

# Get model summary
summary(log_reg)

ผลลัพธ์:

Call:
glm(formula = sold_out ~ temp + promo + weekend, family = binomial, 
    data = coffee_shop)

Coefficients:
               Estimate Std. Error z value Pr(>|z|)
(Intercept)     1.30934    3.92442   0.334    0.739
temp           -0.04448    0.15189  -0.293    0.770
promoPromo     -1.73681    1.31881  -1.317    0.188
weekendWeekend  2.15038    1.45643   1.476    0.140

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 20.728  on 14  degrees of freedom
Residual deviance: 16.426  on 11  degrees of freedom
AIC: 24.426

Number of Fisher Scoring iterations: 4

จะเห็นได้ว่า หน้าตาผลลัพธ์คล้ายกับ linear regression แต่สิ่งที่แตกต่างกัน คือ coefficient อยู่ในรูป log-odd ซึ่งเราสามารถถอดรูปได้ด้วย exp() เพื่อแปลผล:

# Transform coefficient
exp(coef(log_reg))

ผลลัพธ์:

   (Intercept)           temp     promoPromo weekendWeekend 
     3.7037124      0.9564938      0.1760812      8.5881237

เราสามารถแปลผลได้ดังนี้:

PredictorCoefficientInterpretation
temp0.96เมื่ออุณหภูมิสูงขึ้น 1 หน่วย ร้านมีโอกาสขายหมดเพิ่มขึ้น 0.96
promo0.18เมื่อมีโปรโมชัน ร้านมีโอกาสขายหมดเพิ่มขึ้น 0.18
weekend8.59เมื่อเป็นวันสุดสัปดาห์ ร้านมีโอกาสขายหมดเพิ่มขึ้น 8.59

.

3️⃣ Poisson Regression

Poisson regression เป็นการทำนายข้อมูลการนับ (count data) หรือข้อมูลที่เกิดขึ้นในช่วงเวลาที่กำหนด เช่น:

  • จำนวนรถบนถนนในแต่ละชั่วโมง
  • จำนวนข้อความที่ได้รับใน 1 วัน
  • จำนวนสินค้าที่ขายได้ใน 3 เดือน

ใน coffee_shop เรามี customers ซึ่งสามารถทำนาย poisson regression ผ่าน glm() ได้ดังนี้:

# Create a poisson regression model
poisson_reg <- glm(customers ~ temp + promo + weekend,
                   data = coffee_shop,
                   family = poisson)

ดู model:

# Get model summary
summary(poisson_reg)

ผลลัพธ์:

Call:
glm(formula = customers ~ temp + promo + weekend, family = poisson, 
    data = coffee_shop)

Coefficients:
               Estimate Std. Error z value Pr(>|z|)    
(Intercept)    4.108939   0.192499  21.345   <2e-16 ***
temp           0.010077   0.007299   1.381    0.167    
promoPromo     0.010327   0.059616   0.173    0.862    
weekendWeekend 0.012692   0.062739   0.202    0.840    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 7.0199  on 14  degrees of freedom
Residual deviance: 4.8335  on 11  degrees of freedom
AIC: 106.06

Number of Fisher Scoring iterations: 3

Coefficient ของ poisson regression อยู่ในรูป log เช่นเดียวกับ logistic regression ดังนั้น เราจะถอดรูปด้วย exp() ก่อนแปลผล:

# Transform the coefficients
exp(coef(poisson_reg))

ผลลัพธ์:

   (Intercept)           temp     promoPromo weekendWeekend 
     60.882073       1.010127       1.010381       1.012773

จะเห็นได้ว่า coefficient ของทั้ง 3 ตัวแปรต้นอยู่ที่ 1.01 ซึ่งหมายถึง การเปลี่ยนแปลงตัวแปรต้นตัวใดตัวหนึ่ง ทำให้จำนวนลูกค้าเพิ่มขึ้น 1 คน


💪 Summary

ในบทความนี้ เราได้ไปทำความรู้จักกับ GLM ซึ่งเป็นเทคนิคทางสถิติที่ใช้ทำนายข้อมูลที่ไม่ปกติ และได้ดูวิธีการใช้ glm() function ในภาษา R เพื่อทำนายข้อมูล 3 ประเภท:

  1. Linear regression
  2. Logistic regression
  3. Poisson regression

😺 GitHub

ดู code ทั้งหมดในบทความนี้ได้ที่ GitHub


📃 References

What is GLM?

GLM in R:


✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

📕 ขอฝากหนังสือเล่มแรกในชีวิตด้วยนะครับ 😆

🙋 ใครที่กำลังเรียนจิตวิทยาหรือทำงานสายจิตวิทยา และเบื่อที่ต้องใช้ software ราคาแพงอย่าง SPSS และ Excel เพื่อทำข้อมูล

💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน

ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:

  • Correlation
  • t-tests
  • ANOVA
  • Reliability
  • Factor analysis

🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ

แล้วทุกคนจะแปลกใจว่า ทำไมภาษา R ง่ายขนาดนี้ 🙂‍↕️

👉 สนใจดูรายละเอียดหนังสือได้ที่ meb:

Comments

One response to “Generalised Linear Model: วิธีใช้ glm() ในภาษา R เพื่อทำนายข้อมูลที่ไม่ปกติ — Linear, Logistic, และ Poisson Regression”

Leave a reply to Machine Learning in R: รวบรวม 13 บทความสอนสร้าง machine learning ในภาษา R – Shi no Shigoto Cancel reply