Introduction

In this report, we explore text data from blogs, news, and Twitter to build a predictive text model. We aim to simplify technical concepts and provide clear insights into our findings for a broad audience, including those without a data science background.

Installing packages

We begin by installing and loading several R packages which are essential tools for text processing and visualization.

library(NLP)
library(tm)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(stringr)
library(ggplot2)
## 
## Attaching package: 'ggplot2'
## The following object is masked from 'package:NLP':
## 
##     annotate
library(knitr)

Reading Data

We read the data from three distinct sources: blogs, news, and Twitter. Each of these datasets offers a unique perspective on language usage.

read_file <- function(file_path) {
    lines <- readLines(file_path, warn = FALSE)
    return(lines)
}

Defining file path

file_path_blogs <- "C:/Users/BSB/Desktop/Data_Science_Coursera/data/data/Statistical Inference/CAPSTONE/Coursera-SwiftKey/final/en_US/en_US.blogs.txt"
file_path_news <- "C:/Users/BSB/Desktop/Data_Science_Coursera/data/data/Statistical Inference/CAPSTONE/Coursera-SwiftKey/final/en_US/en_US.news.txt"
file_path_twitter <- "C:/Users/BSB/Desktop/Data_Science_Coursera/data/data/Statistical Inference/CAPSTONE/Coursera-SwiftKey/final/en_US/en_US.twitter.txt"

Data Line Counts

blogs <- read_file("C:/Users/BSB/Desktop/Data_Science_Coursera/data/data/Statistical Inference/CAPSTONE/Coursera-SwiftKey/final/en_US/en_US.blogs.txt")
blogs_line_count <- length(blogs)
news <- read_file("C:/Users/BSB/Desktop/Data_Science_Coursera/data/data/Statistical Inference/CAPSTONE/Coursera-SwiftKey/final/en_US/en_US.news.txt")
news_line_count <- length(news)
twitter <- read_file("C:/Users/BSB/Desktop/Data_Science_Coursera/data/data/Statistical Inference/CAPSTONE/Coursera-SwiftKey/final/en_US/en_US.twitter.txt")
twitter_line_count <- length(twitter)

# Add row numbers to the report
cat("Blogs dataset contains", blogs_line_count, "lines\n")
## Blogs dataset contains 899288 lines
cat("News dataset contains", news_line_count, "lines\n")
## News dataset contains 77259 lines
cat("Twitter dataset contains", twitter_line_count, "lines\n")
## Twitter dataset contains 2360148 lines

Data preprocessing function and tokenization

What is Data Preprocessing?

Data preprocessing is the process of cleaning and organizing raw data to make it suitable for a machine learning model. In this phase, we convert text to lowercase, remove punctuation, digits, and irrelevant words to simplify the data.

clean_text <- function(text) {
    text <- tolower(text)  # Convert text to lowercase
    text <- gsub("\\b\\w{1,2}\\b", "", text)  # Remove 1 or 2 letter words
    text <- gsub("[[:punct:]]", "", text)  # Remove punctuation
    text <- gsub("[[:digit:]]", "", text)  # Subtract digits
    text <- gsub("\\W", " ", text)  # Replace non-letter characters with spaces
    text <- gsub("\\s+", " ", text)  # Replace extra spaces with single space
    text <- trimws(text)
    return(text)
}

Tokenization Explained

Tokenization is the process of splitting text into individual elements, commonly words. This step is crucial for understanding and analyzing the text data effectively.

tokenize_text <- function(text) {
    tokens <- unlist(str_split(text, "\\s+"))
    return(tokens)
}

profanity_words <- c("badword1", "badword2")  # Sample

remove_profanity <- function(tokens, profanity_list) {
    filtered_tokens <- tokens[!tokens %in% profanity_list]
    return(filtered_tokens)
}

clean_and_process_text <- function(texts) {
    cleaned_texts <- sapply(texts, clean_text)
    tokenized_texts <- lapply(cleaned_texts, tokenize_text)
    filtered_texts <- lapply(tokenized_texts, function(tokens) remove_profanity(tokens, profanity_words))
    return(filtered_texts)
}

Processing datasets

sample_size <- 20000
cleaned_blogs <- clean_and_process_text(blogs[1:sample_size])
cleaned_news <- clean_and_process_text(news[1:sample_size])
cleaned_twitter <- clean_and_process_text(twitter[1:sample_size])

n-Gram Generation

Understanding n-Grams

An n-gram is a contiguous sequence of n items from a given sample of text. We use n-grams to predict the next word in a sequence, helping us understand the context better.

create_bigrams <- function(tokens) {
    bigrams <- lapply(1:(length(tokens) - 1), function(i) paste(tokens[i], tokens[i + 1], sep = " "))
    return(unlist(bigrams))
}

Generating and combining n-grams

bigrams_blogs <- unlist(lapply(cleaned_blogs, create_bigrams))
bigrams_news <- unlist(lapply(cleaned_news, create_bigrams))
bigrams_twitter <- unlist(lapply(cleaned_twitter, create_bigrams))

