This report explores the properties of three different datasets that will be later used to build a text prediction algorithm. This exercise is part of the Coursera JHU Data Science Specialization. It will perform exploratory data analysis in order to get a grasp of the data to be used and inform what steps need to be taken in order to produce the final text prediction shiny app.
setwd("C:/Users/mclarke/Box/MEC Personal/Coursera/Statistics and Machine Learning")
library(stringi);library(dplyr);library(quanteda);library(RCurl);library(wordcloud2);library(tm);library(ggplot2);library(wesanderson)
enblogs <- as.data.frame(readLines("./Coursera-SwiftKey/final/en_US/en_US.blogs.txt"))
names(enblogs)[1] <- "text"
ennews <- as.data.frame(readLines("./Coursera-SwiftKey/final/en_US/en_US.news.txt"))
names(ennews)[1] <- "text"
entwitter <- as.data.frame(readLines("./Coursera-SwiftKey/final/en_US/en_US.twitter.txt"))
names(entwitter)[1] <- "text"
First, we investigate some basic summary statistics of each file to get an idea of what each file contains and can be used for. We look at the number of lines (entries in the data), total word count, maximum words per line, minimum words per line, average words per line, total characters, maximum characters per line, minimum characters per line, and average characters per line.
## Name Number.of.Lines Total.Word.Count Max.Words.Per.Line
## 1 en_US.blogs.txt 899288 37570839 6726
## 2 en_US.news.txt 77259 2651432 1123
## 3 en_US.twitter.txt 2360148 30451128 47
## Min.Words.Per.Line Average.Words.Per.Line Total.Characters
## 1 0 41.75109 162464653
## 2 1 34.61779 12476453
## 3 1 12.75063 125570616
## Max.Characters.Per.Line Min.Characters.Per.Line Average.Characters.Per.Line
## 1 40833 1 229.98696
## 2 5760 2 202.42830
## 3 144 2 68.69173
As expected, the distribution of word count for news and blogs data
is much higher than the tweet data. Interestingly, while the upper
quartile of the blogs data extends higher than the news data, the news
data has a higher center. Note: Outliers have been removed from the
plots as they were unreadable when included. We’re simply trying to gain
a general understanding of the data.
We first load in the quanteda package which is used for quantitative analysis of textual data. We then set the seed for reproducibility and take a 5% sample of the data (by lines/rows) since the full set would take too much computational power to work with in the long run when building our predictions and performing tokenization.Then we create a corpus and perform some data cleaning (remove stop words, punctuation, URLs, symbols, profanity).
set.seed(4321)
enblogsSample <- as.data.frame(sample(enblogs$text, round(.05*length(enblogs$text), digits = 0), replace = FALSE))
names(enblogsSample)[1] <- "text"
ennewsSample <- as.data.frame(sample(ennews$text, round(.05*length(ennews$text), digits = 0), replace = FALSE))
names(ennewsSample)[1] <- "text"
entwitterSample <- as.data.frame(sample(entwitter$text, round(.05*length(entwitter$text), digits = 0), replace = FALSE))
names(entwitterSample)[1] <- "text"
Sample <- bind_rows(enblogsSample, ennewsSample, entwitterSample)
corpusText <- corpus(Sample)
corpusTextTokens <- tokens(corpusText,
remove_punct = TRUE,
remove_symbols = TRUE,
remove_numbers = TRUE,
remove_url =TRUE,
remove_separators = TRUE,
verbose = quanteda_options("verbose"))
corpusTextTokens <- tokens_remove(corpusTextTokens, pattern = stopwords("en"))
profanityURL <- getURL("https://raw.githubusercontent.com/surge-ai/profanity/main/profanity_en.csv")
profanity <- read.csv(text= profanityURL)
corpusTextTokens <- tokens_remove(corpusTextTokens, pattern = profanity$text)
For our algorithm preparation, we will take our corpus and split it apart by n-grams. These will help us analyze the different combinations of words that are present within the corpus and see which are most frequently used. That way, some sort of probability measure can be used to select the best prediction of the next word.
# Create n-grams from the corpus in order to analyze top frequencies of words as well as combinations of words
unigrams <- tokens_ngrams(corpusTextTokens, n=1, concatenator = " ")
bigrams <- tokens_ngrams(corpusTextTokens, n=2, concatenator = " ")
trigrams <- tokens_ngrams(corpusTextTokens, n=3, concatenator = " ")
# Document Feature Matrices of each to convert from tokens to something interpretable
unigramsdfm <- dfm(unigrams, tolower = TRUE, remove_padding = TRUE)
bigramsdfm <- dfm(bigrams, tolower = TRUE, remove_padding = TRUE)
trigramsdfm <- dfm(trigrams, tolower = TRUE, remove_padding = TRUE)
# Use topfeatures to identify most frequent features (n-grams) of the document feature matrices
unigramsTF <- topfeatures(unigramsdfm, n=75)
bigramsTF <- topfeatures(bigramsdfm, n=75)
trigramsTF <- topfeatures(trigramsdfm, n=75)
# Put into a dataframe
topunigramsDf <- data.frame(Unigram= names(unigramsTF), Frequency= unigramsTF)
topbigramsDf <- data.frame(Bigrams= names(bigramsTF), Frequency= bigramsTF)
toptrigramsDf <- data.frame(Trigrams= names(trigramsTF), Frequency= trigramsTF)
For each set of unigrams, bigrams, and trigrams, we visualize the top
15 n-grams in both a bar plot and word cloud. The bar plot shows the
distinct frequencies of each n-gram while the word cloud changes the
size of the word based on the frequency of its occurrence. Getting an
idea of what these n-grams look like and what dataset they might be
coming from will be helpful in increasing the accuracy of our prediction
algorithm.
Based on our knowledge of the data now, we can see the usefulness of n-grams that add context to what word should be predicted next. Therefore, it seems intuitive to use the largest n-gram possible when predicting the next word to come. That is, adding as much context as possible for our algorithm to work with. With this preliminary thought along with some further research, it seems advantageous to use a back-off model which starts at the largest n-gram, searches for matches to the string of input text and returns a prediction based on the frequency of the input text within the n-gram. If no match is found, the algorithm then backs off to the next n-1 n-gram (i.e. trigram to bigram) to perform the same process. This will ensure the most context around any prediction and hopefully increase our accuracy. The preliminary plan for the app is to have an input text box with a submission button that will then generate at least one prediction for the next word. Accuracy, efficiency (runtime), and memory tests will be run on the algorithm and overall app to ensure practicality and usefulness.