Introduction

This is the first report of the Capstone Project of the Coursera Data Science course. The report presents the results of the exploratory analysis of the data. The exploratory analysis contemplates the descriptions of the contents of each of the datasets, describing it’s basic characteristics regrading the size and structure of the data, as well as statistical analysis and processing of the text information contained.

The local functions that are used can be seen in the Appendix


Analysis

Reading the data

Firstly, the text data is read into an list object txts that contains the data from the archives found in the specified path.

datapath <- "final/en_US/"

files <- list.files(path = datapath, pattern = "*.txt", full.names = T)
nam <- str_match(files, "\\.(.*?)\\.")[, 2]

txts <-
    files %>%
    set_names(nam) %>%
    map(~ read_lines(.))

Datasets statistics

Once the files are loaded into memory, some basic statistic information is calculated, such as the byte size, the number of lines and number of words for each dataset.

bytes <- map_dbl(files, file.size)

tibble(dataset = nam,
       bytes = bytes,
       lines = map(txts, ~ length(.x)),
       words = map(txts, ~ sum(str_count(.x, boundary("word")))),
       char = map(txts, ~ sum(str_count(.x)))) %>% 
    unnest(cols = c("dataset", "bytes", "lines", "words", "char"))
dataset bytes lines words char
blogs 210160014 899288 37546246 206824257
news 205811889 1010242 34762395 203223153
twitter 167105338 2360148 30093369 162095765

As the analysis reveals, the blogs dataset is the biggest one, and strikingly has much longer sentences than both the news and the twitter datasets. As the datasets are quite large, the rest of the analysis will contemplate a sample of full datasets.


Dataset sampling

As the datasets are rather large, they are sampled with a variable percentage (perc) of the lines for each document extracted.

perc <- 0.05

set.seed(41)
samp_txt <- 
    map(txts, ~sample(.x, abs(length(.x) * perc)))


tibble(dataset = nam,
       bytes = map(samp_txt, ~object.size(.x)),
       lines = map(samp_txt, ~ length(.x)),
       words = map(samp_txt, ~ sum(str_count(.x, boundary("word")))),
       char = map(samp_txt, ~ sum(str_count(.x)))) %>% 
    unnest(cols = c("dataset", "bytes", "lines", "words", "char"))
dataset bytes lines words char
blogs 13256160 bytes 44964 1853448 10209787
news 13472072 bytes 50512 1734912 10141224
twitter 16901000 bytes 118007 1506809 8116279

The sample analysed consists on a 5% of the total lines for each dataset.


Statistic analysis

A first approach is to calculate some statistic properties of the distribution of the number of characters (chars) and the number of words (words) for the items of the three different datasets.

First, we calculate the central tendencies of the count of words. The table below show; the 5% quantile (q05) , the median (q50), the 95% quantile (q95) and the mean.

stats <- 
    map_df(samp_txt, function(y) {
        tibble(words = map_dbl(y, ~ str_count(.x, boundary("word"))),
               chars = map_dbl(y, ~ str_count(.x)))
    }, .id = "name")

stats %>%
    group_by(name) %>%
    summarise(
        q05 = quantile(words, probs = c(.05)),
        q50 = median(words),
        q95 = quantile(words, probs = c(.95)),
        mean = mean(words))
name q05 q50 q95 mean
blogs 3 28 124 41.22071
news 5 32 73 34.34653
twitter 3 12 25 12.76881

The distribution of words among lines is very skewed to the left. There is a lot of text that consists in short lines, and fewer texts which have a much longer extension.


Secondly, the distribution of the counts of chars and words are plotted as histograms. The \(x\) axis is transformed into a \(log_{10}\) scale, as the distributions are quite skewed to the left.

stats %>%
    gather(key, value, -name) %>%
    ggplot(aes(x = value)) +
    geom_histogram(color = "black", fill = "grey70", bins = 50) +
    scale_x_log10() +
    facet_grid(name ~ key,scales = "free") +
    theme_clean()

For the three datasets, there are quite a few instances that have few words / characters. One alternative to have in mind is that the instances with few words could be filtered out; they give less information and may only consume processing power.


Text analysis

Corpus creation

The text data is used to build a text corpus using the quanteda library.

