0Pricing
R Academy · บทเรียน

การสร้างโมเดลหัวข้อด้วย LDA

ค้นหาหัวข้อแฝงในคลังเอกสารโดยใช้แพ็กเกจ topicmodels

การสร้างโมเดลหัวข้อด้วย LDA เป็นบทเรียน R Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน R Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส R Academy มีบทเรียนทั้งหมด 4 บทเรียน

การสร้างแบบจำลองหัวข้อคืออะไร

การสร้างแบบจำลองหัวข้อเป็นเทคนิคการเรียนรู้ของเครื่องแบบไม่มีผู้สอนที่ค้นหาโครงสร้างหัวข้อแฝงในคลังข้อความ การจัดสรรแบบไดริชเลต์แฝง (LDA) สมมติว่าแต่ละเอกสารเป็นส่วนผสมของหัวข้อ K หัวข้อ และแต่ละหัวข้อเป็นการแจกแจงความน่าจะเป็นเหนือคำต่าง ๆ

# LDA key assumptions:
# 1. Each document is a mixture of K topics
# 2. Each topic is a distribution over all vocabulary words
# 3. Words are generated by first picking a topic, then a word from that topic

# Example: K=2 topics in a corpus about tech and cooking
# Topic 1 (Tech):    neural(0.15) python(0.12) algorithm(0.10) ...
# Topic 2 (Cooking): recipe(0.14) flour(0.11) bake(0.10) ...

# A document about 'AI-generated recipes' might be:
# 70% Topic 1 (Tech) + 30% Topic 2 (Cooking)

cat('LDA parameters:\n')
cat('K = number of topics (you choose)\n')
cat('alpha = document-topic sparsity prior\n')
cat('beta  = topic-word sparsity prior\n')

DocumentTermMatrix จาก tm

LDA ต้องใช้เมทริกซ์เอกสาร-คำ (DTM): แถวคือเอกสาร คอลัมน์คือคำ และเซลล์คือจำนวนครั้งที่คำปรากฏ แพ็กเกจ tm ที่ใช้ DocumentTermMatrix() หรือ cast_dtm() ของ tidytext ต่างก็สร้างรูปแบบนี้ได้

library(tm)

# Build a corpus from raw text
docs <- c(
  'machine learning neural networks training algorithms',
  'deep learning gradient backpropagation optimizer',
  'python scikit numpy pandas machine learning',
  'database sql tables indexes queries joins',
  'relational schema normalization foreign primary',
  'nosql mongodb document store redis queries'
)

corpus <- Corpus(VectorSource(docs))
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, removeWords, stopwords('english'))
corpus <- tm_map(corpus, stripWhitespace)

dtm <- DocumentTermMatrix(corpus)
cat('DTM shape:', nrow(dtm), 'docs x', ncol(dtm), 'terms\n')
cat('Sparsity: ', round(tm::sparsity(dtm) * 100, 1), '%\n')

cast_dtm จาก tidytext

cast_dtm(document, term, value) แปลงทิบเบิลจำนวนคำแบบเป็นระเบียบให้เป็น DocumentTermMatrix ที่ใช้ร่วมกับแพ็กเกจ topicmodels ได้โดยตรง วิธีนี้ช่วยให้ pipeline ของคุณยังคงอยู่ในรูปแบบ tidyverse

library(tidytext)
library(dplyr)

# Tidy corpus
corpus <- tibble::tibble(
  doc_id = c(rep(1, 3), rep(2, 3), rep(3, 3), rep(4, 3)),
  text   = c(
    'neural networks deep learning training',
    'gradient descent backpropagation optimizer',
    'machine learning algorithms classification',
    'database sql tables queries indexes',
    'relational schema normalization joins',
    'foreign primary key constraints transactions',
    'recipe bake flour butter oven',
    'cooking temperature simmer saute ingredients',
    'kitchen knife herbs spices garnish'
  )
)

dtm <- corpus |>
  unnest_tokens(word, text) |>
  anti_join(tidytext::stop_words, by = 'word') |>
  count(doc_id, word) |>
  cast_dtm(doc_id, word, n)

cat('DTM:', nrow(dtm), 'docs x', ncol(dtm), 'terms\n')

