1. Summary

The goal of the capstone is to build an app that predicts the next word a user is going to type, like the suggestions on a smartphone keyboard. The prediction model will learn from a large collection of English text supplied by SwiftKey, taken from three sources: blogs, news articles and Twitter.

This report shows that the data has been downloaded and loaded, gives basic statistics for each source, lists the main findings so far, and sets out the plan for the prediction algorithm and the Shiny app.

Key points:

  • Together the three files hold more than 4 million lines and over 100 million words.
  • The sources are very different. Tweets are short (about 13 words on average), while blog posts and news articles are 2-3 times longer.
  • A small number of words make up most of the text. Roughly 150 distinct words account for half of all words used, and about 7,000 cover 90%. This means a compact model can still give good predictions.

2. Loading the Data

The data comes from the Coursera-SwiftKey dataset. This report uses only the English (en_US) files.

read_file <- function(f) {
  con <- file(file.path(params$data_dir, f), open = "rb")
  on.exit(close(con))
  readLines(con, encoding = "UTF-8", skipNul = TRUE)
}
files <- c(Blogs = "en_US.blogs.txt", News = "en_US.news.txt", Twitter = "en_US.twitter.txt")
texts <- lapply(files, read_file)

3. Basic Summary of the Three Files

summ <- rbindlist(lapply(names(texts), function(src) {
  x <- texts[[src]]
  w <- stri_count_words(x)
  data.table(
    Source            = src,
    `File size (MB)`  = round(file.size(file.path(params$data_dir, files[[src]])) / 1024^2, 1),
    Lines             = length(x),
    Words             = sum(w),
    Characters        = sum(stri_length(x)),
    `Avg words/line`  = round(mean(w), 1),
    `Median words/line` = median(w),
    `Longest line (words)` = max(w)
  )
}))
kable(summ, format.args = list(big.mark = ","),
      caption = "Table 1. Size and content of each English source file")
Table 1. Size and content of each English source file
Source File size (MB) Lines Words Characters Avg words/line Median words/line Longest line (words)
Blogs 200.4 899,288 37,546,806 206,824,505 41.8 28 6,726
News 196.3 1,010,242 34,762,658 203,223,159 34.4 32 1,796
Twitter 159.4 2,360,148 30,096,690 162,096,241 12.8 12 47

What this shows:

  • Twitter has the most lines (over 2.3 million) but the fewest words per line, because tweets used to be capped at 140 characters.
  • Blogs have the longest entries and the most words in total. Some single blog posts run to thousands of words.
  • News sits in between, with mid-length sentences in a formal style.
wpl <- rbindlist(lapply(names(texts), function(src)
  data.table(Source = src, Words = stri_count_words(texts[[src]]))))

ggplot(wpl[Words <= 150], aes(Words, fill = Source)) +
  geom_histogram(binwidth = 3, colour = "white", show.legend = FALSE) +
  facet_wrap(~ Source, scales = "free_y") +
  scale_fill_manual(values = c("#2E86AB", "#A23B72", "#F18F01")) +
  labs(title = "Figure 1. How many words are in each line?",
       subtitle = "Lines with more than 150 words (under 2% of lines) are left out for readability",
       x = "Words per line", y = "Number of lines") +
  theme_minimal(base_size = 12)

Tweets cluster tightly below about 30 words. Blogs and news have a long tail of much longer entries.

4. Word Frequencies (Sample of the Data)

The full data is very large, so the word-frequency analysis uses a random 2% sample of lines from each file (about 85,394 lines). This is enough to give stable results and keeps processing fast.

Cleaning steps applied to the sample: convert to lower case, and remove numbers, punctuation (apostrophes in words like “don’t” are kept), web addresses and extra spaces.

sample_lines <- unlist(lapply(texts, function(x) sample(x, round(length(x) * params$sample_rate))))
rm(texts); invisible(gc())

clean <- function(x) {
  x <- stri_trans_tolower(x)
  x <- stri_replace_all_regex(x, "(https?://|www\\.)\\S+", " ")
  x <- stri_replace_all_regex(x, "[‘’]", "'")
  x <- stri_replace_all_regex(x, "[^a-z' ]", " ")
  x <- stri_replace_all_regex(x, "(^| )'+|'+( |$)", " ")
  stri_trim_both(stri_replace_all_regex(x, " +", " "))
}
sample_clean <- clean(sample_lines)
tokens <- stri_split_fixed(sample_clean[nchar(sample_clean) > 0], " ")

ngrams <- function(tok, n) {
  unlist(lapply(tok, function(w) {
    if (length(w) < n) return(character(0))
    do.call(paste, lapply(seq_len(n), function(i) w[i:(length(w) - n + i)]))
  }), use.names = FALSE)
}
freq <- function(v) {
  dt <- data.table(term = v)[, .N, by = term][order(-N)]
  dt[, share := N / sum(N)]
  dt
}
uni <- freq(unlist(tokens, use.names = FALSE))
bi  <- freq(ngrams(tokens, 2))
tri <- freq(ngrams(tokens, 3))