cp <-
    tibble(doc_id = names(samp_txt),
           text =  map(samp_txt, ~ paste(.x, collapse = '\n '))) %>%
    unnest(cols = c(doc_id, text)) %>%
    corpus()

Token extraction

The tokens area extracted from the corpus. The text is cleaned removing any numbers, punctuation marks, symbols, special twitter characters, and hyphens.

toks <-
    cp %>%
    tokens(
        remove_numbers = T,
        remove_punct = T,
        remove_symbols = T,
        remove_separators = T,
        remove_twitter = T,
        remove_hyphens = T, 
        ngrams = 1L, 
    )

Document-feature matrix

With the tokens list we create document-feature matrices (DFM) using the function dfm() of the quanteda package. The creation of document feature matrices help to extract n-grams.


1-grams

frequency

A DFM is created for unigram terms. Stop words are removes, to provide more sens full information.

dfm_unigram <-  
    toks %>%
    dfm()

With the unigram DFM we can explore the most frequent unigrams. It makes more sense to remove the stop words, to have a better understanding of the semantic content and richness of each dataset, but for the n-gram model we should try both the complete and the revised dataset.


dfm_unigram %>%
    dfm_remove(stopwords("english")) %>%
    plot_n_top(15)

dfm_unigram %>%
    dfm_remove(stopwords("english")) %>%
    textplot_wordcloud(
        max_words = 300,
            color = brewer_pal("qual", 3)(6))

One of the things that one can notice in the twitter dataset is the presence of frequent, strange tokens, that are used in Twitter slang, such as rt. This tokens should be dealt properly.


corpus specific terms

To see more specific terms used only in one of the corpus we can easily weight the DFM by term frequency-inverse document frequency. This allows to see which words are most used in each of the corpus (while not being used in the others)

dfm_unigram %>%
    dfm_tfidf() %>%
    dfm_sort() %>%
    textplot_wordcloud(
        min_size = 1,
        max_size = 5,
        rotation = 0.2,
        comparison = T,
        max_words = 100,
            color = tableau_color_pal()(3))

AS seen before, the Twitter corpus has some slang terms, and it uses some profanity words that should also be dealt with with a profanity filter.


word coverage exploration

We proceed to explore the words coverage of the frequency ordered token vector. A line for the coverage of the 50% and 90% of the total tokens is plotted.

cumsum_uni <- 
    plot_cumsum(dfm_unigram, c(.5,.9))

cumsum_uni$plot

From the plot we can confirm that the frequency distribution of words is very long tailed. 50% of the tokens are covered with only 143 words, while 7409 are needed to cover up to 90%. This corresponds to 0.0% and 2.0% of the words, respectively. This should be accounted for as it can help to considerably reduced the size of the models used.


2-grams

In the case of the 2-grams, it makes sense to explore the 2-grams both for tokens with and without stop words. Both models should be accounted to see how they behave.

# dfm_s
dfm_2gram <- 
    toks %>%
    tokens_tolower() %>%
    tokens_ngrams(n = 2L, concatenator = " ") %>%
    dfm()

dfm_2gram_nonstop <- 
    toks %>%
    tokens_tolower() %>%
    tokens_remove(stopwords("english")) %>%
    tokens_ngrams(n = 2L, concatenator = " ") %>%
    dfm()
    
dfm_2gram %>%
    plot_n_top(15) + labs(title = "Frequency of uni-grams, with stopwords")

dfm_2gram_nonstop %>%
    plot_n_top(15) + labs(title = "Frequency of uni-grams, without stopwords")

dfm_2gram %>%
    textplot_wordcloud(
        max_words = 300,
        color = brewer_pal("qual", 3)(6))


2-gram coverage exploration

We proceed to explore the words coverage of the frequency ordered token vector. A line for the coverage of the 50% and 90% of the total tokens is plotted.

cumsum_2 <- 
    plot_cumsum(dfm_2gram, c(.5,.9))

cumsum_2_non <- 
    plot_cumsum(dfm_2gram_nonstop, c(.5,.9))

cumsum_2$plot + labs(title = "Cumulative % of 2-grams with stop words")

cumsum_2_non$plot

Regarding 2-grams, their distribution is less long tailed, specially in the case which does not include stop words although, they are still skewed to the left as only 4.386310^{4} types cover 50% of the 2-gram model which is 5020797 long.


3 grams

