Archer and Tidy Data Principles (Part 2)

Motivation

The first part left an open door to analyze Archer contents using tf-idf, bag-of-words or some other NLP techniques. Here I’m also taking a lot of ideas from Julia Silge’s blog.

Note: If some images appear too small on your screen you can open them in a new tab to show them in their original size.

Term Frequency

The most basic measure in natural language processing is obviously to just count words. This is a crude way of knowing what a document is about. The problem with counting words, however, is that there are some words (called stopwords) that are always too common, like “the” or “that”. So to create a more meaningful representation what people usually do is to compare the word counts observed in a document with that of a larger body of text.

Tf-idf is the frequency of a term adjusted for how rarely it is used. It is intended to measure how important a word is to a document in a collection (or corpus) of documents.

The inverse document frequency for any given term is defined as: \[idf(\text{term}) = \ln{\left(\frac{n_{\text{documents}}}{n_{\text{documents containing term}}}\right)}\] We can use tidy data principles to approach tf-idf analysis and use consistent, effective tools to quantify how important various terms are in a document that is part of a collection.

What do Archer characters say?

Let’s start by looking at Archer dialogues and examine first term frequency, then tf-idf. I’ll analyze this removing stopwords beforehand.

if (!require("pacman")) install.packages("pacman")
p_load(data.table, tidyr, tidytext, dplyr, ggplot2, viridis, ggstance)
p_load_gh("dgrtwo/widyr")

archer_subs <- as_tibble(fread("../../data/2017-10-13-rick-and-morty-tidy-data/archer_subs.csv"))

archer_subs_tidy <- archer_subs %>% 
  unnest_tokens(word,text) %>% 
  anti_join(stop_words) %>% 
  count(season, word, sort = TRUE)

total_words <- archer_subs_tidy %>% group_by(season) %>% summarize(total = sum(n))
season_words <- left_join(archer_subs_tidy, total_words)

season_words
# A tibble: 32,386 x 4
   season word       n total
   <chr>  <chr>  <int> <int>
 1 S04    archer  1362 18351
 2 S05    archer  1143 17740
 3 S04    lana     880 18351
 4 S05    lana     705 17740
 5 S03    archer   661 16013
 6 S02    archer   638 15722
 7 S05    malory   525 17740
 8 S05    pam      486 17740
 9 S05    cyril    442 17740
10 S02    lana     403 15722
# ... with 32,376 more rows

Let’s look at the distribution of n/total for each season, the number of times a word appears in a season divided by the total number of terms (words) in that season. This is term frequency!

ggplot(season_words, aes(n/total, fill = season)) +
  geom_histogram(alpha = 0.8, show.legend = FALSE) +
  xlim(0, 0.001) +
  labs(title = "Term Frequency Distribution in Archer' Seasons",
       y = "Count") +
  facet_wrap(~season, nrow = 3, scales = "free_y") +
  theme_minimal(base_size = 13) +
  scale_fill_viridis(end = 0.85, discrete = TRUE) +
  theme(strip.text = element_text(hjust = 0)) +
  theme(strip.text = element_text(face = "italic"))

There are very long tails to the right for these dialogues because of the extremely common words. These plots exhibit similar distributions for each season, with many words that occur rarely and fewer words that occur frequently. The idea of tf-idf is to find the important words for the content of each document by decreasing the weight for commonly used words and increasing the weight for words that are not used very much in a collection or corpus of documents, in this case, the group of Archer’ seasons as a whole. Calculating tf-idf attempts to find the words that are important (i.e., common) in a text, but not too common. Let’s do that now.

season_words <- season_words %>%
  bind_tf_idf(word, season, n)