4.1 Most common single words

top_plot <- function(dt, k, title, colour) {
  d <- dt[1:k]
  ggplot(d, aes(reorder(term, N), N)) +
    geom_col(fill = colour) +
    coord_flip() +
    scale_y_continuous(labels = scales::comma) +
    labs(title = title, x = NULL, y = "Count in sample") +
    theme_minimal(base_size = 12)
}
top_plot(uni, 20, "Figure 2. Top 20 single words", "#2E86AB")

The most common words are short “function” words such as the, to, and, a and of. They are not removed: a keyboard has to predict these words too, and they are the ones people type most.

4.2 Most common word pairs and triples

Word pairs (bigrams) and triples (trigrams) are what the model will use to make predictions. If the user has typed “one of”, the trigram table tells us that “the” is the most likely next word.

top_plot(bi, 20, "Figure 3. Top 20 two-word phrases (bigrams)", "#A23B72")

top_plot(tri, 20, "Figure 4. Top 20 three-word phrases (trigrams)", "#F18F01")

kable(data.table(
  `Phrase length` = c("1 word", "2 words", "3 words"),
  `Total occurrences` = c(sum(uni$N), sum(bi$N), sum(tri$N)),
  `Distinct phrases` = c(nrow(uni), nrow(bi), nrow(tri)),
  `Seen only once` = scales::percent(c(mean(uni$N == 1), mean(bi$N == 1), mean(tri$N == 1)), 0.1)
), format.args = list(big.mark = ","),
caption = "Table 2. Phrase counts in the sample")
Table 2. Phrase counts in the sample
Phrase length Total occurrences Distinct phrases Seen only once
1 word 2,014,138 73,307 49.1%
2 words 1,928,785 761,841 77.7%
3 words 1,843,938 1,466,859 91.2%

The longer the phrase, the more of the distinct phrases appear only once. So longer phrases give more precise predictions, but there is much less evidence behind each one. The model has to balance the two (see Section 6).

5. How Many Words Do We Need?

uni[, cum := cumsum(share)]
cov50 <- uni[cum >= 0.5, which = TRUE][1]
cov90 <- uni[cum >= 0.9, which = TRUE][1]

ggplot(uni[1:min(.N, 30000)], aes(seq_along(cum), cum)) +
  geom_line(colour = "#2E86AB", linewidth = 1) +
  geom_hline(yintercept = c(0.5, 0.9), linetype = "dashed", colour = "grey50") +
  annotate("text", x = 30000, y = c(0.5, 0.9), vjust = -0.5, hjust = 1,
           label = c(paste0("50% of text: ", format(cov50, big.mark = ","), " words"),
                     paste0("90% of text: ", format(cov90, big.mark = ","), " words"))) +
  scale_y_continuous(labels = scales::percent) +
  scale_x_continuous(labels = scales::comma) +
  labs(title = "Figure 5. Share of all text covered by the most common words",
       x = "Number of distinct words (most common first)", y = "Share of all words in the text") +
  theme_minimal(base_size = 12)

In the sample, 143 distinct words cover 50% of all words used and 7,101 words cover 90%, out of 73,307 distinct words in total. Most of the long tail is rare names, typos and slang.

Why this matters: the app can keep a limited vocabulary and drop rare words and phrases. It stays small and fast enough for a web app while still covering almost everything people actually type.

6. Plan for the Prediction Algorithm

  1. Build phrase tables. Use a larger sample of the data to count 1-, 2-, 3- and 4-word phrases. Remove phrases seen only once so the model stays small, and filter out profanity so it is never suggested.
  2. Predict from the most recent words. Look up the last three words the user typed in the 4-word table and suggest the most frequent next words.
  3. Back off when there is no match. If that exact phrase has never been seen, fall back to the last two words, then the last word, then the most common words overall. This is the “Stupid Backoff” method, which is simple, fast and widely used for large text collections.
  4. Test accuracy. Hold back some text the model has not seen, and measure how often the correct next word appears among the top 1 and top 3 suggestions. Also check speed and memory use.

7. Plan for the Shiny App

  • A simple web page with a text box. As the user types, the app shows the top 3 predicted next words, and clicking one adds it to the text.
  • The phrase tables are pre-computed and loaded once when the app starts, so each prediction is near-instant.
  • The app will be published on shinyapps.io, along with a short slide deck explaining how it works.

8. Feedback Welcome

I would welcome feedback on:

  • whether showing three suggestions is the right number for users, and
  • whether a smaller and faster model or a larger and more accurate one should take priority.