dfm_3gram <- 
    toks %>%
    tokens_tolower() %>%
    tokens_ngrams(n = 3L, concatenator = " ") %>%
    dfm()

dfm_3gram_nonstop <- 
    toks %>%
    tokens_tolower() %>%
    tokens_remove(stopwords("english")) %>%
    tokens_ngrams(n = 3L, concatenator = " ") %>%
    dfm()
    
dfm_3gram %>%
    plot_n_top(15) + labs(title = "Frequency of 3-grams, with stop words")

dfm_3gram_nonstop %>%
    plot_n_top(15) + labs(title = "Frequency of 3-grams, without stop words")

dfm_3gram %>%
    textplot_wordcloud(
        max_words = 300,
        color = brewer_pal("qual", 3)(6))


3-gram coverage exploration

cumsum_3 <- 
    plot_cumsum(dfm_3gram, c(.5,.9))

cumsum_3_non <- 
    plot_cumsum(dfm_3gram_nonstop, c(.5,.9))

cumsum_3$plot + labs(title = "Cumulative % of 3-grams with stop words")

cumsum_3_non$plot

Analysis of less frequent n-grams

1-grams

We can explore the less frequent terms to see their characteristics.

plot_rare(dfm_unigram, 1, 5)

# Print a sample of less frequent unigrams
set.seed(41)
dfm_unigram %>%
    textstat_frequency() %>%
    filter(frequency == 1) %>%
    sample_n(50) %>%
    pull(feature) %>%
    pander()

baldry, geographies, monsterenergydrink, thingsthatbotherme, fermention, leadershipchat, gour, 15oz, realpr, inever, naderi, آسیا, sheree, braverman, follwer, sulfation, lanston, nyvs, garciaparra, fossa, merchbitch, semoball, falconstor, ifttt, blackstock’s, spiles, hazem, sprint’s, wolfslair, larimore, denizen, ilbo, pee’ing, stemme, nxqqaz, sbus, rutine, temne, sldkgjshfgkjshfgkusdfjhgkljsdfhgnklsjdhfgksjdh, miscavige’s, jianxin, jeopardised, wykle, toastieness, nanchang, spingarn, cedc, dropdox, exstraordinaire and life.com


a sample of the terms show that there are comprised of orthographic errors, slang words, and some words in other language.

2-grams

dfm_2gram %>%
    plot_rare(1, 5)

# Print a sample of less frequent bigrams
set.seed(41)
dfm_2gram %>%
    textstat_frequency() %>%
    filter(frequency == 1) %>%
    sample_n(50) %>%
    pull(feature) %>%
    pander()

said edward, and dicing, briefs all, media success, back segments, randomized double, quality test, and inxpo, on clifford, michael been, time serving, left play, band replaced, a geocities, cookbook she’s, all making, its 11am, in wilful, or shooters, favorite articles, himself arjuna, got shawasted, audition june, on hip, jersey gets, skilled but, humphreys chased, laws overhauled, josey more, bravely about, ce tv, tamie i’m, franchise along, addiction their, doing we’d, scholarships have, letters all, quo so, two you’ll, against single, crisp so, of settlements, one farms, participating restaurants, dispatchment of, awesomee people, ac golden, idea u, attending parties and leisure embarrassed


3-grams

dfm_3gram %>%
    plot_rare(1, 5)

# Print a sample of less frequent trigrams
set.seed(41)
dfm_3gram %>%
    textstat_frequency() %>%
    filter(frequency == 1) %>%
    sample_n(50) %>%
    pull(feature) %>%
    pander()

too funny that, he continued seemingly, and poetry i, i miss ucla, husband pointed out, there gab and, with a twenty, words the argument, westville’s parkview school, goin the the, he is mighty, gestures as empty, concentration on a, still it’s the, tailors her writing, that my shop, me back1 thankyoulord, folds that can, grill we had, so true boryan, ave middlesex county, too are called, good luck let’s, vol simply leave, averages about 64k, phillips to florida, within it demoff, spurs fans i’m, denied in its, awake is finally, gold star scribbler, work do not, republicans have blamed, test every two, wall to request, do love ya, whether people consider, for inmates sentenced, tap at the, consumerism veils the, with its approach, refuge awareness of, me again bitch, at all israel, could sense the, even know consider, monitoring program for, despair last week, tired the day and whisky association a


Model

