This is an R Markdown Notebook. When you execute code within the notebook, the results appear beneath the code.
Try executing this chunk by clicking the Run button within the chunk or by placing your cursor inside it and pressing Ctrl+Shift+Enter.
dd a new chunk by clicking the Insert Chunk button on the toolbar or by pressing Ctrl+Alt+I.
##Load and Summarize
# RStudio Options
options(scipen = 1000) #Prevent display in scientific notation
# Run this reusable confusion matrix function (https://en.wikipedia.org/wiki/Confusion_matrix)
my_confusion_matrix <- function(cf_table) {
true_positive <- cf_table[4]
true_negative <- cf_table[1]
false_positive <- cf_table[2]
false_negative <- cf_table[3]
accuracy <- (true_positive + true_negative) / (true_positive + true_negative + false_positive + false_negative)
sensitivity_recall <- true_positive / (true_positive + false_negative)
specificity_selectivity <- true_negative / (true_negative + false_positive)
precision <- true_positive / (true_positive + false_positive)
neg_pred_value <- true_negative/(true_negative + false_negative)
print(cf_table)
my_list <- list(sprintf("%1.0f = True Positive (TP), Hit", true_positive),
sprintf("%1.0f = True Negative (TN), Rejection", true_negative),
sprintf("%1.0f = False Positive (FP), Type 1 Error", false_positive),
sprintf("%1.0f = False Negative (FN), Type 2 Error", false_negative),
sprintf("%1.4f = Accuracy (TP+TN/(TP+TN+FP+FN))", accuracy),
sprintf("%1.4f = Sensitivity, Recall, Hit Rate, True Positive Rate (How many positives did the model get right? TP/(TP+FN))", sensitivity_recall),
sprintf("%1.4f = Specificity, Selectivity, True Negative Rate (How many negatives did the model get right? TN/(TN+FP))", specificity_selectivity),
sprintf("%1.4f = Precision, Positive Predictive Value (How good are the model's positive predictions? TP/(TP+FP))", precision),
sprintf("%1.4f = Negative Predictive Value (How good are the model's negative predictions? TN/(TN+FN)", neg_pred_value)
)
return(my_list)
}
#install packages
# Load any libraries here
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(ggplot2)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ lubridate 1.9.3 ✔ tibble 3.2.1
## ✔ purrr 1.0.2 ✔ tidyr 1.3.0
## ✔ readr 2.1.4
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(magrittr)
##
## Attaching package: 'magrittr'
##
## The following object is masked from 'package:purrr':
##
## set_names
##
## The following object is masked from 'package:tidyr':
##
## extract
library(lubridate)
library(corrplot)
## corrplot 0.92 loaded
#Introduction:
df=readRDS("mod6HE_logit.rds")
# Not for the model (for use later)
ColumnsNotUsed <- df %>%
select(store, region, week, high_med_rev, high_med_gp, high_med_gpm)
knn1 <- df %>%
mutate(high_med_units = factor(if_else(high_med_units==1, 'high', 'low'), levels=c('low', 'high')))
knn1 <- knn1 %>%
select(high_med_units, size, region,
promo_units_per,
altbev_units_per, confect_units_per, salty_units_per,
velocityA_units_per, velocityB_units_per, velocityC_units_per, velocityD_units_per, velocityNEW_units_per)
library(fastDummies)
## Warning: package 'fastDummies' was built under R version 4.3.2
## Thank you for using fastDummies!
## To acknowledge our work, please cite the package:
## Kaplan, J. & Schlegel, B. (2023). fastDummies: Fast Creation of Dummy (Binary) Columns and Rows from Categorical Variables. Version 1.7.1. URL: https://github.com/jacobkap/fastDummies, https://jacobkap.github.io/fastDummies/.
knn1 <- fastDummies::dummy_cols(knn1, select_columns = c("region"), remove_selected_columns=T)
contrasts(knn1$high_med_units)
## high
## low 0
## high 1
library(caret)
## Warning: package 'caret' was built under R version 4.3.2
## Loading required package: lattice
##
## Attaching package: 'caret'
## The following object is masked from 'package:purrr':
##
## lift
set.seed(42)
partition <- caret::createDataPartition(y=knn1$high_med_units, p=.75, list=FALSE)
data_train <- knn1[partition, ]
data_test <- knn1[-partition, ]
# Separate the target variables from the training and testing data.
# "X" indicates the independent variables and "y" indicates the target variables
X_train <- data_train %>%
select(-high_med_units)
X_test <- data_test %>%
select(-high_med_units)
y_train <- data_train$high_med_units
y_test <- data_test$high_med_units
X_train <- scale(X_train)
X_test <- scale(X_test)
#install.packages('class') #don't install twice
library(class)
knn_prediction = class::knn(train=X_train, test=X_test, cl=y_train, k=round(sqrt(nrow(data_train))/2))
table2 <- table(knn_prediction, y_test) #prediction on left and truth on top
confusionMatrix(table2)
## Confusion Matrix and Statistics
##
## y_test
## knn_prediction low high
## low 966 222
## high 294 1035
##
## Accuracy : 0.795
## 95% CI : (0.7787, 0.8106)
## No Information Rate : 0.5006
## P-Value [Acc > NIR] : < 0.00000000000000022
##
## Kappa : 0.59
##
## Mcnemar's Test P-Value : 0.001774
##
## Sensitivity : 0.7667
## Specificity : 0.8234
## Pos Pred Value : 0.8131
## Neg Pred Value : 0.7788
## Prevalence : 0.5006
## Detection Rate : 0.3838
## Detection Prevalence : 0.4720
## Balanced Accuracy : 0.7950
##
## 'Positive' Class : low
##
# Put the prediction back into the test data
library(tidyverse)
data_test$knn <- knn_prediction
# Create a variable that shows if the prediction was correct
data_test <- data_test %>% mutate(correct_knn = if_else(data_test$knn == data_test$high_med_units, 'correct', 'WRONG!'))
# Add back the variables we took out at the beginning to the test data
temp1 <- ColumnsNotUsed[-partition, ]
full_test_knn <- bind_cols(temp1, data_test)
# For viewing in class
full_test_knn <- full_test_knn %>%
select(store, week, high_med_units, knn, correct_knn, size, region, promo_units_per, salty_units_per)
slice_sample(full_test_knn, n=10)
## # A tibble: 10 × 9
## store week high_med_units knn correct_knn size region promo_units_per
## <fct> <dbl> <fct> <fct> <chr> <int> <fct> <dbl>
## 1 92576 26 high high correct 1015 WEST 0.390
## 2 14141 52 low high WRONG! 896 QUEBEC 0.302
## 3 2519 30 low low correct 917 WEST 0.402
## 4 35284 30 low low correct 904 ONTARIO 0.445
## 5 399 6 low low correct 948 ONTARIO 0.447
## 6 35277 15 low high WRONG! 955 ONTARIO 0.299
## 7 69874 21 high high correct 943 WEST 0.316
## 8 35326 14 high high correct 1031 ONTARIO 0.364
## 9 35277 44 low high WRONG! 955 ONTARIO 0.132
## 10 36780 52 low high WRONG! 964 WEST 0.347
## # ℹ 1 more variable: salty_units_per <dbl>
# Data that is not for the model, but for later
ColumnsNotUsedTREE <- df %>%
select(store, region, week, high_med_rev, high_med_gp, high_med_gpm)
# Make the target feature and `region` a factor
tree1 <- df %>%
mutate(high_med_units = factor(if_else(high_med_units==1, 'high', 'low'), levels=c('low', 'high')),
region = factor(region))
tree1 <- tree1 %>%
select(high_med_units, size, region,
promo_units_per,
altbev_units_per, confect_units_per, salty_units_per,
velocityA_units_per, velocityB_units_per, velocityC_units_per, velocityD_units_per, velocityNEW_units_per)
# Check that "positive" is last for `my_confusion_matrix()` to work
contrasts(tree1$high_med_units)
## high
## low 0
## high 1
library(caret)
set.seed(42)
partition <- caret::createDataPartition(y=tree1$high_med_units, p=.75, list=FALSE)
data_train <- tree1[partition, ]
data_test <- tree1[-partition, ]
#install.packages('rpart') #(don't install twice)
#install.packages('rpart.plot') #(don't install twice)
library(rpart)
library(rpart.plot)
## Warning: package 'rpart.plot' was built under R version 4.3.2
model_tree <- rpart::rpart(high_med_units ~ ., data_train)
`
`
```r
predict_tree <- predict(model_tree, data_test, type='class') #`type='class'` keeps this a factor
``
```r
table1 <- table(predict_tree, data_test$high_med_units)
confusionMatrix(table1)
## Confusion Matrix and Statistics
##
##
## predict_tree low high
## low 990 291
## high 270 966
##
## Accuracy : 0.7771
## 95% CI : (0.7603, 0.7932)
## No Information Rate : 0.5006
## P-Value [Acc > NIR] : <0.0000000000000002
##
## Kappa : 0.5542
##
## Mcnemar's Test P-Value : 0.3984
##
## Sensitivity : 0.7857
## Specificity : 0.7685
## Pos Pred Value : 0.7728
## Neg Pred Value : 0.7816
## Prevalence : 0.5006
## Detection Rate : 0.3933
## Detection Prevalence : 0.5089
## Balanced Accuracy : 0.7771
##
## 'Positive' Class : low
##
rpart.plot::rpart.plot(model_tree, box.palette = 'RdBu', shadow.col = 'gray', nn=TRUE, yesno=2)
# Put the prediction back into the test data
data_test$tree <- predict_tree
# Create a variable that shows if the prediction was correct
data_test <- data_test %>%
mutate(correct_tree = if_else(tree == high_med_units, 'correct', 'WRONG!'))
# Add back the variables we took out at the beginning to the test data
temp1 <- ColumnsNotUsedTREE[-partition, ]
full_test_tree <- bind_cols(temp1, data_test)
## New names:
## • `region` -> `region...2`
## • `region` -> `region...9`
str(full_test_tree)
## tibble [2,517 × 20] (S3: tbl_df/tbl/data.frame)
## $ store : Factor w/ 194 levels "186","227","233",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ region...2 : Factor w/ 4 levels "ONTARIO","WEST",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ week : num [1:2517] 2 3 6 9 10 12 20 22 27 31 ...
## $ high_med_rev : num [1:2517] 1 1 1 1 1 1 1 1 1 1 ...
## $ high_med_gp : num [1:2517] 1 1 1 1 1 1 1 1 1 1 ...
## $ high_med_gpm : num [1:2517] 0 0 0 0 0 0 1 0 0 1 ...
## $ high_med_units : Factor w/ 2 levels "low","high": 2 2 2 2 2 2 2 2 2 2 ...
## $ size : int [1:2517] 966 966 966 966 966 966 966 966 966 966 ...
## $ region...9 : Factor w/ 4 levels "ONTARIO","WEST",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ promo_units_per : num [1:2517] 0.297 0.295 0.313 0.281 0.287 ...
## $ altbev_units_per : num [1:2517] 0.271 0.276 0.282 0.29 0.305 ...
## $ confect_units_per : num [1:2517] 0.345 0.366 0.351 0.334 0.317 ...
## $ salty_units_per : num [1:2517] 0.226 0.207 0.225 0.211 0.204 ...
## $ velocityA_units_per : num [1:2517] 0.619 0.615 0.623 0.572 0.563 ...
## $ velocityB_units_per : num [1:2517] 0.202 0.198 0.206 0.219 0.223 ...
## $ velocityC_units_per : num [1:2517] 0.0755 0.0768 0.0642 0.0817 0.0858 ...
## $ velocityD_units_per : num [1:2517] 0.0768 0.0838 0.0785 0.1027 0.0936 ...
## $ velocityNEW_units_per: num [1:2517] 0 0 0 0 0 ...
## $ tree : Factor w/ 2 levels "low","high": 2 2 2 2 2 2 2 2 2 2 ...
## ..- attr(*, "names")= chr [1:2517] "1" "2" "3" "4" ...
## $ correct_tree : chr [1:2517] "correct" "correct" "correct" "correct" ...
# For viewing in class
full_test_tree <- full_test_tree %>%
select(store, week, high_med_units, tree, correct_tree, size, region...2, promo_units_per, salty_units_per)
slice_sample(full_test_tree, n=10)
## # A tibble: 10 × 9
## store week high_med_units tree correct_tree size region...2
## <fct> <dbl> <fct> <fct> <chr> <int> <fct>
## 1 74485 23 low high WRONG! 910 WEST
## 2 2591 43 high high correct 1038 WEST
## 3 38893 14 high high correct 890 WEST
## 4 67800 1 low low correct 907 ONTARIO
## 5 14229 41 low low correct 906 QUEBEC
## 6 68295 12 low low correct 899 WEST
## 7 92576 26 high high correct 1015 WEST
## 8 84325 27 high high correct 900 WEST
## 9 1446 18 low low correct 944 ONTARIO
## 10 813 30 low low correct 906 ONTARIO
## # ℹ 2 more variables: promo_units_per <dbl>, salty_units_per <dbl>
full_test <- bind_cols(full_test_knn %>%
select(store, week, high_med_units, knn, correct_knn),
full_test_tree %>%
select(-store, -week, -high_med_units))
## New names:
## • `region...2` -> `region`
slice_sample(full_test, n=10)
## # A tibble: 10 × 11
## store week high_med_units knn correct_knn tree correct_tree size region
## <fct> <dbl> <fct> <fct> <chr> <fct> <chr> <int> <fct>
## 1 85964 32 high high correct high correct 946 WEST
## 2 14212 36 high high correct high correct 1015 ONTARIO
## 3 59212 50 high low WRONG! high correct 985 ONTARIO
## 4 36718 30 high high correct high correct 1119 WEST
## 5 35284 7 low low correct low correct 904 ONTARIO
## 6 68295 9 low low correct low correct 899 WEST
## 7 53002 42 low low correct low correct 922 ONTARIO
## 8 13808 45 low low correct low correct 895 QUEBEC
## 9 14229 41 low low correct low correct 906 QUEBEC
## 10 77809 31 high high correct high correct 982 WEST
## # ℹ 2 more variables: promo_units_per <dbl>, salty_units_per <dbl>