Reading data

library(tm)
library(stringr)
library(wordcloud)
library(ggplot2)
library(dplyr)
library(tidyr)

path <- '../data-raw/en_US/'
blogs <- readLines(paste0(path, 'en_US.blogs.txt'))
news <- readLines(paste0(path, 'en_US.news.txt'))
twitter <- readLines(paste0(path, 'en_US.twitter.txt'))
## Warning in readLines(paste0(path, "en_US.twitter.txt")): line 167155
## appears to contain an embedded nul
## Warning in readLines(paste0(path, "en_US.twitter.txt")): line 268547
## appears to contain an embedded nul
## Warning in readLines(paste0(path, "en_US.twitter.txt")): line 1274086
## appears to contain an embedded nul
## Warning in readLines(paste0(path, "en_US.twitter.txt")): line 1759032
## appears to contain an embedded nul
l_blogs <- sapply(blogs, str_length)
l_news <- sapply(news, str_length)
l_twitter <- sapply(twitter, str_length)

n_blogs <- length(blogs)
n_news <- length(news)
n_twitter <- length(twitter)

Some descriptive analsys

Blogs data has 899288 lines, news data has 1010242 lines and twitter data has 2360148 lines.

Line length histograms

We can see that, as twitter texts are truncated, we have at most 140 line length. It is curious to see what happens around 130 lengths.

To best visualize the blogs and news data, I had to use a log scale, because the data is asymmetric. We can see that, even with log scale, blogs news data still asymmetric, to the same side.

qplot(l_twitter, binwidth = 1)

qplot(l_blogs) + scale_x_log10()

qplot(l_news) + scale_x_log10()

Word counts

I have tried to clean the “twitter” data, removing stop words, punctuation and numbers. I worked with a sample to save computation time for this initial study.

# this set seed is in honor of LaplacesDemon R package.
set.seed(666)
twitter_sample <- twitter[sample(1:length(twitter), 10000)]

# works only in linux
rm_accent <- function(x) gsub("`|\\'", "", iconv(x, to = "ASCII//TRANSLIT"))

d_tm_raw <- VCorpus(VectorSource(twitter_sample))

d_tm <- d_tm_raw %>%
  tm_map(stripWhitespace) %>%
  tm_map(content_transformer(tolower)) %>%
  tm_map(removeWords, stopwords('en')) %>%
  tm_map(removePunctuation, preserve_intra_word_dashes = TRUE) %>%
  tm_map(content_transformer(rm_accent)) %>%
  tm_map(removeNumbers) %>% 
  tm_map(stripWhitespace)

After cleaning the twitter data, I created a document term frequency matrix. Here are the 20 most frequent words. The results are somewhat intuitive, with words like “just”, “like” and “love” being the most recent. We can also see “lol”, that is not an english word, but is widely used in internet context.

dtm <- DocumentTermMatrix(d_tm)
dtm <- removeSparseTerms(dtm, 0.99)

d_dtm <- data.frame(as.matrix(dtm)) %>%
  add_rownames() %>%
  tbl_df()

word_count <- d_dtm %>%
  mutate(rowname = as.numeric(rowname)) %>%
  gather(key, val, -rowname) %>%
  arrange(desc(val)) %>%
  group_by(key) %>%
  summarise(val = sum(val)) %>%
  ungroup() %>%
  arrange(desc(val), key)

knitr::kable(head(word_count, 20))
key val
just 613
like 503
love 498
get 482
good 453
can 399
will 395
thanks 393
day 377
know 365
one 337
now 333
time 304
today 302
lol 295
great 294
new 288
see 276
got 244
going 242

Then tried to create a document term matrix with tf-idf weighting. Non-technically speaking, this algorithm tries to give a score of “relevance” or “information” for each term in each document. Then I selected the “most important” word of each tweet and plotted with word cloud. As we can see, the words “get”, “can” and “just” and “day” appears to be the most important in a high number of documents. These words, however, do not appear to be so meaningful. Maybe we will need to consider some of these words differently to build the prediction model.

ctrl <- list(weighting = function(x) weightTfIdf(x, normalize = FALSE))
dtm2 <- DocumentTermMatrix(d_tm, control = ctrl)
dtm2 <- removeSparseTerms(dtm, 0.99)

d_dtm_tfidf <- data.frame(as.matrix(dtm2)) %>%
  add_rownames() %>%
  tbl_df()

words <- d_dtm_tfidf %>%
  mutate(rowname = as.numeric(rowname)) %>%
  gather(key, val, -rowname) %>%
  arrange(desc(val)) %>%
  group_by(rowname) %>%
  slice(1) %>%
  ungroup %>%
  filter(val > 0)

set.seed(123)
wordcloud(words$key, 
          max.words = 50, 
          colors = brewer.pal(8, 'Dark2'))

Plans for building the prediction algorithm and shiny app

Some colleagues in Brazil have developed an awesome model that do not use n-grams to predict the words, but variable k-grams.

The model is a “variable length” stochastic process, and considers different number of words, depending on the word. This is a link resuming the model (in portuguese).

I’ll try to program this model in R and compare it with n-gram based models.

For the shiny app, I’ll let the user choose one in some different algorithms, and write some sentences. The app will show some options for the next word in a box, and the user could click on one of there options to include the word. It’s almost like SwiftKey app.