Calculating bigram frequencies

bigram_freq <- table(c(bigrams_blogs, bigrams_news, bigrams_twitter))

Prediction function for the next three words

We build a predictive model that suggests the next 3 word in a sentence. The model analyzes the frequency of word pairings (bigrams) in our datasets to make predictions.

predict_next_word <- function(input, bigram_freq, n = 3) {
    input <- clean_text(input)
    predicted_sequence <- input

    for (i in 1:n) {
        last_word <- tail(str_split(predicted_sequence, " ")[[1]], 1)
        pattern <- paste(last_word, collapse = " ")
        candidates <- grep(paste("^", pattern, sep=""), names(bigram_freq), value = TRUE)

        if (length(candidates) == 0) {
            break  # No more predictions possible
        }

        sorted_candidates <- sort(bigram_freq[candidates], decreasing = TRUE)
        next_word_pairs <- names(sorted_candidates)
        next_word <- sapply(str_split(next_word_pairs, " "), function(x) x[2])

        if (length(next_word) > 0) {
            predicted_sequence <- paste(predicted_sequence, next_word[1], sep = " ")
        } else {
            break  # No suitable next word found
        }
    }

    return(predicted_sequence)
}

Sample prediction

A demonstration of how our model predicts the next words given a sentence fragment.

# Predict the next three words after "this is"
predicted_text <- predict_next_word("this is", bigram_freq, 3)
cat("Original text: 'this is'\nPredicted continuation: ", predicted_text, "\n")
## Original text: 'this is'
## Predicted continuation:  this year ago and

In our example:

After “this,” the model predicted “year” as the next word. Then, it used “year” to predict “ago.” Finally, “ago” was used to predict “and.” Each of these predictions is based on common pairings in the dataset. While the overall phrase “this year ago and” may not form a complete or coherent sentence, it’s important to remember that each step in the prediction is based solely on the most recent word, without a broader understanding of language or context.

Performance and Memory Optimization

We assess the size and efficiency of our model, ensuring it is both fast and doesn’t consume excessive memory.

print(object.size(bigram_freq), units = "Mb")
## 53.3 Mb
gc()
##             used   (Mb) gc trigger   (Mb)  max used   (Mb)
## Ncells   6292824  336.1    9599785  512.7   9599785  512.7
## Vcells 133832953 1021.1  232299480 1772.4 161196856 1229.9

Visualization of Key Features of Data Sets

We use visualizations to highlight significant patterns in our datasets. For instance, we create histograms to show the distribution of word lengths and most frequently used words in each data set.

stop_words <- stopwords("en")

# For Blogs
word_freq_blogs <- unlist(cleaned_blogs) %>% table() %>% as.data.frame()
names(word_freq_blogs) <- c("word", "freq")
word_freq_blogs <- word_freq_blogs %>% 
              arrange(desc(freq)) %>% 
              filter(!word %in% stop_words)

# For News
word_freq_news <- unlist(cleaned_news) %>% table() %>% as.data.frame()
names(word_freq_news) <- c("word", "freq")
word_freq_news <- word_freq_news %>% 
              arrange(desc(freq)) %>% 
              filter(!word %in% stop_words)

# For Twitter
word_freq_twitter <- unlist(cleaned_twitter) %>% table() %>% as.data.frame()
names(word_freq_twitter) <- c("word", "freq")
word_freq_twitter <- word_freq_twitter %>% 
              arrange(desc(freq)) %>% 
              filter(!word %in% stop_words)

Creating Histograms and Bar Charts

# For Blogs
top_words_filtered_blogs <- head(word_freq_blogs, 20)
# Create histogram for Blogs

# For News
top_words_filtered_news <- head(word_freq_news, 20)
# Create histogram for News

# For Twitter
top_words_filtered_twitter <- head(word_freq_twitter, 20)
# Create histogram for Twitter

Creating histogram of word lengths

# For Blogs
word_lengths_blogs <- str_length(unlist(cleaned_blogs))
ggplot(data.frame(length = word_lengths_blogs), aes(x = length)) +
  geom_histogram(binwidth = 1, fill = "pink", color = "black") +
  theme_minimal() +
  xlab("Word Length") +
  ylab("Frequency") +
  ggtitle("Distribution of Word Lengths in Blogs")

# For News
word_lengths_news <- str_length(unlist(cleaned_news))
ggplot(data.frame(length = word_lengths_news), aes(x = length)) +
  geom_histogram(binwidth = 1, fill = "green", color = "black") +
  theme_minimal() +
  xlab("Word Length") +
  ylab("Frequency") +
  ggtitle("Distribution of Word Lengths in News")

# For Twitter
word_lengths_twitter <- str_length(unlist(cleaned_twitter))
ggplot(data.frame(length = word_lengths_twitter), aes(x = length)) +
  geom_histogram(binwidth = 1, fill = "blue", color = "black") +
  theme_minimal() +
  xlab("Word Length") +
  ylab("Frequency") +
  ggtitle("Distribution of Word Lengths in Twitter")

