Introduction

This is the Milestone Report for week 2 of the Coursera Data Science Capstone project. The primary objectives include demonstrating successful data download and loading, creating a basic report with summary statistics, sharing interesting findings, and seeking feedback on plans for a prediction algorithm and Shiny app.

Here we will identify the major features of the training data and then summarize plans for the predictive model.

The model’s training will utilize a unified document corpus from three primary sources: Blogs, News, and Twitter, with a focus exclusively on the English corpora among the available four languages.

Libraries

We need these R Libraries for this analysis.

library(RWeka)
library(tm)
library(stringi)
library(slam)
library(ggplot2)
library(gridExtra)
library(knitr)
library(dplyr)
library(kableExtra)
library(wordcloud)
library(RColorBrewer)

Data Preprocessing

The first step is to download the data and read them:

trainURL <- "https://d396qusza40orc.cloudfront.net/dsscapstone/dataset/Coursera-SwiftKey.zip"

if (!file.exists("data/final/en_US")) {
    tempFile <- tempfile()
    download.file(trainURL, tempFile)
    unzip(tempFile, exdir = "data")
    unlink(tempFile)
}


twitter <- readLines("data/final/en_US/en_US.twitter.txt", skipNul = TRUE)
news <- readLines("data/final/en_US/en_US.news.txt" , warn = FALSE, skipNul = TRUE)
blogs <- readLines("data/final/en_US/en_US.blogs.txt", warn = FALSE, skipNul = TRUE)

Before constructing the unified document corpus and performing data cleaning, we analyze the summary of each of the three text corpora. The following table shows file sizes, line counts, character counts, and word counts for each source file. Additionally, we provide basic statistics on the number of words per line, including the minimum, mean, and maximum values.

# Get file sizes
blogs.size <- paste(round(file.info("data/final/en_US/en_US.blogs.txt")$size / 1024 ^ 2),"MB")
news.size <- paste(round(file.info("data/final/en_US/en_US.news.txt")$size / 1024 ^ 2),"MB")
twitter.size <- paste(round(file.info("data/final/en_US/en_US.twitter.txt")$size / 1024 ^ 2),'MB')


# num lines per file
numLines <- sapply(list(blogs, news, twitter), length)

# num characters per file
numChars <- sapply(list(nchar(blogs), nchar(news), nchar(twitter)), sum)

# num words per file
numWords <- sapply(list(blogs, news, twitter), stri_stats_latex)[4,]

# words per line
wpl <- lapply(list(blogs, news, twitter), function(x) stri_count_words(x))

FileSize <- c(blogs.size,news.size,twitter.size)

# words per line summary
wplSummary = sapply(list(blogs, news, twitter),
                    function(x) summary(stri_count_words(x))[c('Min.', 'Mean', 'Max.')])
rownames(wplSummary) = c('Min WPL', 'Mean WPL', 'Max PL')


summary <- data.frame(
    File = c("en_US.blogs.txt", "en_US.news.txt", "en_US.twitter.txt"),
    FileSize = FileSize,
    Lines = numLines,
    Characters = numChars,
    Words = numWords,
    t(rbind(round(wplSummary)))
    )

kable(summary,
      row.names = FALSE,
      align = c("l", rep("r", 7)),
      caption = "") %>% kable_styling(position = "left")
File FileSize Lines Characters Words Min.WPL Mean.WPL Max.PL
en_US.blogs.txt 200 MB 899288 206824509 37570839 0 42 6726
en_US.news.txt 196 MB 77259 15639408 2651432 1 35 1126
en_US.twitter.txt 159 MB 2360148 162122861 30451170 1 13 47

We have conducted a preliminary exploration of the English dataset, and the table above provides an overview of its statistics from three distinct sources. Notably, the dataset sizes from the three sources are relatively comparable. The Twitter dataset stands out with the smallest file size (~159 MB) but exhibits twice the number of lines compared to the other two sources. Additionally, the Twitter data records the lowest number of words and mean (average number of words per line). This aligns with expectations, given the nature of Twitter data consisting of short texts with defined character limits. Anticipating a higher incidence of ‘garbage words’ in the Twitter data, we recognize the need for thorough cleaning compared to the blogs and news data.

Prior to delving into exploratory data analysis, the next section will address data cleaning procedures.

Data cleaning

