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:
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)
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")
| 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 |
| 159.4 | 2,360,148 | 30,096,690 | 162,096,241 | 12.8 | 12 | 47 |
What this shows:
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.
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))
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.
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")
| 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).
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.
I would welcome feedback on: