This is a milestone report for my Coursera JHU Data Science Capstone Project.
The report’s objective is to present the initial exploration of a large dataset. Our goal here is to identify key statistical properties that will inform the development of our final objective: a predictive text model in the form of a Shiny app which will suggest the next word to the user after receiving a text input.
Here’s an outline of how we’ll proceed with our predictive model development:
In this step, we will only be using the English language data sets. We’ll load those and identify some general characteristics and do basic exploratory data analysis. We’ll also identify appropriate tokens for tokenization - looking at words, numbers, punctuation, etc. and remove profanity so that those words get filtered out and don’t get predicted by our model.
We’ll start by importing the libraries we’ll need for this report:
library(dplyr)
library(ggplot2)
library(quanteda)
library(stringi)
library(kableExtra)
library(SnowballC)
library(hunspell)
library(wordcloud)
library(RColorBrewer)
library(Matrix)
First we’ll download the full dataset from: https://d396qusza40orc.cloudfront.net/dsscapstone/dataset/Coursera-SwiftKey.zip
# Define working directory
wd <- "C:/Users/Admin/Desktop/projects/capstone"
# Define URL where Capstone dataset will be downloaded
url <- "https://d396qusza40orc.cloudfront.net/dsscapstone/dataset/Coursera-SwiftKey.zip"
# Define name and destination of downloaded file
data.path <- paste(wd, "/SwiftKey-Data.zip", sep = "")
# If the file containing the data does not yet exist, download the dataset
if (!file.exists(data.path)){
download.file(url, data.path, mode = "wb")
}
Then we’ll unzip the dataset:
# Define path to unzipped file
data.files.path <- paste(wd, "/final", sep = "")
# Unzip file if necessary
if(!file.exists(data.files.path)){
unzip(zipfile = data.files.path)
}
Let’s look at the data we have in the dataset:
# List the directories contained in the unzipped data
list.files(data.files.path)
## [1] "de_DE" "en_US" "fi_FI" "ru_RU"
As we can see, there is data available for four different languages. We’ll be using the English language data. Let’s look at those files:
# Define path to English-language data
data.files.path.EN <- paste(data.files.path, "/en_US", sep = "")
# List directories contained in the English-language component of the dataset
list.files(data.files.path.EN)
## [1] "en_US.blogs.txt" "en_US.news.txt" "en_US.twitter.txt"
This dataset has a vast amount of information from US news, blog and twitter feeds. Let’s load in the data:
# Assign a variable for each English lanaguage file:
blog.file <- paste(data.files.path.EN, "/en_US.blogs.txt", sep = "") # blogs
news.file <- paste(data.files.path.EN, "/en_US.news.txt", sep = "") # news
twitter.file <- paste(data.files.path.EN, "/en_US.twitter.txt", sep = "") # Twitter
# Load in blog data
blog.file.con <- file(blog.file, open = "r")
blog.text <- readLines(blog.file.con, encoding = "UTF-8", skipNul = TRUE)
close(blog.file.con)
# Load in news data
news.file.con <- file(news.file, open = "r")
news.text <- readLines(news.file.con, encoding = "UTF-8", skipNul = TRUE)
close(news.file.con)
# Load in Twitter data
twitter.file.con <- file(twitter.file, open = "r")
twitter.text <- readLines(twitter.file.con, encoding = "UTF-8", skipNul = TRUE)
close(twitter.file.con)
Part of the assignment grading criteria asks us to summarize the files with word counts and line counts. Let’s do that:
# Count words in each text file using stringi
num.words.blog <- sum(stringi::stri_count_words(blog.text))
num.words.news <- sum(stringi::stri_count_words(news.text))
num.words.twitter <- sum(stringi::stri_count_words(twitter.text))
# Count lines
num.lines.blog <- length(blog.text)
num.lines.news <- length(news.text)
num.lines.twitter <- length(twitter.text)
# Count characters
num.chars.blog <- sum(stringi::stri_length(blog.text))
num.chars.news <- sum(stringi::stri_length(news.text))
num.chars.twitter <- sum(stringi::stri_length(twitter.text))
# Calculate file sizes in MB
size.blog.file <- file.info(blog.file)$size / 1024^2
size.news.file <- file.info(news.file)$size / 1024^2
size.twitter.file <- file.info(twitter.file)$size / 1024^2
Now we can summarize this info in a table:
files.summary <- data.frame(
filename = c("en_US.blogs.txt", "en_US.news.txt", "en_US.twitter.txt"),
size_MB = sprintf("%0.2f MB", c(size.blog.file, size.news.file, size.twitter.file)),
lines = c(num.lines.blog, num.lines.news, num.lines.twitter),
words = c(num.words.blog, num.words.news, num.words.twitter),
characters = c(num.chars.blog, num.chars.news, num.chars.twitter)
)
# Display the summary table using knitr::kable for better formatting
knitr::kable(files.summary, caption = "Summary of Text Files")
| filename | size_MB | lines | words | characters |
|---|---|---|---|---|
| en_US.blogs.txt | 200.42 MB | 899288 | 37546806 | 206824505 |
| en_US.news.txt | 196.28 MB | 77259 | 2674561 | 15639408 |
| en_US.twitter.txt | 159.36 MB | 2360148 | 30096690 | 162096241 |
These file are quite large! One of our assignment parameters indicates that we need to account for compute and processing times, so we will definitely want to first sample the data, and then combine it so we can have one corpus that accounts for all of our valuable data and be the most helpful text predictor.
We’ll take 5,000 lines from each file - to be cleaned and combined into one corpus:
# Set the seed to ensure reproducible results
set.seed(45454)
# Set sample size
sample.size <- 5000
# Sample data from each text file
sample.blog <- sample(blog.text, sample.size, replace = FALSE)
sample.news <- sample(news.text, sample.size, replace = FALSE)
sample.twitter <- sample(twitter.text, sample.size, replace = FALSE)
Next, we’ll combine samples into one data file:
# Combine the data
combined.sample <- c(sample.blog, sample.news, sample.twitter)
# Define filename for sample data
combined.sample.filename <- "sample_data_EN.txt"
# Write combined sample data to file
combined.sample.con <- file(combined.sample.filename, open = "w")
writeLines(combined.sample, combined.sample.con)
close(combined.sample.con)
Now we can combine our sample into a corpus using the R package quanteda, which stands for “Quantitative Analysis of Textual Data”:
text.EN.corpus <- corpus(combined.sample)
Now we’ll need to remove unnecessary variables and clean the data to remove inconsistencies. This includes things like uppercase vs. lowercase, punctuation, URL’s, and profanity:
text.tokens <- tokens(text.EN.corpus,
what="word1",
remove_numbers = TRUE,
remove_punct = TRUE,
remove_url =TRUE,
remove_separators = TRUE,
remove_symbols = TRUE,
verbose = quanteda_options("verbose"))
For our initial exploratory analysis, we have a version of the tokens without stopwords. In the model itself, stopwords will be left in the data, in order to produce more natural sounding results.
tokens.no.stopwords <- tokens_remove(text.tokens, pattern = stopwords("en"))
Next, we need to remove profanity from the text sample. If we go to this website: http://www.cs.cmu.edu/~biglou/resources/ we can see an offensive/profane word list in the form of a .txt file that will be great for this purpose:
# Define name and destination of downloaded file
data.path <- paste(wd, "/bad-words.txt", sep = "")
# Define URL where text file containing a list of profane words/phrases can be downloaded
url <- "http://www.cs.cmu.edu/~biglou/resources/bad-words.txt"
# If necessary, download the text file
if (!file.exists(data.path)){
download.file(url, data.path, mode = "wb")
}
# Read the lines of the text file containing profanities
bad.words.con <- file(data.path, open = "r")
bad.words <- readLines(bad.words.con, encoding = "UTF-8", skipNul = TRUE)
close(bad.words.con)
Now, we need to better understand the relationships and distribution between words, tokens, and phrases in our dataset. We’ll analyze unigrams, bigrams and trigrams. We’ll also try to see how many unique words are needed in a ‘frequency-sorted’ dictionary to cover a certain subset of all word instances in a language, like 50% of the total and 90% of the total. We’ll also consider how we can increase the coverage by looking for words not in our corpus, using smaller words to cover the same number of phrases.
Let’s generate a set of unigrams with stopwords, and a set without:
# Generate unigrams with and without stopwords
unigram.no.stopwords <- tokens_ngrams(tokens.no.stopwords, n = 1)
unigram.with.stopwords <- tokens_ngrams(text.tokens, n = 1)
Now, we’ll need a document feature matrix for the unigram case (without stopwords for our current exploration). All words are converted to lowercase and padding (extra spaces) is filtered with DFM, but we will need to remove profanity as well:
# Create the document-feature matrix from unigrams without stopwords
text.unigram <- dfm(unigram.no.stopwords)
# Remove profanity from the DFM
text.unigram.cleaned <- dfm_remove(text.unigram, pattern = bad.words)
Let’s identify the 100 most frequent unigrams in the corpus:
# Define most frequently-occurring unigrams
unigram.top.features.no.stopwords <- topfeatures(text.unigram.cleaned, 100)
# Create dataframe displaying most frequent unigrams
unigram.top.features.no.stopwords.df <- data.frame(unigram = names(unigram.top.features.no.stopwords), freq = unigram.top.features.no.stopwords)
# Display the most frequent unigrams
head(unigram.top.features.no.stopwords.df)
## unigram freq
## said said 1484
## one one 1332
## just just 1111
## like like 1069
## can can 1005
## time time 898
Now let’s visualize our 100 most common unigrams as a word cloud with RColorBrewer for some visual distinction:
wordcloud(words = unigram.top.features.no.stopwords.df$unigram,
freq = unigram.top.features.no.stopwords.df$freq,
min.freq = 1,
max.words = 100,
random.order = FALSE,
rot.per = 0.35,
colors=brewer.pal(10, "Spectral"))
Next, let’s check the frequency of the 20 most common unigrams using a histogram:
unigram_hist <- ggplot(unigram.top.features.no.stopwords.df[1:20,], aes(reorder(unigram.top.features.no.stopwords.df[1:20,]$unigram, -unigram.top.features.no.stopwords.df[1:20,]$freq), y = unigram.top.features.no.stopwords.df[1:20,]$freq))
unigram_hist <- unigram_hist + geom_bar(stat = "Identity", fill = "blue")
unigram_hist <- unigram_hist + xlab("unigram") + ylab("frequency") + ggtitle("20 Most Frequent Unigrams")
unigram_hist <- unigram_hist + theme(plot.title = element_text(size = 14, hjust = 0.5, vjust = 0.5),
axis.text.x = element_text(hjust = 0.5, vjust = 0.5, angle = 45),
axis.text.y = element_text(hjust = 0.5, vjust = 0.5))
# Display histogram
print(unigram_hist)
The analysis of the most common words reveals that a relatively small number of distinct words constitute a significant portion of the entire corpus. This observation prompts us to explore further into the vocabulary diversity. Specifically, we are interested in determining the minimal set of unique words required to account for 50%, and then for 90% of the total occurrences of words within our corpus. It’s important to highlight that this examination excludes stopwords, which are common words often removed in text analysis due to their limited informational value. Incorporating stopwords into this analysis would likely reduce the size of the unique word set needed to reach these coverage thresholds, even if we need them for our final model.
# Create another dataframe with a maximum number of features to capture all unique words in dataset
unigram.freqs.no.stopwords <- topfeatures(text.unigram, 100000)
unigram.freqs.no.stopwords.df <- data.frame(unigram = names(unigram.freqs.no.stopwords), freq = unigram.freqs.no.stopwords)
# Calculate cumulative percentage of dataset to which each word contributes
unigram.freqs.no.stopwords.df["cumul_perc"] <- cumsum(unigram.freqs.no.stopwords.df$freq / sum(unigram.freqs.no.stopwords.df$freq)) * 100.0
# Determine number of words necessary to cover 50% of the language
num.words.fifty.perc <- nrow(filter(unigram.freqs.no.stopwords.df, cumul_perc < 50.0)) + 1
print(paste("Number of words necessary to cover 50% of the language = ", num.words.fifty.perc, sep = ""))
## [1] "Number of words necessary to cover 50% of the language = 1141"
# Determine number of words necessary to cover 90% of the language
num.words.ninety.perc <- nrow(filter(unigram.freqs.no.stopwords.df, cumul_perc < 90.0)) + 1
print(paste("Number of words necessary to cover 90% of the language = ", num.words.ninety.perc, sep = ""))
## [1] "Number of words necessary to cover 90% of the language = 14880"
We’ll repeat the process above for bigrams (word pairs), creating one set with stopwords and another without:
# Generate bigrams with and without stopwords
bigram.no.stopwords <- tokens_ngrams(tokens.no.stopwords, n = 2)
bigram.with.stopwords <- tokens_ngrams(text.tokens, n = 2)
Now, we’ll need a document feature matrix for the bigram case (without stopwords for our current exploration). All words are converted to lowercase and padding (extra spaces) is filtered with DFM, but we will need to remove profanity as well:
# Create the document-feature matrix from bigrams without stopwords
text.bigram <- dfm(bigram.no.stopwords)
# Remove profanity from the DFM
text.bigram.cleaned <- dfm_remove(text.bigram, pattern = bad.words)
Let’s identify the 100 most frequent bigrams:
# Define most frequently-occurring bigrams
bigram.top.features.no.stopwords <- topfeatures(text.bigram.cleaned, 100)
# Create dataframe displaying most frequent bigrams
bigram.top.features.no.stopwords.df <- data.frame(bigram = names(bigram.top.features.no.stopwords), freq = bigram.top.features.no.stopwords)
# Display the most frequent bigrams
head(bigram.top.features.no.stopwords.df)
## bigram freq
## last_year last_year 102
## new_york new_york 92
## right_now right_now 73
## years_ago years_ago 72
## high_school high_school 71
## last_week last_week 64
Let’s make our bigram word cloud:
# Replace underscores with spaces in bigram names
bigram.top.features.no.stopwords.df$bigram <- gsub("_", " ", bigram.top.features.no.stopwords.df$bigram)
# Create word cloud
wordcloud(words = bigram.top.features.no.stopwords.df$bigram,
freq = bigram.top.features.no.stopwords.df$freq,
min.freq = 1,
max.words = 100,
random.order = FALSE,
rot.per = 0.35,
scale = c(3, 0.50),
colors=brewer.pal(10, "Spectral"))
And our bigram histogram:
bigram_hist <- ggplot(bigram.top.features.no.stopwords.df[1:20,], aes(reorder(bigram.top.features.no.stopwords.df[1:20,]$bigram, -bigram.top.features.no.stopwords.df[1:20,]$freq), y = bigram.top.features.no.stopwords.df[1:20,]$freq))
bigram_hist <- bigram_hist + geom_bar(stat = "Identity", fill = "blue")
bigram_hist <- bigram_hist + xlab("bigram") + ylab("frequency") + ggtitle("20 Most Frequent Bigramss")
bigram_hist <- bigram_hist + theme(plot.title = element_text(size = 14, hjust = 0.5, vjust = 0.5),
axis.text.x = element_text(hjust = 0.5, vjust = 0.5, angle = 45),
axis.text.y = element_text(hjust = 0.5, vjust = 0.5))
# Display histogram
print(bigram_hist)
Lastly, we will iterate through the same process with trigrams!
# Generate trigrams with and without stopwords
trigram.no.stopwords <- tokens_ngrams(tokens.no.stopwords, n = 3)
trigram.with.stopwords <- tokens_ngrams(text.tokens, n = 3)
And our document feature matrix:
# Create the document-feature matrix from trigrams without stopwords
text.trigram <- dfm(trigram.no.stopwords)
# Remove profanity from the DFM
text.trigram.cleaned <- dfm_remove(text.trigram, pattern = bad.words)
Identify most frequent trigrams:
# Define most frequently-occurring trigrams
trigram.top.features.no.stopwords <- topfeatures(text.trigram.cleaned, 100)
# Create dataframe displaying most frequent trigrams
trigram.top.features.no.stopwords.df <- data.frame(trigram = names(trigram.top.features.no.stopwords), freq = trigram.top.features.no.stopwords)
# Display the most frequent trigrams
head(trigram.top.features.no.stopwords.df)
## trigram freq
## new_york_city new_york_city 16
## invitation_paintball_party invitation_paintball_party 11
## two_years_ago two_years_ago 11
## gov_chris_christie gov_chris_christie 9
## new_york_times new_york_times 8
## tick_tick_tick tick_tick_tick 8
Trigram word cloud:
# Replace underscores with spaces in trigram names
trigram.top.features.no.stopwords.df$trigram <- gsub("_", " ", trigram.top.features.no.stopwords.df$trigram)
# Create word cloud
wordcloud(words = trigram.top.features.no.stopwords.df$trigram,
freq = trigram.top.features.no.stopwords.df$freq,
min.freq = 1,
max.words = 100,
random.order = FALSE,
rot.per = 0.35,
scale = c(2, 0.50),
colors=brewer.pal(10, "Spectral"))
Most frequent trigrams histogram:
trigram_hist <- ggplot(trigram.top.features.no.stopwords.df[1:20,], aes(reorder(trigram.top.features.no.stopwords.df[1:20,]$trigram, -trigram.top.features.no.stopwords.df[1:20,]$freq), y = trigram.top.features.no.stopwords.df[1:20,]$freq))
trigram_hist <- trigram_hist + geom_bar(stat = "Identity", fill = "blue")
trigram_hist <- trigram_hist + xlab("bigram") + ylab("frequency") + ggtitle("20 Most Frequent Trigrams")
trigram_hist <- trigram_hist + theme(plot.title = element_text(size = 14, hjust = 0.5, vjust = 0.5),
axis.text.x = element_text(hjust = 0.5, vjust = 0.5, angle = 45),
axis.text.y = element_text(hjust = 0.5, vjust = 0.5))
# Display histogram
print(trigram_hist)
The sets of unigrams, bigrams and trigrams are saved to disk in order to be applied to our predictive model:
# Save unigram data
saveRDS(unigram.with.stopwords, paste(wd, "/unigram-with-stopwords.rds", sep = ""))
saveRDS(unigram.no.stopwords, paste(wd, "/unigram-no-stopwords.rds", sep = ""))
# Save bigram data
saveRDS(bigram.with.stopwords, paste(wd, "/bigram-with-stopwords.rds", sep = ""))
saveRDS(bigram.no.stopwords, paste(wd, "/bigram-no-stopwords.rds", sep = ""))
# Save trigram data
saveRDS(trigram.with.stopwords, paste(wd, "/trigram-with-stopwords.rds", sep = ""))
saveRDS(trigram.no.stopwords, paste(wd, "/trigram-no-stopwords.rds", sep = ""))
With the foundational data analysis complete, we proceed to the final stages of developing and deploying the predictive text model. The following steps outline the roadmap for completion:
Model Building: Utilize the unigrams, bigrams, and trigrams datasets to construct a predictive model. We can leverage Markov chains to model word probabilities and employ backoff models to ensure robustness in predictions across various contexts.
Data Coverage Enhancement: Address the challenge of limited data coverage by identifying and classifying infrequent words as “unknown”. Explore the use of synonyms and external resources to enrich the model’s vocabulary and improve its predictive capability.
Shiny App Development: Develop a Shiny application to serve as the interface for the predictive text model. The app will allow users to input text and receive word predictions in real-time, showcasing the model’s utility.
User Interface Design: Design the Shiny app with a focus on simplicity and user experience. Ensure the interface is intuitive, responsive, and provides immediate feedback to user inputs.
Accessibility Considerations: Ensure the Shiny app is accessible to all users, including those with disabilities. This includes making visualizations color-blind friendly and ensuring the app is navigable without a mouse.
Deployment and Testing: Deploy the Shiny app and conduct testing to evaluate its performance and usability. Make iterative improvements to both the model and the app interface if necessary!