These steps are critical for enhancing the precision of our model. Considering the substantial size of the datasets, reaching up to 200MB with 2 million lines from each source, expediting data exploration and validating data cleaning processes is essential. To streamline these tasks, we opt to work with a 1% sample of the dataset. Initially, we load this sample data into a Corpus, a primary data structure employed by the ‘tm’ package. This approach facilitates more efficient and manageable data handling as we proceed with subsequent analyses.

# set seed for reproducability
set.seed(123)
# sample all three data sets
sampleBlogs <- sample(blogs, length(blogs) * 0.01, replace = FALSE)
sampleNews <- sample(news, length(news) * 0.01, replace = FALSE)
sampleTwitter <- sample(twitter, length(twitter) * 0.01, replace = FALSE)
# remove all non-English characters from the sampled data
sampleBlogs <- iconv(sampleBlogs, "latin1", "ASCII", sub = "")
sampleNews <- iconv(sampleNews, "latin1", "ASCII", sub = "")
sampleTwitter <- iconv(sampleTwitter, "latin1", "ASCII", sub = "")

The following function will generate a result structure of type VCorpus (‘virtual corpus’ that is, loaded into memory) where each line of text in the source is loaded as a document in the corpus.

The VCorpus object, essentially a nested list, features PlainTextDocument objects at each index. These objects are lists containing the actual text data (content) along with relevant metadata (meta), facilitating the visualization and conceptualization of the entire VCorpus.

Implemented through the ‘tm’ package, various functions are employed for these tasks. These functions act as transformations, applied to the document collection via the tm_map() function. The forthcoming data cleaning tasks are executed through tm_map, involving:

While further refinement is possible by excluding specific words such as profanity, ‘garbage words,’ or informal/slang language commonly used in platforms like Twitter, caution is warranted. Omitting such words may alter the context or meaning of original sentences. Therefore, this step will not be undertaken in the current data cleaning process.

buildCorpus <- function (dataSet) {
    docs <- VCorpus(VectorSource(dataSet))
    toSpace <- content_transformer(function(x, pattern) gsub(pattern, " ", x))
    
    # remove URL, Twitter handles and email patterns
    docs <- tm_map(docs, toSpace, "(f|ht)tp(s?)://(.*)[.][a-z]+")
    docs <- tm_map(docs, toSpace, "@[^\\s]+")
    docs <- tm_map(docs, toSpace, "\\b[A-Z a-z 0-9._ - ]*[@](.*?)[.]{1,3} \\b")
    
# remove profane words from the sample data set
    profanity<-readLines("http://www.cs.cmu.edu/~biglou/resources/bad-words.txt",encoding = "UTF-8", skipNul = TRUE)
    profanity<-profanity[-(which(profanity%in%c("screw","looser","^color")==TRUE))]

    profanity <- iconv(profanity, "latin1", "ASCII", sub = "")
    docs <- tm_map(docs, removeWords, profanity)
    
    docs <- tm_map(docs, tolower)
    docs <- tm_map(docs, removeWords, stopwords("english"))
    docs <- tm_map(docs, removePunctuation)
    docs <- tm_map(docs, removeNumbers)
    docs <- tm_map(docs, stripWhitespace)
    docs <- tm_map(docs, PlainTextDocument)
    return(docs)
}

We will apply the function to the three datset.

corpus_blogs <- buildCorpus(sampleBlogs)
corpus_news <- buildCorpus(sampleNews)
corpus_twitter <- buildCorpus(sampleTwitter)

Word cloud

A word cloud illustrates unique word frequencies for the three dataset.

# combine all three data sets into a single data set 
sampleData <- c(sampleBlogs, sampleNews, sampleTwitter)

# construct word cloud 3 dataset combined

tdm <- TermDocumentMatrix(buildCorpus(sampleData))
freq <- sort(rowSums(as.matrix(tdm)), decreasing = TRUE)
wordFreq <- data.frame(word = names(freq), freq = freq)

suppressWarnings (
    wordcloud(words = wordFreq$word,
              freq = wordFreq$freq,
              min.freq = 1,
              max.words = 100,
              random.order = FALSE,
              rot.per = 0.35, 
              colors=brewer.pal(8, "Dark2"))
)

Tokenizing and N-Gram Generation

We will generate plots showcasing the frequency distribution of the most prevalent words that persist in the data post data cleaning. Leveraging the Rweka library, specifically its n-grams functions, we will construct various n-grams from the corpus. Subsequently, we will create term-document matrices for these diverse n-gram tokens. The ggplot2 library will then be employed to visualize the frequency distribution of the matrices against the corresponding n-gram words.

The utilization of a document-term matrix is pivotal when each document is to be represented as a row. This approach proves beneficial in scenarios where comparison between authors is essential within rows or when the data is arranged chronologically, and preservation of the time series is paramount. Additionally, a sparse term removal technique is implemented with a sparsity threshold set at 0.9999. Sparsity, in this context, signifies the relative document frequency threshold for a term. Terms exceeding this threshold are removed, ensuring that only those terms more sparse than 0.9999 are eliminated from the analysis.

## Calculate n-grams
createNgrams<-function(corpus, n, N=NA){
  token<-function(corpus){
    NGramTokenizer(corpus, Weka_control(min = n, max = n))
  }
  
  # create term document matrix for the corpus
  tdm <- TermDocumentMatrix(corpus, control = list(tokenize = token))
  # eliminate sparse terms for each n-gram and get frequencies of most common n-grams
  
  fm <- sort(rowSums(as.matrix(removeSparseTerms(tdm,0.9999))),decreasing = TRUE)
  ngram<-data.frame(ngram=names(fm),freq=fm)
  ngram<-ngram[order(-ngram$freq),]
  if(!is.na(N)){
    ngram<-head(ngram,N)
  }
  return(ngram)
}
oneGramBlogs <- createNgrams(corpus_blogs,1,20)
oneGramNews <- createNgrams(corpus_news,1,20) 
oneGramTwitter <- createNgrams(corpus_twitter,1,20) 


twoGramBlogs <- createNgrams(corpus_blogs,2,20)
twoGramNews <- createNgrams(corpus_news,2,20) 
twoGramTwitter <- createNgrams(corpus_twitter,2,20) 

threeGramBlogs <- createNgrams(corpus_blogs,3,20)
threeGramNews <- createNgrams(corpus_news,3,20) 
threeGramTwitter <- createNgrams(corpus_twitter,3,20) 
plot.ngram<-function(ngram_df, title){
  g<-ggplot(ngram_df, aes(x=reorder(ngram, freq),y=freq)) + geom_bar(stat="Identity", fill="skyblue") + 
    theme(axis.text.y = element_text(size=8))+
    labs(title= title, y = "",x = "") + 
    theme(axis.title.y = element_text(size=8))+
    theme(axis.title.x = element_text(size=8))+
    guides(color=FALSE)+
    coord_flip()
  return(g)
  
}

plot 1-grams

t1<-plot.ngram(oneGramBlogs, "Blogs: 1")
## Warning: The `<scale>` argument of `guides()` cannot be `FALSE`. Use "none" instead as
## of ggplot2 3.3.4.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
n1<-plot.ngram(oneGramTwitter, "Twitter: 1")
b1<-plot.ngram(oneGramNews, "News: 1")
grid.arrange(t1,n1,b1 , ncol=3)

plot 2-grams

t2<-plot.ngram(twoGramBlogs, "Twitter: 2")
n2<-plot.ngram(twoGramTwitter, "News: 2")
b2<-plot.ngram(twoGramNews, "Blogs: 2")
grid.arrange(t2,n2,b2 , ncol=3)

plot 3-grams

t3<-plot.ngram(threeGramBlogs, "Twitter: 3")
n3<-plot.ngram(threeGramTwitter, "News: 3")
b3<-plot.ngram(threeGramNews, "Blogs: 3")
grid.arrange(t3,n3,b3 , ncol=3)

Summary and conclusion

Having completed a thorough examination of the dataset, we have derived intriguing findings through exploratory analysis. Our focus now shifts to the training and creation of our initial predictive model. In the realm of Machine Learning, this process unfolds iteratively. We commence by preprocessing the training data, then proceed to train and evaluate the model, repeating these steps iteratively to iteratively refine the model’s performance based on our chosen evaluation metrics.

The forthcoming Shiny app, developed on the foundation of our trained predictive model, will feature functionality akin to the SwiftKey app. It will provide users with a text field for input, offering 3-5 suggestions for the next word. Users can effortlessly choose from these options, seamlessly appending the selected word to their input, thus optimizing typing efficiency.

As we conclude this report, it is imperative to emphasize the significance of each step in our workflow – from data cleaning and preprocessing to model training and evaluation. Continuous re-evaluation of each step is essential to cultivate a truly functional and accurate Machine Learning model for our predictive text app. Anticipating the next report on the predictive model and Shiny app development, we are eager to delve deeper into this exciting phase of our project.