Prepare the Environment

Package loading time! I’ll use some of the ones from the walkthrough, along with the pacman package and the caret package.

install.packages("pacman")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.3'
## (as 'lib' is unspecified)
library("pacman")

pacman::p_load(
  tidyverse,
  readr, 
  magrittr,
  dplyr,
  psych, 
  caret,
  naivebayes,
  gmodels 
)

Let’s read in the MOOC Certificate dataset with the read.csv function and call it ‘MOOCCert’. We also need to select the features needed to answer the assignment’s research question (age, estimated salary, purchase record.)

MOOCCert <- read.csv("/cloud/project/Data/MOOC-certificate.csv")


MOOCCertSelect <- select(MOOCCert, Age, EstimatedSalary, Purchased) #I like using the 'select' function from dplyr to organize my data frames. 

Encoding the Target Feature

We’ll use the same process that we did during the KNN assignment to encode the target feature ‘Purchased’ as a factor, and perform feature scaling on the the other features in our dataset.

MOOCCertSelect$Purchased <- factor(MOOCCertSelect$Purchased, levels = c("0", "1"),
                                   labels = c("Not Purchased", "Purchased"))

class(MOOCCertSelect$Purchased) #check to make sure Purchased is a factor now
## [1] "factor"
MOOCCertSelect_z <- as.data.frame(scale(MOOCCertSelect[1:2])) #scale Age and EstimateSalary

MOOCCertSelect_z$Purchased <- MOOCCertSelect$Purchased #add the unaltered target factor back into the final dataset

Data Splitting

We’ll use ‘123’ as the seed to make the code reproducible, and split the dataset into training/testing sets. We’ll also want to check that the training/testing datasets are balanced similarly to the overall dataset when it comes to our target feature (Purchased). Unlike the KNN assignment, this time I’ll remember to include the code for testing both subsets!

set.seed(123)

trainIndex <- createDataPartition(MOOCCertSelect_z$Purchased, p = .75, list = FALSE)

train_MOOCData <- MOOCCertSelect_z[trainIndex,]
test_MOOCData <- MOOCCertSelect_z[-trainIndex,]

table(MOOCCertSelect_z$Purchased)
## 
## Not Purchased     Purchased 
##           257           143
round(prop.table(table(train_MOOCData$Purchased)) * 100, digits = 1)
## 
## Not Purchased     Purchased 
##          64.1          35.9
round(prop.table(table(test_MOOCData$Purchased)) * 100, digits = 1)
## 
## Not Purchased     Purchased 
##          64.6          35.4

Looks pretty balanced - 257 ‘not purchased’ out of 400 total is around 64% in the original dataset, which mirrors both our training and test datasets.

Implementing Naive Bayes

Now to fit the Naive Bayes classifier to the training set and save the output as y_classifier.

y_classifier <- naive_bayes(train_MOOCData, train_MOOCData$Purchased)
## Warning: naive_bayes(): Feature Purchased - zero probabilities are present.
## Consider Laplace smoothing.
  1. What does the warning “zero probabilities are present” mean? and why should we consider using a Laplace number?

According to Lantz, the “zero probabilities” problem exists when “an event never occurs for one or more levels of the class and therefore their joint probability is zero.” (p.101) For example, this might mean that certain values for Age or Estimated Salary have never appeared in the ‘Purchased’ state, which rendered the entire posterior probability zero and created a scenario where ‘Purchased’ would have a zero probability.

Lantz mentions the Laplace number as a potential solution to this problem. The Laplace number increases each count in the frequency table by a small amount, ensuring that “each feature has a non-zero probability of occurring with each class.” (p.101) The standard procedure is to set the Laplace estimator to a value of one, which gives each class-feature combination at least one occurence.

Moving on - let’s predict whether MOOC students purchased the certificate on the testing data using the code below. We’ll save it as y_predicted and evaluate it in the next section.

y_predicted <- predict(y_classifier, #our newly created classifer
                       test_MOOCData) #our testing data

Model Evaluation

A confusion matrix can help us to evaluate the Naive Bayes classifier’s performance on the test set.

CrossTable(x = test_MOOCData$Purchased, #the actual Purchased values from test dataset
           y = y_predicted, #the predicted Purchased values
           prop.chisq = FALSE)
## 
##  
##    Cell Contents
## |-------------------------|
## |                       N |
## |           N / Row Total |
## |           N / Col Total |
## |         N / Table Total |
## |-------------------------|
## 
##  
## Total Observations in Table:  99 
## 
##  
##                         | y_predicted 
## test_MOOCData$Purchased | Not Purchased |     Purchased |     Row Total | 
## ------------------------|---------------|---------------|---------------|
##           Not Purchased |            64 |             0 |            64 | 
##                         |         1.000 |         0.000 |         0.646 | 
##                         |         1.000 |         0.000 |               | 
##                         |         0.646 |         0.000 |               | 
## ------------------------|---------------|---------------|---------------|
##               Purchased |             0 |            35 |            35 | 
##                         |         0.000 |         1.000 |         0.354 | 
##                         |         0.000 |         1.000 |               | 
##                         |         0.000 |         0.354 |               | 
## ------------------------|---------------|---------------|---------------|
##            Column Total |            64 |            35 |            99 | 
##                         |         0.646 |         0.354 |               | 
## ------------------------|---------------|---------------|---------------|
## 
## 

Interesting. It looks to me that this model is 100% accurate (64% true negative, 35% true positive, which makes me a little suspicious as I would have expected some amount of error given that we’re going to be implementing the Laplace number in the next section. However, I’ve reviewed the code, the walkthrough, the assignment instructions, and the Lantz chapter multiple times without seeing any obvious errors.

Model Improvement and Evaluation

Let’s create a second classifer that uses a Laplace estimator, then run the model again with the new classifer. Similar to our previous model, this model is 100% accurate, which I’m now very suspicious that I’ve done something wrong as I would expect some type of change to demonstrate the effect of the Laplace estimator. However, I can only make conclusions using what’s available to me - based on this output, I have observed no change when using the Laplace number. The function of the Laplace number in y_classifier2 is to ensure that each class-feature combination has a count of at least 1.

y_classifier2 <- naive_bayes(train_MOOCData, train_MOOCData$Purchased, laplace = 1)

y_predicted2 <- predict(y_classifier2, #the second classifer
                       test_MOOCData) #our testing data

CrossTable(x = test_MOOCData$Purchased, #the actual Purchased values from test dataset
           y = y_predicted2, #the predicted Purchased values
           prop.chisq = FALSE)
## 
##  
##    Cell Contents
## |-------------------------|
## |                       N |
## |           N / Row Total |
## |           N / Col Total |
## |         N / Table Total |
## |-------------------------|
## 
##  
## Total Observations in Table:  99 
## 
##  
##                         | y_predicted2 
## test_MOOCData$Purchased | Not Purchased |     Purchased |     Row Total | 
## ------------------------|---------------|---------------|---------------|
##           Not Purchased |            64 |             0 |            64 | 
##                         |         1.000 |         0.000 |         0.646 | 
##                         |         1.000 |         0.000 |               | 
##                         |         0.646 |         0.000 |               | 
## ------------------------|---------------|---------------|---------------|
##               Purchased |             0 |            35 |            35 | 
##                         |         0.000 |         1.000 |         0.354 | 
##                         |         0.000 |         1.000 |               | 
##                         |         0.000 |         0.354 |               | 
## ------------------------|---------------|---------------|---------------|
##            Column Total |            64 |            35 |            99 | 
##                         |         0.646 |         0.354 |               | 
## ------------------------|---------------|---------------|---------------|
## 
##