The prediction of the next word could be attained by a model that goes through a Markov process that looks for coincidence in the N-1 model. If it does not find a coinsidence it searches in the N-k, until it reaches k=1, when it just return a list of the most frequent unigram.

  1. The model will attempt to take \(k\) words from the input and compare the input \(k-gram\) with the \(n-gram\) models, assuming \(n = k+1\)
  2. If the model encounters a coincidence in the dataset, the last word \(n\) is returned.
  3. If no coincidence is found, the process begins again with \(k = k-1\)
  4. If \(k = 2\) and no coincidence is met, then a list of the most frequent unigrams is returned.

Conclusion

The three datasets are probably a good source to build a predicting model. The blogs and news datasets are more similar, while the twitter dataset has some differences, that mainly have to do with the character limitation of tweets, and probably to the use of a more informal style of language.

There are some terms that may have to be manually extracted, especially in the twitter dataset, which has some specific slang terms (p.e. “rt”). Other anomalous terms or words in other language should be accounted as explained in the next paragraph, as they are very unusual. There also may be the need to filter profanity words.

For a model that is suitable and fast enough there has to be some trimming and selection of the information, as the whole dataset is too big to build a useful model. In what regards to words coverage, the distribution for word frequencies is very long tailed, with a large amount of words with a very low frequency. One strategy for building a better model could be to drop this unusual terms. One of the things that has to be examined, is which types will be considered unusual and can be dropped to gain speed over loosing as least coverage as possible. As we could see in the unigram model, we can get a model coverage of up to 90% with just around 2.0% of the tokens. With this information plus the fact that just above 70% of the tokens only appear once, it is safe to eliminate words that only appear up to around 3 or 4 times. Other approach could be to trim the DFM from below to a certain percentage, taking into account the information about coverage.


Further steps

  • Partition the data into a train and test set
  • Creation of the n-gram model.
    • Clean data of profanity, and special words
    • Decide one criteria for exclusion; eliminate short lines of text and/or exlude words based on low frequency
      • decide number of n
    • decide if removing stopwords or not
  • Test model

Appendix

Local Functions

plot_n_top <- function(dfm, n){ 
    dfm %>%
        textstat_frequency(groups = docnames(dfm_unigram), ties_method = 'first') %>%
        group_by(group) %>%
        top_n(n,-rank) %>%
        ggplot(aes(reorder_within(feature, frequency, group), frequency, fill = group)) +
        geom_col() +
        coord_flip() +
        scale_x_reordered() +
        facet_wrap( ~ group, scales = "free_y") +
        guides(fill = F) +
        scale_fill_tableau() +
        theme_clean() +
        labs(title = "Frequency of n-grams", x = "n-grams", y = "frequency")}

plot_cumsum <- function(dfm, percs) {
    # function to plot the cumulative sum of the ordered frequencies of the n-grams
    cums <-
        dfm %>%
        textstat_frequency() %>%
        mutate(prob = frequency / sum(frequency),
               cumprob = cumsum(prob)) %>%
        rowid_to_column()
    
    dats <-
        map_dbl(percs, ~ which(abs(cums$cumprob - .x) == min(abs(
            cums$cumprob - .x))))
    
    plot <-
        cums %>%
        ggplot(aes(rowid, cumprob)) +
        geom_line(color = "darkgreen") +
        geom_vline(xintercept = dats,
                   color = "darkred",
                   alpha = .75) +
        theme_clean() +
        scale_x_continuous(breaks = seq(0 , max(cums$rowid), 10 ^ (round(log10(
            max(cums$rowid)
        )) - 1))) +
        annotate(
            'label',
            x = dats,
            y = 1,
            label = dats,
            color = "darkred"
        ) +
        labs(title = "Cumulative percentage of n-grams",
             x = "n-grams", y = "cumulative percentage")
    
    elements <- list("dats" = dats, "plot" = plot)
    return(elements)
    
}


plot_rare <- function(dfm, from, to) {
    dfm %>%
        textstat_frequency() %>%
        filter(between(frequency, from, to)) %>%
        ggplot(aes(x = frequency)) +
        geom_bar(aes(y = (..count..) / sum(..count..))) +
        scale_y_continuous(labels = scales::percent) +
        scale_x_reverse(breaks = seq(to:from)) +
        coord_flip() +
        labs(y = "percent")+
        theme_clean() 
}