Prepare the Environment

Time to start loading packages! In this case, I’ll use the same ones that we used in the walkthrough from last week, along with the pacman package to streamline install. I left the comments from the walkthrough on the packages that are new to me, in case I need to reference them later.

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,
  ggplot2,
  caTools,
  caret,
  class, #includes the knn algorithm
  gmodels #for knn model evaluation
)

I’ll also read in the MOOC Certificate dataset using the read.csv function and label it ‘MOOCCert’. I’ll also select the features that we need to answer the assisgnment’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

Now, we’ve got 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

Let’s set a 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).

set.seed(252)

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

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

Implementing K-NN

Now to use the knn function to fit the kNN classifier to the training set.

y_pred <- knn(train = train_MOOCData[-3], #training set w/o target variable
              test = test_MOOCData[-3], #test set w/o target variable
              cl = train_MOOCData$Purchased, #training set w/ only target variable
              k = 20, #sqrt of 400 cases is 20
              TRUE)
  
view(y_pred)

Model Evaluation

A confusion matrix can help us to evaluate the K-NN classifier’s performance on the test set.

CrossTable(x = test_MOOCData$Purchased, #the actual Purchased values from test dataset
           y = y_pred, #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_pred 
## test_MOOCData$Purchased | Not Purchased |     Purchased |     Row Total | 
## ------------------------|---------------|---------------|---------------|
##           Not Purchased |            53 |            11 |            64 | 
##                         |         0.828 |         0.172 |         0.646 | 
##                         |         0.914 |         0.268 |               | 
##                         |         0.535 |         0.111 |               | 
## ------------------------|---------------|---------------|---------------|
##               Purchased |             5 |            30 |            35 | 
##                         |         0.143 |         0.857 |         0.354 | 
##                         |         0.086 |         0.732 |               | 
##                         |         0.051 |         0.303 |               | 
## ------------------------|---------------|---------------|---------------|
##            Column Total |            58 |            41 |            99 | 
##                         |         0.586 |         0.414 |               | 
## ------------------------|---------------|---------------|---------------|
## 
## 
  1. What do the following categories mean in this context and interpreted in light of the output in the confusion matrix?

True negative: This tells us how many times our model correctly predicted ‘Not Purchased’ for an individual. In this case, it correctly identified 53/99 as ‘Not Purchased.’

True positive: This tells us how many times our model correctly predicted ‘Purchased’ for an individual. In this case, it correctly identified 30/99 as ‘Purchased.’

False negative: This tells us how many times our model incorrectly predicted ‘Not Purchased’ when in fact the individual had purchased a certificate. In this case, it incorrectly identified 5/99 as having ‘not purchased’ when in fact they had purchased.

False positive: This tells us how many times our model incorrectly predicted ‘Purchased’ when in fact the individual had not purchased a certificate. In this case, it incorrectly identified 11/99 as ‘purchased’ when in fact they had not purchased.

We can add the true negatives + positives, then divide by the overall number of observations, to get an accuracy rate of around 84%. Not terrible, but we’d probably want to revisit and revise a little bit.