LDA(dtm, k = 5): การปรับแบบจำลอง

LDA(dtm, k = K, control = list(seed = 42)) ปรับแบบจำลอง LDA ที่มีหัวข้อ K หัวข้อโดยใช้การสุ่มตัวอย่างแบบกิบส์หรือ VEM ควรกำหนด seed เสมอเพื่อให้ทำซ้ำผลลัพธ์ได้ เนื่องจาก LDA เป็นกระบวนการสุ่ม และผลลัพธ์จะแตกต่างกันในแต่ละครั้งหากไม่กำหนดค่า seed คงที่

library(tidytext)
library(dplyr)
library(topicmodels)

# Build DTM
corpus <- tibble::tibble(
  doc_id = c(rep(1,3), rep(2,3), rep(3,3), rep(4,3), rep(5,3), rep(6,3)),
  text = c(
    'neural networks deep gradient','backpropagation training optimizer','learning model layers',
    'database sql queries indexes','relational tables joins foreign','schema normalization constraints',
    'recipe flour bake butter','cooking temperature oven simmer','kitchen knife herbs spices'
  )[rep(c(1,2,3,4,5,6), each=1)]
)

dtm <- corpus |>
  unnest_tokens(word, text) |>
  count(doc_id, word) |>
  cast_dtm(doc_id, word, n)

# Fit LDA with k=3 topics
lda_model <- LDA(dtm, k = 3, control = list(seed = 42))
cat('LDA model fitted: k=3 topics\n')
cat('Class:', class(lda_model), '\n')

tidy(lda, matrix = 'beta'): ความน่าจะเป็นหัวข้อต่อคำ

tidy(lda_model, matrix = 'beta') แยกความน่าจะเป็นของหัวข้อต่อคำ (เมทริกซ์เบตา) ออกมา แต่ละแถวแสดงความน่าจะเป็นที่คำหนึ่ง ๆ ถูกสร้างขึ้นโดยหัวข้อหนึ่ง ๆ คำที่มีความน่าจะเป็นสูงจะบ่งบอกว่าแต่ละหัวข้อเกี่ยวกับอะไร

library(topicmodels)
library(tidytext)
library(dplyr)

# Using the built-in AssociatedPress dataset
data('AssociatedPress', package = 'topicmodels')

lda <- LDA(AssociatedPress[1:50, ], k = 4, control = list(seed = 1234))

# Per-word topic probabilities (beta)
beta_tbl <- tidy(lda, matrix = 'beta')
cat('Beta matrix rows:', nrow(beta_tbl), '\n')
cat('Columns:', names(beta_tbl), '\n')

# Top words per topic
top_terms <- beta_tbl |>
  group_by(topic) |>
  slice_max(beta, n = 5) |>
  ungroup()

cat('\nTop 5 words per topic:\n')
print(top_terms)

การแสดงคำของหัวข้อเป็นภาพ

แสดงคำ N อันดับแรกของแต่ละหัวข้อเป็นแผนภูมิแท่งแบบแบ่งช่อง เรียงลำดับภายในแต่ละหัวข้อตามค่าเบตาด้วย reorder_within() และ scale_x_reordered() จาก tidytext เพื่อให้แต่ละช่องมีลำดับอิสระที่ถูกต้อง

library(topicmodels)
library(tidytext)
library(dplyr)
library(ggplot2)

data('AssociatedPress', package = 'topicmodels')
lda <- LDA(AssociatedPress[1:100, ], k = 4, control = list(seed = 42))

tidy(lda, matrix = 'beta') |>
  group_by(topic) |>
  slice_max(beta, n = 8) |>
  ungroup() |>
  mutate(term = reorder_within(term, beta, topic)) |>
  ggplot(aes(term, beta, fill = factor(topic))) +
    geom_col(show.legend = FALSE) +
    facet_wrap(~topic, scales = 'free') +
    scale_x_reordered() +
    coord_flip() +
    labs(x = NULL, y = 'Beta', title = 'Top Words per LDA Topic') +
    theme_minimal(base_size = 10)

tidy(lda, matrix = 'gamma'): ความน่าจะเป็นหัวข้อต่อเอกสาร

