Fitting Topic Models

Data preparation and model fitting code for topics.

Kris Sankaran (UW Madison)
2021-04-06

Reading, Recording, Rmarkdown

library("dplyr")
library("ggplot2")
library("gutenbergr")
library("stringr")
library("tidyr")
library("tidytext")
library("topicmodels")
theme479 <- theme_minimal() + 
  theme(
    panel.grid.minor = element_blank(),
    panel.background = element_rect(fill = "#f7f7f7"),
    panel.border = element_rect(fill = NA, color = "#0c0c0c", size = 0.6),
    legend.position = "bottom"
  )
theme_set(theme479)
  1. There are several packages in R that can be used to fit topic models. We will use LDA as implemented in the topicmodels package, which expects input to be structured as a DocumentTermMatrix, a special type of matrix that stores the counts of words (columns) across documents (rows). In practice, most of the effort required to fit a topic model goes into transforming the raw data into a suitable DocumentTermMatrix.

  2. To illustrate this process, let’s consider the “Great Library Heist” example from the reading. We imagine that a thief has taken four books — Great Expectations, Twenty Thousand Leagues Under The Sea, War of the Worlds, and Pride & Prejudice — and torn all the chapters out. We are left with pieces of isolated pieces of text and have to determine from which book they are from. The block below downloads all the books into an R object.

titles <- c("Twenty Thousand Leagues under the Sea", 
            "The War of the Worlds",
            "Pride and Prejudice", 
            "Great Expectations")
books <- gutenberg_works(title %in% titles) %>%
  gutenberg_download(meta_fields = "title")
books
# A tibble: 53,205 x 3
   gutenberg_id text                                    title         
          <int> <chr>                                   <chr>         
 1           36 "The War of the Worlds"                 The War of th…
 2           36 ""                                      The War of th…
 3           36 "by H. G. Wells [1898]"                 The War of th…
 4           36 ""                                      The War of th…
 5           36 ""                                      The War of th…
 6           36 "     But who shall dwell in these wor… The War of th…
 7           36 "     inhabited? .  .  .  Are we or th… The War of th…
 8           36 "     World? .  .  .  And how are all … The War of th…
 9           36 "          KEPLER (quoted in The Anato… The War of th…
10           36 ""                                      The War of th…
# … with 53,195 more rows
  1. Since we imagine that the word distributions are not equal across the books, topic modeling is a reasonable approach for discovering the books associated with each chapter. Note that, in principle, other clustering and dimensionality reduction procedures could also work.

  2. First, let’s simulate the process of tearing the chapters out. We split the raw texts anytime the word “Chapter” appears. We will keep track of the book names for each chapter, but this information is not passed into the topic modeling algorithm.

by_chapter <- books %>%
  group_by(title) %>%
  mutate(
    chapter = cumsum(str_detect(text, regex("chapter", ignore_case = TRUE)))
  ) %>%
  group_by(title, chapter) %>%
  mutate(n = n()) %>%
  filter(n > 5) %>%
  ungroup() %>%
  unite(document, title, chapter)
  1. As it is, the text data are long character strings, giving actual text from the novels. To fit LDA, we only need counts of each word within each chapter – the algorithm throws away information related to word order. To derive word counts, we first split the raw text into separate words using the unest_tokens function in the tidytext package. Then, we can count the number of times each word appeared in each document using count, a shortcut for the usual group_by and summarize(n = n()) pattern.
word_counts <- by_chapter %>%
  unnest_tokens(word, text) %>%
  anti_join(stop_words) %>%
  count(document, word) # shortcut for group_by(document, word) %>% summarise(n = n())

word_counts
# A tibble: 51,361 x 3
   document             word       n
   <chr>                <chr>  <int>
 1 Great Expectations_0 1          1
 2 Great Expectations_0 1867       1
 3 Great Expectations_0 2          3
 4 Great Expectations_0 4          1
 5 Great Expectations_0 _also      1
 6 Great Expectations_0 _am_       2
 7 Great Expectations_0 _and_      1
 8 Great Expectations_0 _are_      2
 9 Great Expectations_0 _betsy     1
10 Great Expectations_0 _both_     1
# … with 51,351 more rows
  1. These words counts are still not in a format compatible with conversion to a DocumentTermMatrix. The issue is that the DocumentTermMatrix expects words to be arranged along columns, but currently they are stored across rows. The line below converts the original “long” word counts into a “wide” DocumentTermMatrix in one step. Across these 4 books, we have 65 chapters and a vocabulary of size 18325.
chapters_dtm <- word_counts %>%
  cast_dtm(document, word, n)
chapters_dtm
<<DocumentTermMatrix (documents: 65, terms: 18312)>>
Non-/sparse entries: 51361/1138919
Sparsity           : 96%
Maximal term length: 19
Weighting          : term frequency (tf)
  1. Once the data are in this format, we can use the LDA function to fit a topic model. We choose \(K = 4\) topics because we expect that each topic will match a book. Different hyperparameters can be set using the control argument.
chapters_lda <- LDA(chapters_dtm, k = 4, control = list(seed = 1234))
chapters_lda
A LDA_VEM topic model with 4 topics.
  1. There are two types of outputs produced by the LDA model: the topic word distributions (for each topic, which words are common?) and the document-topic memberships (from which topics does a document come from?). For visualization, it will be easiest to extract these parameters using the tidy function, specifying whether we want the topics (beta) or memberships (gamma).
topics <- tidy(chapters_lda, matrix = "beta")
memberships <- tidy(chapters_lda, matrix = "gamma")
  1. This tidy approach is preferable to extracting the parameters directly from the fitted model (e.g., using chapters_lda@gamma) because it ensures the output is a tidy data.frame, rather than a matrix. Tidy data.frames are easier to visualize using ggplot2.
# highest weight words per topic
topics %>%
  arrange(topic, -beta)
# A tibble: 73,248 x 3
   topic term        beta
   <int> <chr>      <dbl>
 1     1 captain  0.0154 
 2     1 nautilus 0.0131 
 3     1 sea      0.00882
 4     1 nemo     0.00875
 5     1 ned      0.00807
 6     1 conseil  0.00684
 7     1 land     0.00605
 8     1 water    0.00595
 9     1 sir      0.00495
10     1 day      0.00371
# … with 73,238 more rows
# topic memberships per document
memberships %>%
  arrange(document, topic)
# A tibble: 260 x 3
   document                topic       gamma
   <chr>                   <int>       <dbl>
 1 Great Expectations_0        1 0.000000336
 2 Great Expectations_0        2 0.000000336
 3 Great Expectations_0        3 0.996      
 4 Great Expectations_0        4 0.00440    
 5 Pride and Prejudice_0       1 0.00159    
 6 Pride and Prejudice_0       2 0.662      
 7 Pride and Prejudice_0       3 0.00159    
 8 Pride and Prejudice_0       4 0.335      
 9 Pride and Prejudice_100     1 0.0000394  
10 Pride and Prejudice_100     2 0.0000394  
# … with 250 more rows