Milestone Report

Task 1: Data processing/cleaning

Sampling

To get a representation of data from each of the three sources, I chose to sample equal numbers of lines from each sample. This was straightforward to implement but glosses over that lines from each file might have different numbers of words; for this analysis I chose to disregard this factor.

Code
set.seed(1234)

blogs_path <- "final/en_US/en_US.blogs.txt"
news_path <- "final/en_US/en_US.news.txt"
twitter_path <- "final/en_US/en_US.twitter.txt"

sample_corpus <- function(path, n = 100000) {
  file_length <- R.utils::countLines(con <- file(path, "rb")); close(con)
  data <- readLines(con <- file(path, "rb"))[sample(1:file_length, n, replace = FALSE)]; close(con)
  data
}

if (!file.exists("data/data.csv")) {
  data_blogs <- sample_corpus(blogs_path)
  data_news <- sample_corpus(news_path)
  data_twitter <- sample_corpus(twitter_path)
  data <- c(data_blogs, data_news, data_twitter)
  write_csv(data.frame(lines = data), "data/data.csv")
}

data <- read_csv("data/data.csv", show_col_types = FALSE)

Cleaning data

Next I opted to remove all punctuation as I am not planning on running any sentiment analysis, but rather solely prediction of next words. By the same logic, I also chose to remove numeric characters - when predicting the next line in a message a specific number is not a useful item to predict. Finally, I changed all letters to lowercase to remove any ambiguity between phrases such as “i” and “I” or “pittsburgh” and “Pittsburgh.

Code
# Remove anything not [a-zA-Z], space, or apostrophe
data <- data$lines %>% gsub('[^[:alpha:][:space:]\']', '', .) %>%
  tolower()

data[1:5]
[1] "he looked back at me his eyes were as dark as coal"                                                                                                                                                                                                  
[2] "you've set up a problem without stakes why does she care who the voice on the phone is why would she even listen to him past hello"                                                                                                                  
[3] "yvonne strahovski  peg mooring"                                                                                                                                                                                                                      
[4] "what are you like with medical procedures when it comes to your kids"                                                                                                                                                                                
[5] "but i believe that the dna in the rainbow trout was created directly by god at a time in the past replacements for it are no longer being made therefore to wipe it out of an existence would be to destroy the work of the greatest artist there is"

A potential shortcoming of this approach is that I am not using an interesting piece of information: beginning and end of sentence. In the structure of the English language, there are likely phrases that show up more often in the beginning, middle, or end of a sentence. Ultimately, for the model I am planning on building, simply predicting the next word, I am uncertain of the need for this and the additional overhead that the algorithm would run through. In a future implementation of this model, I would like to incorporate the beginning/end of sentence information.

Profanity Filtering

I searched for a list of profanity that included a wide assortment of negative words that I didn’t want to include in the corpus. These were then removed from the data.

Code
if (!file.exists("swearWords.txt")) {
  download.file("http://www.bannedwordlist.com/lists/swearWords.txt", "swearWords.txt")
}
swear_words <- read_csv("swearWords.txt", col_names = FALSE, show_col_types = FALSE)

word_match_list = function(...) {
  words = c(...)
  word_options = paste(words, collapse = "|") # combine the words w/ | between them
  paste0('\\b(?:', word_options, ')\\b') 
  # add extra regex formatting that makes it work
}

word_list_regex <-  word_match_list(swear_words$X1)
pre_cleanup_n <- sum(lengths(strsplit(data, "\\W+")))
data <- str_remove_all(data, word_list_regex)
post_cleanup_n <- sum(lengths(strsplit(data, "\\W+")))

Cleaning up with the chosen list of profanity removes a total of 7594 words from the corpus.

Tokenize

Now that the data has been cleaned, I can tokenize, that is find instances of single words, bigrams (two word sets), trigrams (three word sets), and quadgrams (4 word sets). This is easily achieved with the tokenize_ngrams function where different lengths of ngrams are passed.

Code
tokenized_words <- tokenize_words(data)
tokenized_2gram <- tokenize_ngrams(data, n = 2)
tokenized_3gram <- tokenize_ngrams(data, n = 3)
tokenized_4gram <- tokenize_ngrams(data, n = 4)

Task 2: Exploratory Data Analysis

My next step in building the predictive model is to understand the distribution and relationship between words, tokens, and phrases of the text. To get a grasp of the material, I’ll look at the distributions of 1, 2, and 3-grams as well as several questions detailed in the task I’ll illustrate below.

Word Frequency

To begin with we can examine the distribution of words from the tokenized_words created above with tokenizers::tokenize_words.

Code
word_data <- data.frame(words = unlist(tokenized_words))
most_common_words_0 <- word_data %>% 
  count(words, sort = TRUE)

Unsurprisingly, the words the, to, and, a, of, in are the most common but relatively uninteresting. These can be ignored as they are included in tm::stopwords().

Code
word_data_nsw <- word_data %>% 
  anti_join(data.frame(words = tm::stopwords("en")))
Joining with `by = join_by(words)`
Code
most_common_words_1 <- word_data_nsw %>%
  count(words, sort = TRUE)

