The goal of this project is just to display that you’ve gotten used to working with the data and that you are on track to create your prediction algorithm. Please submit a report on R Pubs (http://rpubs.com/) that explains your exploratory analysis and your goals for the eventual app and algorithm. This document should be concise and explain only the major features of the data you have identified and briefly summarize your plans for creating the prediction algorithm and Shiny app in a way that would be understandable to a non-data scientist manager. You should make use of tables and plots to illustrate important summaries of the data set. The motivation for this project is to: 1. Demonstrate that you’ve downloaded the data and have successfully loaded it in.2. Create a basic report of summary statistics about the data sets.3. Report any interesting findings that you amassed so far.4. Get feedback on your plans for creating a prediction algorithm and Shiny app.
This report is structure in 2 parts. The first comprising a very preliminary analysis, considering only the first 3 lines of the file en_US.twitter.txt, so that it is possible to visualize the data and understand the changes introducing by the data reshaping. The second part Exploratory analysis, performs a more extensive analysis of the three files in the project, comparing the statistics of each and outlying the steps for a predictive algorithm. For time efficiency, only 10% of each file was used for this exploration. The reader can choose to jump to section two without loosing generality of the analysis.
For this part of the exploration I will only loaded only 3 lines of the file “en_US.twitter.txt”. This will be to be able to have a proper understanding of each one of the steps and the results before moving forward. Few things to note:
files<-"Coursera-SwiftKey/final/en_US/en_US.twitter.txt"
con_en <- file(files, "r")
sample<-readLines(con_en, 3)
close (con_en)
corpus<-VCorpus(VectorSource(sample)) # build the corpus
corpus<-tm_map(corpus, removePunctuation, preserve_intra_word_contractions=TRUE , preserve_intra_word_dashes = TRUE) #removing punctuation and keeping apostrophes
corpus<-tm_map(corpus, content_transformer(tolower)) #converting all words to lowercase
corpus<-tm_map(corpus, removeNumbers) #remove numbers
#profanitywords <- read.delim(paste0(path,file4),header=FALSE,skip=13,encoding = "UTF-8" )
#corpusClean = tm_map(corpusClean, removeWords, profanitywords$V1)
#rm(profanitywords)
#corpus<-tm_map(corpus, removeWords, stopwords())
#corpus<-tm_map(corpus, stemDocument, "english")
We can clearly see the effect of these transformations from the original text
sample
## [1] "How are you? Btw thanks for the RT. You gonna be in DC anytime soon? Love to see you. Been way, way too long."
## [2] "When you meet someone special... you'll know. Your heart will beat more rapidly and you'll smile for no reason."
## [3] "they've decided its more fun if I don't."
as.character(corpus[[1]])
## [1] "how are you btw thanks for the rt you gonna be in dc anytime soon love to see you been way way too long"
as.character(corpus[[2]])
## [1] "when you meet someone special you'll know your heart will beat more rapidly and you'll smile for no reason"
as.character(corpus[[3]])
## [1] "they've decided its more fun if i don't"
BigramTokenizer <- function(x) {
unlist(lapply(ngrams(words(x), 2), paste, collapse = " "), use.names = FALSE)
}
#creating the bag of words model
dtm <-DocumentTermMatrix(corpus,control=list(wordLengths=c(1, Inf))) # It will take words from 1 character to infinity
dtm.bigram <- DocumentTermMatrix(corpus, control=list(tokenize = BigramTokenizer, wordLengths=c(1,Inf)))
#dtm<-rmoveSparseTerms(dtm,0.999) # I will now use this here, as my sample is already a minimal subset.
inspect(dtm)
## <<DocumentTermMatrix (documents: 3, terms: 44)>>
## Non-/sparse entries: 47/85
## Sparsity : 64%
## Maximal term length: 7
## Weighting : term frequency (tf)
## Sample :
## Terms
## Docs and anytime are be beat for more way you you'll
## 1 0 1 1 1 0 1 0 2 3 0
## 2 1 0 0 0 1 1 1 0 1 2
## 3 0 0 0 0 0 0 1 0 0 0
names(dtm)
## [1] "i" "j" "v" "nrow" "ncol" "dimnames"
dtm$i
## [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## [39] 2 3 3 3 3 3 3 3 3
dtm$j
## [1] 2 3 4 6 7 8 11 13 15 18 21 22 28 29 32 34 35 37 38 39 42 1 5 11 14
## [26] 20 23 24 25 26 27 30 31 33 40 41 42 43 44 9 10 12 16 17 19 24 36
dtm$dimnames
## $Docs
## [1] "1" "2" "3"
##
## $Terms
## [1] "and" "anytime" "are" "be" "beat" "been" "btw"
## [8] "dc" "decided" "don't" "for" "fun" "gonna" "heart"
## [15] "how" "i" "if" "in" "its" "know" "long"
## [22] "love" "meet" "more" "no" "rapidly" "reason" "rt"
## [29] "see" "smile" "someone" "soon" "special" "thanks" "the"
## [36] "they've" "to" "too" "way" "when" "will" "you"
## [43] "you'll" "your"
inspect(dtm.bigram)
## <<DocumentTermMatrix (documents: 3, terms: 48)>>
## Non-/sparse entries: 48/96
## Sparsity : 67%
## Maximal term length: 15
## Weighting : term frequency (tf)
## Sample :
## Terms
## Docs and you'll anytime soon are you be in beat more been way btw thanks
## 1 0 1 1 1 0 1 1
## 2 1 0 0 0 1 0 0
## 3 0 0 0 0 0 0 0
## Terms
## Docs dc anytime decided its for no
## 1 1 0 0
## 2 0 0 1
## 3 0 1 0
names(dtm.bigram)
## [1] "i" "j" "v" "nrow" "ncol" "dimnames"
dtm.bigram$i
## [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## [39] 2 2 2 3 3 3 3 3 3 3
dtm.bigram$j
## [1] 2 3 4 6 7 8 11 13 15 18 21 27 28 31 33 34 36 37 38 39 42 43 44 1 5
## [26] 10 14 20 22 24 25 26 29 30 32 40 41 45 46 47 48 9 12 16 17 19 23 35
dtm.bigram$dimnames
## $Docs
## [1] "1" "2" "3"
##
## $Terms
## [1] "and you'll" "anytime soon" "are you" "be in"
## [5] "beat more" "been way" "btw thanks" "dc anytime"
## [9] "decided its" "for no" "for the" "fun if"
## [13] "gonna be" "heart will" "how are" "i don't"
## [17] "if i" "in dc" "its more" "know your"
## [21] "love to" "meet someone" "more fun" "more rapidly"
## [25] "no reason" "rapidly and" "rt you" "see you"
## [29] "smile for" "someone special" "soon love" "special you'll"
## [33] "thanks for" "the rt" "they've decided" "to see"
## [37] "too long" "way too" "way way" "when you"
## [41] "will beat" "you been" "you btw" "you gonna"
## [45] "you meet" "you'll know" "you'll smile" "your heart"
From this preliminary analysis we can see that apostrophes are kept, although contracted words are recognized as a single word. We can look at the frequency of words in the mono-grams and bi-grams:
dtm_tidy<-tidy(dtm)
dtm_tidy_bigram<-tidy(dtm.bigram)
term.count <- dtm_tidy %>% group_by(term) %>% summarize(n.total=sum(count)) %>% arrange(desc(n.total))
term.count_bigrams <- dtm_tidy_bigram %>% group_by(term) %>% summarize(n.total=sum(count)) %>% arrange(desc(n.total))
frequencies <- data.table(tok = term.count$term, freq = term.count$n.total, n="monograms")
frequencies <- rbind(frequencies,data.table(tok = term.count_bigrams$term, freq = term.count_bigrams$n.total, n="bigrams"))
ggplot(frequencies[frequencies$n=="monograms",][1:25,], aes(x = reorder(tok,freq), y = freq)) + coord_flip() +
geom_bar(stat = "identity", fill = "darkgreen") + theme_bw() +
ggtitle("Frequency of Top 25 monograms") +labs(x = "", y = "")
ggplot(frequencies[frequencies$n=="bigrams",][1:25,], aes(x = reorder(tok,freq), y = freq)) + coord_flip() +
geom_bar(stat = "identity", fill = "darkgreen") + theme_bw() +
ggtitle("Frequency of Top 25 bigrams") +labs(x = "", y = "")
As excpected for the lower sampling, bi-grams appear only once in this corpus.
Next I will extend this analysis to all words into the twitter file. Later I will compare any bias between the statistics in the different files provided. For this I will first write a function to systematically do the analysis, then plot the frequencies and discuss the number of words in the dictionary needed to cover 50% and 90% of the words in the corpus. To note, as the number of elements increased, now more elements of the dtm matrix will be unique, or sparce, (it can be seen by the “original Sparsity” value printed below, therefore I will use rmoveSparseTerms with a value of 0.999 (“For example, if you set sparse = 0.999 as the argument to removeSparseTerms(), then this will remove only terms that are more sparse than 0.999.”, extracted from https://stackoverflow.com/questions/28763389/how-does-the-removesparseterms-in-r-work).
frequencies<-function(file, lines){
con_en <- file(files, "r")
sample<-readLines(con_en, lines)
close (con_en)
corpus<-VCorpus(VectorSource(sample)) # build the corpus
corpus<-tm_map(corpus, removePunctuation, preserve_intra_word_contractions=TRUE , preserve_intra_word_dashes = TRUE) #removing punctuation and keeping apostrophes
corpus<-tm_map(corpus, content_transformer(tolower)) #converting all words to lowercase
corpus<-tm_map(corpus, removeNumbers) #remove numbers
dtm<-DocumentTermMatrix(corpus,control=list(wordLengths=c(1, Inf)))
dtm.bigram <- DocumentTermMatrix(corpus, control=list(tokenize = BigramTokenizer, wordLengths=c(1,Inf)))
print(c("original Sparsity=", round(sparsity(dtm, proportion = TRUE),3)))
print(c("original size=", dim(dtm)))
dtm<-removeSparseTerms(dtm,0.999)
#dtm.bigram<-removeSparseTerms(dtm.bigram,0.999)
print(c("final Sparsity (0.999)=", round(sparsity(dtm, proportion = TRUE),3)))
print(c("final size=", dim(dtm)))
dtm_tidy<-tidy(dtm)
dtm_tidy_bigram<-tidy(dtm.bigram)
term.count <- dtm_tidy %>% group_by(term) %>% summarize(n.total=sum(count)) %>% arrange(desc(n.total))
term.count_bigrams <- dtm_tidy_bigram %>% group_by(term) %>% summarize(n.total=sum(count)) %>% arrange(desc(n.total))
frequencies <- data.table(tok = term.count$term, freq = term.count$n.total, n="monograms")
frequencies <- rbind(frequencies,data.table(tok = term.count_bigrams$term, freq = term.count_bigrams$n.total, n="bigrams"))
}
plot_freqs<-function(data,type, title){
ggplot(data[data$n==type,][1:25,], aes(x = reorder(tok,freq), y = freq/sum(freq))) + coord_flip() +
geom_bar(stat = "identity", fill = "darkgreen") + theme_bw() +
ggtitle(title) +labs(x = "", y = "")
}
file<-"Coursera-SwiftKey/final/en_US/en_US.twitter.txt"
lines<-sapply(file,countLines)
print(paste("lines in file ", sub("Coursera-SwiftKey/final/en_US/", "", file)," = ", as.numeric(lines)))
## [1] "lines in file en_US.twitter.txt = 2360148"
frequencies_twiter<-frequencies(file,lines/10)
## [1] "original Sparsity=" "1"
## [1] "original size=" "236014" "113819"
## [1] "final Sparsity (0.999)=" "0.993"
## [1] "final size=" "236014" "1210"
## [1] "lines in file en_US.news.txt = 1010242"
## [1] "original Sparsity=" "1"
## [1] "original size=" "101024" "66441"
## [1] "final Sparsity (0.999)=" "0.993"
## [1] "final size=" "101024" "1216"
## [1] "lines in file en_US.blogs.txt = 899288"
## [1] "original Sparsity=" "1"
## [1] "original size=" "89928" "61705"
## [1] "final Sparsity (0.999)=" "0.993"
## [1] "final size=" "89928" "1220"
t<-plot_freqs(frequencies_twiter,"monograms","twitter")
n<-plot_freqs(frequencies_news,"monograms","News")
b<-plot_freqs(frequencies_blogs,"monograms","Blogs")
G<-ggarrange(t, n, b + rremove("x.text"), ncol = 3, nrow = 1)
annotate_figure(G,top = text_grob("Monograms", color = "black", face = "bold", size = 14))
t<-plot_freqs(frequencies_twiter,"bigrams","twitter")
n<-plot_freqs(frequencies_news,"bigrams","News")
b<-plot_freqs(frequencies_blogs,"bigrams","Blogs")
G<-ggarrange(t, n, b + rremove("x.text"), ncol = 3, nrow = 1)
annotate_figure(G,top = text_grob("bigrams", color = "black", face = "bold", size = 14))
From this exploration it is possible to see that the there is not substantial difference in the monogram frequency among the different data sources (although so and then appear in different order in twitter and news relative to blogs). The frequency of bigrams is also consistent although in this case there are terms in different order. This all can be due to the sample size that was used for this exploration.
To finish this report I will present a preliminary algorithm for text prediction based on the distribution of bigrams, and I will compare the results obtained with the different sources. (I based this approach from from https://rpubs.com/HN317/531772)
splitTokenbigram = function(x){
prefix = character(nrow(x))
rest = character(nrow(x))
tmp <- strsplit(x$tok, " ", fixed=TRUE)
for(i in 1:nrow(x)){
prefix[i] = paste(tmp[[i]][1]) #,tmp[[i]][2])
rest[i] = tmp[[i]][2]
}
x$prefix <- prefix
x$rest <- rest
#list(prefix=prefix, rest=rest)
return(x)
}
outputbigram = function(x,data){
paste (x, head(subset(data, prefix == x), 3)$rest, sep=" ")
}
freq<-frequencies_twiter[frequencies_twiter$n=="bigrams",]
bigrams_twiter <- splitTokenbigram(freq)
#head(bigrams_twiter)
freq<-frequencies_news[frequencies_news$n=="bigrams",]
bigrams_news <- splitTokenbigram(freq)
freq<-frequencies_blogs[frequencies_blogs$n=="bigrams",]
bigrams_blogs <- splitTokenbigram(freq)
We can check this model by predicting the word following to the, the most frequent monogram:
twitter<-outputbigram('the',bigrams_twiter)
news<-outputbigram('the',bigrams_news)
blogs<-outputbigram('the',bigrams_blogs)
rbind(twitter,news,blogs)
## [,1] [,2] [,3]
## twitter "the best" "the same" "the world"
## news "the best" "the same" "the world"
## blogs "the best" "the same" "the world"
In this case, there is not difference between the different data sets, but further inspection is needed. The ultimate goal is to combine them togheter, but characterising any possible bias first.