Top 10 Most Used Words

# For Blogs
top_10_words_blogs <- head(word_freq_blogs, 10)
ggplot(top_10_words_blogs, aes(x = reorder(word, freq), y = freq)) +
  geom_bar(stat = "identity") +
  theme_minimal() +
  coord_flip() +
  xlab("Words") +
  ylab("Frequency") +
  ggtitle("Top 10 Most Frequent Words in Blogs")

# For News
top_10_words_news <- head(word_freq_news, 10)
ggplot(top_10_words_news, aes(x = reorder(word, freq), y = freq)) +
  geom_bar(stat = "identity") +
  theme_minimal() +
  coord_flip() +
  xlab("Words") +
  ylab("Frequency") +
  ggtitle("Top 10 Most Frequent Words in News")

# For Twitter
top_10_words_twitter <- head(word_freq_twitter, 10)
ggplot(top_10_words_twitter, aes(x = reorder(word, freq), y = freq)) +
  geom_bar(stat = "identity") +
  theme_minimal() +
  coord_flip() +
  xlab("Words") +
  ylab("Frequency") +
  ggtitle("Top 10 Most Frequent Words in Twitter")

Summary Statistics

We calculate and display key statistical measures like minimum, maximum, mean, and standard deviation for the word counts in our datasets. These statistics provide a quantitative summary of the data.

# For Blogs
word_counts_blogs <- sapply(cleaned_blogs, function(text) length(unlist(str_split(text, "\\s+"))))
summary_stats_blogs <- data.frame(
  Min = min(word_counts_blogs),
  Median = median(word_counts_blogs),
  Mean = mean(word_counts_blogs),
  Max = max(word_counts_blogs),
  SD = sd(word_counts_blogs)
)
knitr::kable(summary_stats_blogs, caption = "Summary Statistics for Word Counts in Blogs")
Summary Statistics for Word Counts in Blogs
Min Median Mean Max SD
1 21 31.69625 529 34.40856
# For News
word_counts_news <- sapply(cleaned_news, function(text) length(unlist(str_split(text, "\\s+"))))
summary_stats_news <- data.frame(
  Min = min(word_counts_news),
  Median = median(word_counts_news),
  Mean = mean(word_counts_news),
  Max = max(word_counts_news),
  SD = sd(word_counts_news)
)
knitr::kable(summary_stats_news, caption = "Summary Statistics for Word Counts in News")
Summary Statistics for Word Counts in News
Min Median Mean Max SD
1 25 27.1528 439 18.29263
# For Twitter
word_counts_twitter <- sapply(cleaned_twitter, function(text) length(unlist(str_split(text, "\\s+"))))
summary_stats_twitter <- data.frame(
  Min = min(word_counts_twitter),
  Median = median(word_counts_twitter),
  Mean = mean(word_counts_twitter),
  Max = max(word_counts_twitter),
  SD = sd(word_counts_twitter)
)
knitr::kable(summary_stats_twitter, caption = "Summary Statistics for Word Counts in Twitter")
Summary Statistics for Word Counts in Twitter
Min Median Mean Max SD
1 9 9.50315 25 5.228887

Box Plot and Density Plot for Each Data Set

Box plots and density plots offer a visual summary of the data’s distribution, highlighting key aspects like the central tendency and variability.

# Box Plot and Density Plot for Blogs
ggplot(data.frame(Length = word_lengths_blogs), aes(x = Length)) +
  geom_boxplot() +
  theme_minimal() +
  xlab("Word Length") +
  ggtitle("Boxplot of Word Lengths in Blogs")

ggplot(data.frame(Length = word_lengths_blogs), aes(x = Length)) +
  geom_density(fill = "pink") +
  theme_minimal() +
  xlab("Word Length") +
  ggtitle("Density Plot of Word Lengths in Blogs")

# Box Plot and Density Plot for News
ggplot(data.frame(Length = word_lengths_news), aes(x = Length)) +
  geom_boxplot() +
  theme_minimal() +
  xlab("Word Length") +
  ggtitle("Boxplot of Word Lengths in News")

ggplot(data.frame(Length = word_lengths_news), aes(x = Length)) +
  geom_density(fill = "green") +
  theme_minimal() +
  xlab("Word Length") +
  ggtitle("Density Plot of Word Lengths in News")

# Box Plot and Density Plot for Twitter
ggplot(data.frame(Length = word_lengths_twitter), aes(x = Length)) +
  geom_boxplot() +
  theme_minimal() +
  xlab("Word Length") +
  ggtitle("Boxplot of Word Lengths in Twitter")

ggplot(data.frame(Length = word_lengths_twitter), aes(x = Length)) +
  geom_density(fill = "blue") +
  theme_minimal() +
  xlab("Word Length") +
  ggtitle("Density Plot of Word Lengths in Twitter")

Conclusion

Our analysis provides valuable insights into the patterns of language usage across different text sources. By using simple language and clear visualizations, we hope to make these findings accessible to a wide range of audiences.