tidy(lda_model, matrix = 'gamma') แยกความน่าจะเป็นของหัวข้อต่อเอกสาร (เมทริกซ์แกมมา) ออกมา แต่ละแถวแสดงสัดส่วนของเอกสารที่ประมาณว่ามาจากหัวข้อหนึ่ง ๆ เอกสารที่มีค่าแกมมาสำหรับหัวข้อ 2 สูงจะถือว่าเกี่ยวกับหัวข้อ 2

library(topicmodels)
library(tidytext)
library(dplyr)

data('AssociatedPress', package = 'topicmodels')
lda <- LDA(AssociatedPress[1:30, ], k = 3, control = list(seed = 99))

# Per-document topic proportions (gamma)
gamma_tbl <- tidy(lda, matrix = 'gamma')
cat('Gamma matrix rows:', nrow(gamma_tbl), '\n')

# Dominant topic per document
dominant_topic <- gamma_tbl |>
  group_by(document) |>
  slice_max(gamma, n = 1) |>
  ungroup()

cat('\nDominant topic per document (first 8):\n')
print(head(dominant_topic, 8))

การเลือก K: จำนวนหัวข้อ

LDA กำหนดให้คุณระบุค่า K ล่วงหน้า แนวทางทั่วไป ได้แก่ (1) ค่า perplexity — ค่าที่ต่ำกว่าดีกว่า แต่จะลดลงอย่างต่อเนื่องเมื่อ K เพิ่มขึ้น (2) คะแนนความสอดคล้อง (แพ็กเกจ ldatuning) (3) ความรู้เฉพาะสาขา และ (4) ทดลองใช้ K = 5, 10, 20 แล้วตรวจสอบรายการคำด้วยตนเอง

library(topicmodels)
library(tidytext)

data('AssociatedPress', package = 'topicmodels')

# Evaluate perplexity for K = 2, 3, 4, 5
k_values <- 2:5
perplexities <- vapply(k_values, function(k) {
  model <- LDA(AssociatedPress[1:50, ], k = k,
               control = list(seed = 42))
  perplexity(model)
}, numeric(1))

results <- data.frame(k = k_values, perplexity = round(perplexities, 1))
cat('Perplexity by K:\n')
print(results)
cat('\nNote: lower perplexity = better fit to training data\n')

การตั้งชื่อหัวข้อ

LDA สร้างหัวข้อที่ไม่มีชื่อกำกับ (1, 2, 3…) นักวิเคราะห์ต้องตั้งชื่อให้แต่ละหัวข้อโดยตรวจสอบคำอันดับต้น ๆ สร้างตารางค้นคืนที่จับคู่หมายเลขหัวข้อกับชื่ออธิบาย แล้วเชื่อมตารางนั้นเข้ากับผลลัพธ์

library(topicmodels)
library(tidytext)
library(dplyr)

data('AssociatedPress', package = 'topicmodels')
lda <- LDA(AssociatedPress[1:100, ], k = 4, control = list(seed = 7))

# Top 5 words per topic for manual labelling
tidy(lda, matrix = 'beta') |>
  group_by(topic) |>
  slice_max(beta, n = 5) |>
  summarise(top_words = paste(term, collapse = ', ')) |>
  print()

# After inspecting top words, assign human-readable labels
topic_labels <- tibble::tibble(
  topic = 1:4,
  label = c('Politics', 'Economy', 'Sports', 'Science')  # your interpretation
)

cat('\nTopic labels assigned (example):\n')
print(topic_labels)

LDA กับคลังข้อความแบบกำหนดเอง

ต่อไปนี้คือ pipeline ของ LDA แบบครบตั้งแต่ต้นจนจบบนคลังข้อความแบบกำหนดเอง: แบ่งข้อความเป็นโทเค็น สร้าง DTM ปรับ LDA แยกเมทริกซ์เบตา และแสดงคำอันดับต้น ๆ ของแต่ละหัวข้อ

library(tidytext)
library(dplyr)
library(topicmodels)

# 9 documents across 3 latent topics
docs <- tibble::tibble(
  id   = 1:9,
  text = c(
    'machine learning neural deep training',
    'algorithm gradient backpropagation network',
    'python tensorflow keras model layers',
    'database sql relational tables queries',
    'joins indexes schema foreign primary',
    'transactions normalization constraints',
    'recipe ingredients bake flour butter',
    'cooking temperature simmer oven saute',
    'kitchen knife herbs spices garnish'
  )
)

