토픽 모델링 소개

R로 배우는 자연어 처리 입문

Kasey Jones

Research Data Scientist

토픽 모델링

스포츠 기사:

  • 점수
  • 선수 가십
  • 팀 뉴스

잠비아의 날씨:

  • ?
  • ?
R로 배우는 자연어 처리 입문

잠재 디리클레 할당(LDA)

  1. 문서는 여러 토픽의 혼합입니다
    • 팀 뉴스 70%
    • 선수 가십 30%
  2. 토픽은 여러 단어의 혼합입니다
    • 팀 뉴스: trade, pitcher, move, new
    • 선수 가십: angry, change, money

신문에는 특정 주제에 초점을 맞춘 기사가 실립니다.

1 https://en.wikipedia.org/wiki/Latent_Dirichlet_allocation
R로 배우는 자연어 처리 입문

LDA 준비하기

사전 준비:

animal_farm_tokens <- animal_farm %>%
  unnest_tokens(output = "word", token = "words", input = text_column) %>%
  anti_join(stop_words) %>%
  mutate(word = wordStem(word))

문서-단어 행렬:

animal_farm_matrix <- animal_farm_tokens %>%
  count(chapter, word) %>%
  cast_dtm(document = chapter, term = word,
           value = n, weighting = tm::weightTf)
R로 배우는 자연어 처리 입문

LDA

library(topicmodels)
animal_farm_lda <- LDA(train, k = 4, method = 'Gibbs',
                 control = list(seed = 1111))
animal_farm_lda
A LDA_Gibbs topic model with 4 topics.
R로 배우는 자연어 처리 입문

LDA 결과

animal_farm_betas <-
    tidy(animal_farm_lda, matrix = "beta")
animal_farm_betas
# A tibble: 11,004 x 3
   topic term         beta
   <int> <chr>       <dbl>
...
 5     1 abolish 0.0000360
 6     2 abolish 0.00129  
 7     3 abolish 0.000355 
 8     4 abolish 0.0000381
...
sum(animal_farm_betas$beta)
[1] 4
R로 배우는 자연어 처리 입문

토픽별 상위 단어

animal_farm_betas %>%
  group_by(topic) %>%
  slice_max(beta, n = 10) %>%
  arrange(topic, -beta) %>%
  filter(topic == 1)
   topic term          beta
   <int> <chr>        <dbl>
 1     1 napoleon   0.0339 
 2     1 anim       0.0317 
 3     1 windmil    0.0144 
 4     1 squealer   0.0119 
 ...
animal_farm_betas %>%
  group_by(topic) %>%
  slice_max(beta, n = 10) %>%
  arrange(topic, -beta) %>%
  filter(topic == 2)
   topic term        beta
   <int> <chr>      <dbl>
...
 3     2 anim     0.0189 
 ...
 6     2 napoleon 0.0148 
 ...
R로 배우는 자연어 처리 입문

상위 단어 이어서

토픽별 상위 단어를 나열하고 ggplot으로 시각화할 수 있습니다.

1 https://www.tidytextmining.com/topicmodeling.html
R로 배우는 자연어 처리 입문

문서를 토픽으로 라벨링

animal_farm_chapters <- tidy(animal_farm_lda, matrix = "gamma")
animal_farm_chapters %>%
  filter(document == 'Chapter 1')
# A tibble: 4 x 3
  document  topic  gamma
  <chr>     <int>  <dbl>
1 Chapter 1     1 0.157 
2 Chapter 1     2 0.136 
3 Chapter 1     3 0.623 
4 Chapter 1     4 0.0838
R로 배우는 자연어 처리 입문

LDA 연습!

R로 배우는 자연어 처리 입문

Preparing Video For Download...