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.
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 apostrophedata <- 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 thempaste0('\\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.
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().
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().
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 wordsword_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.