dtm <- docs |>
  unnest_tokens(word, text) |>
  count(id, word) |>
  cast_dtm(id, word, n)

lda <- LDA(dtm, k = 3, control = list(seed = 123))

tidy(lda, 'beta') |>
  group_by(topic) |>
  slice_max(beta, n = 4) |>
  summarise(words = paste(term, collapse = ', ')) |>
  print()

ข้อจำกัดของ LDA

LDA สมมติให้ใช้แบบจำลองถุงคำ (ไม่สนใจลำดับคำ) หัวข้อคงที่ตลอดทั้งคลังข้อความ และต้องเลือกค่า K ไว้ล่วงหน้า สำหรับหัวข้อแบบพลวัตหรือแบบลำดับชั้น ให้พิจารณา STM (แบบจำลองหัวข้อเชิงโครงสร้าง) หรือ CTM (แบบจำลองหัวข้อสหสัมพันธ์) ซึ่งมีอยู่ในแพ็กเกจ stm

# LDA assumptions and limitations
limitations <- data.frame(
  Assumption = c(
    'Bag of words', 'Fixed K', 'Topic independence',
    'Static topics', 'No metadata'
  ),
  Alternative = c(
    'word2vec / BERT',
    'ldatuning for K selection',
    'CTM (Correlated Topic Model)',
    'DTM (Dynamic Topic Model)',
    'STM (Structural Topic Model)'
  )
)

print(limitations, row.names = FALSE)

ตรวจสอบความเข้าใจอย่างรวดเร็ว

ใน LDA เมทริกซ์ เบตา แสดงถึงอะไร

ทบทวน: การสร้างแบบจำลองหัวข้อด้วย LDA

ประเด็นสำคัญ:

  • LDA ค้นหาหัวข้อแฝง K หัวข้อในรูปการแจกแจงคำจากเมทริกซ์เอกสาร-คำ
  • สร้าง DTM ด้วย cast_dtm(document, word, n) (tidytext) หรือ DocumentTermMatrix() (tm)
  • LDA(dtm, k = K, control = list(seed = 42)) ใช้ปรับแบบจำลอง
  • tidy(lda, 'beta') = ความน่าจะเป็นของหัวข้อต่อคำ (สิ่งที่กำหนดแต่ละหัวข้อ)
  • tidy(lda, 'gamma') = สัดส่วนหัวข้อต่อเอกสาร (สิ่งที่เอกสารแต่ละฉบับเกี่ยวข้อง)
  • ใช้ค่า perplexity หรือคะแนนความสอดคล้องเพื่อช่วยเลือกค่า K
  • ตรวจสอบคำอันดับต้น ๆ ด้วยตนเองเสมอเพื่อกำหนดชื่อหัวข้อ
library(topicmodels)
library(tidytext)
library(dplyr)

data('AssociatedPress', package = 'topicmodels')
lda <- LDA(AssociatedPress[1:20, ], k = 2, control = list(seed = 1))

tidy(lda, 'beta') |>
  group_by(topic) |>
  slice_max(beta, n = 3) |>
  summarise(top_words = paste(term, collapse = ', ')) |>
  print()

คำถามที่พบบ่อย

บทเรียน “การสร้างโมเดลหัวข้อด้วย LDA” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การสร้างโมเดลหัวข้อด้วย LDA” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส R Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส R Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การสร้างโมเดลหัวข้อด้วย LDA”

ค้นหาหัวข้อแฝงในคลังเอกสารโดยใช้แพ็กเกจ topicmodels คุณปฏิบัติ R Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน R Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน R Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน

บทเรียน “การสร้างโมเดลหัวข้อด้วย LDA” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน R Academy นี้ได้ไหม

ได้ บทเรียน R Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การตัดคำเป็นโทเคนและการลบคำหยุด
  2. TF-IDF และการวิเคราะห์ความถี่ของคำ
  3. การวิเคราะห์ความรู้สึกใน R
  4. การสร้างโมเดลหัวข้อด้วย LDA
← กลับไปที่ R Academy