season_words
# A tibble: 32,386 x 7
   season word       n total     tf   idf tf_idf
   <chr>  <chr>  <int> <int>  <dbl> <dbl>  <dbl>
 1 S04    archer  1362 18351 0.0742    0.     0.
 2 S05    archer  1143 17740 0.0644    0.     0.
 3 S04    lana     880 18351 0.0480    0.     0.
 4 S05    lana     705 17740 0.0397    0.     0.
 5 S03    archer   661 16013 0.0413    0.     0.
 6 S02    archer   638 15722 0.0406    0.     0.
 7 S05    malory   525 17740 0.0296    0.     0.
 8 S05    pam      486 17740 0.0274    0.     0.
 9 S05    cyril    442 17740 0.0249    0.     0.
10 S02    lana     403 15722 0.0256    0.     0.
# ... with 32,376 more rows

Notice that idf and thus tf-idf are zero for the extremely common words after removing stopwords. These are all words that appear all the time on every chapter, so the idf term (which will then be the natural log of 1) is zero, and “Rick” and “Morty” are examples of this. The inverse document frequency (and thus tf-idf) is very low (near zero) for words that occur in many of the documents in a collection; this is how this approach decreases the weight for common words. The inverse document frequency will be a higher number for words that occur in fewer of the documents in the collection. Let’s look at terms with high tf-idf.

season_words %>%
  select(-total) %>%
  arrange(desc(tf_idf)) 
# A tibble: 32,386 x 6
   season word         n      tf   idf  tf_idf
   <chr>  <chr>    <int>   <dbl> <dbl>   <dbl>
 1 S03    drake      153 0.00955  2.08 0.0199 
 2 S05    cherlene   250 0.0141   1.39 0.0195 
 3 S03    riley      137 0.00856  2.08 0.0178 
 4 S04    o.s        143 0.00779  2.08 0.0162 
 5 S05    cocaine    123 0.00693  2.08 0.0144 
 6 S05    calderón   113 0.00637  2.08 0.0132 
 7 S03    noah        91 0.00568  2.08 0.0118 
 8 S07    veronica    64 0.00555  2.08 0.0115 
 9 S04    troy        86 0.00469  2.08 0.00975
10 S07    deane       51 0.00442  2.08 0.00919
# ... with 32,376 more rows

Curious about Veronica Deane or Drake? Veronica Deane made an important cameo and she was extremely relevant in one of the seasons. Drake was an astronaut (a tribute to Chris Hadfield?) characterized by Bryan Cranston with a short participation.

Some of the values for idf are the same for different terms because there are 8 documents in this corpus and we are seeing the numerical value for ln(8/1), ln(8/2), etc. Let’s look at a visualization for these high tf-idf words.

plot_tfidf <- season_words %>%
  arrange(desc(tf_idf)) %>%
  mutate(word = factor(word, levels = rev(unique(word))))
  
ggplot(plot_tfidf[1:20, ], aes(tf_idf, word, fill = season, alpha = tf_idf)) +
  geom_barh(stat = "identity") +
  labs(title = "Highest tf-idf words in Archer' Seasons",
       y = NULL, x = "tf-idf") +
  theme_minimal(base_size = 13) +
  scale_alpha_continuous(range = c(0.6, 1), guide = FALSE) +
  scale_x_continuous(expand = c(0, 0)) +
  scale_fill_viridis(end = 0.85, discrete = TRUE) +
  theme(legend.title = element_blank()) +
  theme(legend.justification = c(1, 0),
  legend.position = c(1, 0))

Let’s look at the seasons individually.

plot_tfidf <- plot_tfidf %>% 
  group_by(season) %>% 
  top_n(15) %>% 
  ungroup()

ggplot(plot_tfidf, aes(tf_idf, word, fill = season, alpha = tf_idf)) +
  geom_barh(stat = "identity", show.legend = FALSE) +
  labs(title = "Highest tf-idf words in Archer' Seasons",
       y = NULL, x = "tf-idf") +
  facet_wrap(~season, nrow = 3, scales = "free") +
  theme_minimal(base_size = 13) +
  scale_alpha_continuous(range = c(0.6, 1)) +
  scale_x_continuous(expand = c(0,0)) +
  scale_fill_viridis(end = 0.85, discrete = TRUE) +
  theme(strip.text = element_text(hjust = 0)) +
  theme(strip.text = element_text(face = "italic"))