By excluding stopwords, we can now make a plot of the most common words with ggplot.

Code
library(ggplot2)
head(most_common_words_1, n = 8) %>% 
  mutate(words = factor(words, 
                        levels = head(most_common_words_1, n = 8)$words)) %>%
  ggplot(aes(x = words, y = n)) + 
  geom_col() + 
  labs(title = "10 most common words")

2-Gram Frequency

The single most common words don’t tell us much information about the set, but common 2-grams may be more illuminating.

Code
two_gram_data <- data.frame(two_gram = unlist(tokenized_2gram))

most_common_bigrams <- two_gram_data %>%
  count(two_gram, sort = TRUE)

gt(head(most_common_bigrams, n = 10))
two_gram n
of the 41908
in the 37984
to the 19834
on the 17649
for the 16476
to be 13860
at the 12613
and the 12270
in a 11075
with the 10023

3-Gram frequency

Similarly, three-grams may provide additional insight into common phrases. Initially I noticed that there were 11641 NA’s that were the most prevalent type of trigram but realized these were due to finding trigrams of two word lines by evaluating sum(sapply(tokenized_words, length) < 3) and was rectified by passing the trigram data to na.omit().

Code
trigram_data <- data.frame(trigram = unlist(tokenized_3gram)) %>%
  na.omit()

most_common_trigrams <- trigram_data %>%
  count(trigram, sort = TRUE)

gt(head(most_common_trigrams, n = 10))
trigram n
one of the 3311
a lot of 2854
to be a 1481
out of the 1450
as well as 1432
the end of 1388
some of the 1376
going to be 1358
part of the 1264
it was a 1227

4-gram frequency

For future analysis, I opted to create most_common_quadgrams in the same format as the prior work for bigrams and trigrams.

Code
quadgram_data <- data.frame(quadgram = unlist(tokenized_4gram)) %>%
  na.omit()

most_common_quadgrams <- quadgram_data %>%
  count(quadgram, sort = TRUE)

gt(head(most_common_quadgrams, n = 10))
quadgram n
the end of the 693
at the end of 615
the rest of the 604
for the first time 531
at the same time 469
one of the most 434
when it comes to 391
is one of the 390
in the middle of 372
to be able to 345

Words needed to cover dataset

How many words are needed to cover 50% of all word instances? 90%? This is straight forward to answer if the words are sorted by their frequency, converted to proportion by dividing by total number of words in the dataset, and then aggregated with a cumulative sum. Similarly to the evaluation of most common words, for this question to provide an interesting answer, we can first filter out stopwords such as the, and, a, etc.

Code
# word data, no stop words

word_props <- word_data_nsw %>%
  count(words, sort = TRUE) %>%
  mutate(prop = n/sum(n),
         cumprop = cumsum(prop)) %>%
  summarize(`50%` = with(., which.max(cumprop >= .5)), 
            `90%` = with(., which.max(cumprop >= .9)), 
            `100%` = nrow(.)) %>%
  pivot_longer(everything(), names_to = "Percent of corpus", values_to = "Number of words") %>% 
  select(c(2,1))

gt(word_props, caption = "Number of words to cover varying percentages of all word instances")
Number of words to cover varying percentages of all word instances
Number of words Percent of corpus
1102 50%
17642 90%
193426 100%

Though there are a total of 193426 words in the no-stop word dataset, it takes only 0.57% of the total words to describe 50% of all word instances and 9.12% of the total words to describe 90% of all word instances. If future implementation of an ngram model proves too slow, this is one place where a speedup could occur: if the size of the corpus is decreased evaluation may speed up.

Finding foreign language words

If the data is obtained from websites of one primary language, then I would expect the majority of words acquired in the corpus to be all from the same language. What this indicates to me is that if you sort all word instances by their frequency, the high frequency words are likely to be from the target language while the low frequency words are likely to be typos, misspellings, or words from other languages.
Looking at tail(most_common_words_1, n = 10), we can see that there are assorted, predominantly foreign, characters clustered at the end of the sorted word list.

words n
라선호 1
레이 1
소풍 1
스파클 1
역도산 1
크림소스 1
호적 1
find 1
2 1
ipa 1

Alternatively, we could also look at which words contain non-ascii characters. A convenient function is stringi::stri_enc_isascii() which checks whether characters are encoded with 127 or less bits (length of ascii characters). I chose to include the foreign words in the corpus as there were relatively few and these basic filters would eliminate words like “café” and “cliché”.

Next Steps

Prediction algorithm

The next step in this project will be to create a prediction algorithm based on n-grams. A basic implementation would be to use the highest match of ngram if it exists to predict the next word via maximum likelihood.

What I’m targeting to implement is a more rigorous treatment that includes linear Good-Turing smoothing (to help improve low count estimates) and Katz backoff.

Shiny app

The envisioned Shiny app will take a user’s input and either upon click of a button or live will show the result of the next most likely word. Which implementation used will depend on how quickly the prediction algorithm runs: if a user has to wait more than 500ms or so for the result to automatically display they may wonder if anything is happening. Adding a button and perhaps a progress bar would show feedback that the algorithm is working behind the scenes.