Introduction

Coursera Data Science Specialization intends to give the basic skills involved with being a data scientist. The goal of this capstone is to mimic the experience of being a data scientist. The project consists of developing a predictive model of text(Predictive Text Analytics) using a Swifkey Company Dataset. The main steps of this exercise will consist then on downloading the dataset, understanding it, cleaning it and do some basic analysis.

Libraries

library(knitr)
library(RColorBrewer)
library(stringi)
library(wordcloud2)
## Warning: package 'wordcloud2' was built under R version 4.3.2
library(ggplot2)
library(ngram)
## Warning: package 'ngram' was built under R version 4.3.1
library(NLP)
## Warning: package 'NLP' was built under R version 4.3.1
## 
## Attaching package: 'NLP'
## The following object is masked from 'package:ggplot2':
## 
##     annotate
library(tm)
## Warning: package 'tm' was built under R version 4.3.2
library(RWeka)
## Warning: package 'RWeka' was built under R version 4.3.2
library(slam)
## Warning: package 'slam' was built under R version 4.3.1
library(xtable)

Dataset

The Swifkey Dataset has been downloaded and unzipped manually from the below link:

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

aa_AA.blogs.txt: text obtained from blogs aa_AA.news.txt: text obtained from news feeds aa_AA.twitter.txt: text obtained from Twitter

where aa_AA denotes language and language area and is either de_DE (German), en_US (English, US), fi_FI (Finnish) or ru_RU (Russian).

This project will look only at the English language files: en_US.blogs.txt, en_US.news.txt, en_US.twitter.txt

fileInformation <- function(filepath) {
  size <- file.info(filepath)$size/1048576
  
  conn <- file(filepath, "r")
  fulltext <- readLines(conn)
  nlines <- length(fulltext)
  
  maxline <- 0
  for (i in 1:nlines) {
    linelength <- nchar(fulltext[i])
    if (linelength > maxline) { maxline <- linelength }
  }
  
  nwords <- sum(stri_count_words(fulltext))
  
  close(conn)
  
  list(size=size, nlines=nlines, maxline=maxline, nwords=nwords)
}

data_dir <- 'C:/Users/betap/Desktop/FINALLLLLLLLLL/final/en_US/'

blog_info <- fileInformation(paste0(data_dir,"en_US.blogs.txt"))
news_info <- fileInformation(paste0(data_dir,"en_US.news.txt"))
## Warning in readLines(conn): incomplete final line found on
## 'C:/Users/betap/Desktop/FINALLLLLLLLLL/final/en_US/en_US.news.txt'
twit_info <- fileInformation(paste0(data_dir,"en_US.twitter.txt"))
## Warning in readLines(conn): line 167155 appears to contain an embedded nul
## Warning in readLines(conn): line 268547 appears to contain an embedded nul
## Warning in readLines(conn): line 1274086 appears to contain an embedded nul
## Warning in readLines(conn): line 1759032 appears to contain an embedded nul
matrix(c(blog_info[1],blog_info[2],blog_info[3],blog_info[4], 
         news_info[1],news_info[2],news_info[3],news_info[4],
         twit_info[1],twit_info[2],twit_info[3],twit_info[4]), 
      nrow = 3, ncol = 4, byrow = TRUE,
      dimnames = list(c("Blogs Info:", "News Info:", "Twit Info:"),
                 c("Size (MB)", "No of Lines", "Longest Line (No characters)", "No of words")))
##             Size (MB) No of Lines Longest Line (No characters) No of words
## Blogs Info: 200.4242  899288      40833                        37546250   
## News Info:  196.2775  77259       5760                         2674536    
## Twit Info:  159.3641  2360148     144                          30093372

Sampling Data

Only a portion of the data will be used for an initial analysis, therefore getting a sample for the 3 file types for US set: blogs, news, twitter. A Corpus (collection of documents) is also created based on the 3 samples.

conb <- file("C:/Users/betap/Desktop/FINALLLLLLLLLL/final/en_US/en_US.twitter.txt", "r")

conn <- file("C:/Users/betap/Desktop/FINALLLLLLLLLL/final/en_US/en_US.news.txt", "r")

cont <- file("C:/Users/betap/Desktop/FINALLLLLLLLLL/final/en_US/en_US.blogs.txt", "r")

#first 1000 lines of text: readLines(conb, 1000)
  
blogs <-  readLines(conb, 1000)
news <-   readLines(conn, 1000)
twitter <-   readLines(cont, 1000)

corpus <- VCorpus(VectorSource(c(blogs, news, twitter)), readerControl=list(readPlain, language="en", load=TRUE))

close(conb)
close(conn)
close(cont)

Exloration and Cleaning

This section will use the text mining library ‘tm’ (loaded previously) to perform Data cleaning tasks, which are meaningful in Predictive Text Analytics. Main cleaning steps are:

1.Converting the document to lowercase 2.Removing punctuation marks 3.Removing numbers 4.Removing stopwords (i.e. “and”, “or”, “not”, “is”, etc) 5.Removing undesired terms 6.Removing extra whitespaces generated in previous 5 steps

The above can be achieve with some of the TM package functions; let’s take a look to each cleaning task, individually:

  1. Converting the document to lowercase: having the entire text in lowercase format is beneficial as it would avoid comparisons between lowercase, uppercase or a mix of those:
corpus_lowercase <- tm_map(corpus, content_transformer(tolower))
  1. Removing punctuation marks Good to note that this could generate some issues like apostrophes one, which in English are commonly used.
corpus_low_punct <- tm_map(corpus_lowercase, removePunctuation)
  1. Removing numbers As typically predicting a number is quite a challenging task, decided to remove those from the data
corpus_low_punct_no <- tm_map(corpus_low_punct, removeNumbers)
  1. Removing stopwords (i.e. “and”, “or”, “not”, “is”, etc) Stopwords are words that appear so often in the text that they are not very useful for a prediction algorimth as they don’t add too much value. A good exercise before removing this type of words would be to check how common they are in the text and decide after if they are considered stopwords or not. Nevertheless, the TM package already includes a collection of stopwords for several different languages.
corpus_low_punct_no_stop <- tm_map(corpus_low_punct_no, removeWords,stopwords("english"))
  1. Removing undesired terms In a first exploration of the datasets, we could see they contain a lot of “profanity” words, which potentially would need to be removed; nevertheless, they could have some weight in the prediction results so therefore we can always consider this step at a later stage, depending on needs.

6.Removing extra whitespaces generated in previous 5 steps

corpus_low_punct_no_stop_white <- tm_map(corpus_low_punct_no_stop, stripWhitespace)

Analysis

Data is now cleaned and ready to be analysed, so for instance we could check:

  1. Some words are more frequent than others - what are the distributions of word frequencies?
  2. What are the frequencies of 2-grams and 3-grams in the dataset? The above can be achieve by tokenizing the data as: Unigram (1-Gram), Bigram (2-Gram), Trigram (3-Gram)
# 1 Gram
 
gram1 = as.data.frame((as.matrix(  TermDocumentMatrix(corpus_low_punct_no_stop_white) )) ) 
gram1v <- sort(rowSums(gram1),decreasing=TRUE)
gram1d <- data.frame(word = names(gram1v),freq=gram1v)
gram1d[1:10,]
##      word freq
## said said  304
## will will  259
## one   one  254
## just just  249
## like like  248
## can   can  191
## time time  191
## new   new  186
## get   get  171
## know know  144
# 2 Gram
bigram <- function(x) NGramTokenizer(x, Weka_control(min = 2, max = 2))
gram2= as.data.frame((as.matrix(  TermDocumentMatrix(corpus_low_punct_no_stop_white,control = list(tokenize = bigram)) )) ) 
gram2v <- sort(rowSums(gram2),decreasing=TRUE)
gram2d  <- data.frame(word = names(gram2v),freq=gram2v)
gram2d[1:10,]
##                    word freq
## new york       new york   26
## last year     last year   19
## last night   last night   15
## right now     right now   15
## feel like     feel like   12
## new jersey   new jersey   12
## one day         one day   12
## dont know     dont know   11
## high school high school   11
## last week     last week   11
# 3 Gram
trigram <- function(x) NGramTokenizer(x, Weka_control(min = 3, max = 3))
gram3 = as.data.frame((as.matrix(  TermDocumentMatrix(corpus_low_punct_no_stop_white,control = list(tokenize = trigram)) )) ) 
gram3v <- sort(rowSums(gram3),decreasing=TRUE)
gram3d <- data.frame(word = names(gram3v),freq=gram3v)
gram3d[1:10,]
##                                    word freq
## cinco de mayo             cinco de mayo    5
## cricket world cup     cricket world cup    4
## new york city             new york city    4
## hyun suk asks             hyun suk asks    3
## new york times           new york times    3
## osama bin laden         osama bin laden    3
## rock paper scissors rock paper scissors    3
## team leader han         team leader han    3
## world cup dvd             world cup dvd    3
## ” said “                       ” said “    2

Histogram of the 30st Top Unigrams

ggplot(gram1d[1:30,], aes(x=reorder(word, freq),y=freq)) + 
        geom_bar(stat="identity", width=0.5, fill="tomato2") + 
        labs(title="Unigrams")+
        xlab("Unigrams") + ylab("Frequency") + 
        theme(axis.text.x=element_text(angle=65, vjust=0.6))

## WordCloud of the 20st Top BiGrams

wordcloud2(gram2d[1:20,],size=1.6,shape = 'star')

Interesting findings in the dataset

When loading the data, “news” has an incomplete final line; “twitter” set seems to contain some nulllines. As per error processing info displayed.

There are still some accents that weren’t completely removed in the cleaning step; it would be cleaner for the algorithm to remove those in a second cleaning round.

Feedback on plans for creating a prediction algorithm and Shiny app