Load Required libraries and data from ISLR

library(tidymodels)
## ── Attaching packages ────────────────────────────────────── tidymodels 1.1.1 ──
## ✔ broom        1.0.5     ✔ recipes      1.0.8
## ✔ dials        1.2.0     ✔ rsample      1.2.0
## ✔ dplyr        1.1.3     ✔ tibble       3.2.1
## ✔ ggplot2      3.4.4     ✔ tidyr        1.3.0
## ✔ infer        1.0.5     ✔ tune         1.1.2
## ✔ modeldata    1.2.0     ✔ workflows    1.1.3
## ✔ parsnip      1.1.1     ✔ workflowsets 1.0.1
## ✔ purrr        1.0.2     ✔ yardstick    1.2.0
## ── Conflicts ───────────────────────────────────────── tidymodels_conflicts() ──
## ✖ purrr::discard() masks scales::discard()
## ✖ dplyr::filter()  masks stats::filter()
## ✖ dplyr::lag()     masks stats::lag()
## ✖ recipes::step()  masks stats::step()
## • Use tidymodels_prefer() to resolve common conflicts.
library(ISLR)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats   1.0.0     ✔ readr     2.1.4
## ✔ lubridate 1.9.3     ✔ stringr   1.5.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ readr::col_factor() masks scales::col_factor()
## ✖ purrr::discard()    masks scales::discard()
## ✖ dplyr::filter()     masks stats::filter()
## ✖ stringr::fixed()    masks recipes::fixed()
## ✖ dplyr::lag()        masks stats::lag()
## ✖ readr::spec()       masks yardstick::spec()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
data("Carseats")

Question One

Create a random forest specification

and Set the importance to “TRUE”

Carseats$Sales <- as.factor(Carseats$Sales)
sum(is.na(Carseats))
## [1] 0
rf_spec <- rand_forest(mtry=4)%>%
set_engine("randomForest",importance=TRUE)%>%
set_mode("classification")

Set up the workflow for the Hyperparameter tuning

rf_wf <- workflow() %>%
 add_model(rf_spec) %>%
 add_formula(Sales ~ .)

Set up the resampling to generate resamples that accuractely represent data

resampling <- vfold_cv(Carseats, v = 5)

Tuning

set.seed(123)
tunegrid <- expand_grid(.mtry=seq(1,ncol(Carseats)))

Set the engine for the random forest model

rf_spec <- set_engine(rf_spec, engine = "randomForest")

Question Two

Fitting the model

str(Carseats)
## 'data.frame':    400 obs. of  11 variables:
##  $ Sales      : Factor w/ 336 levels "0","0.16","0.37",..: 256 298 268 159 38 291 134 307 130 56 ...
##  $ CompPrice  : num  138 111 113 117 141 124 115 136 132 132 ...
##  $ Income     : num  73 48 35 100 64 113 105 81 110 113 ...
##  $ Advertising: num  11 16 10 4 3 13 0 15 0 0 ...
##  $ Population : num  276 260 269 466 340 501 45 425 108 131 ...
##  $ Price      : num  120 83 80 97 128 72 108 120 124 124 ...
##  $ ShelveLoc  : Factor w/ 3 levels "Bad","Good","Medium": 1 2 3 3 1 1 3 2 3 3 ...
##  $ Age        : num  42 65 59 55 38 78 71 67 76 76 ...
##  $ Education  : num  17 10 12 14 13 16 15 10 10 17 ...
##  $ Urban      : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 1 2 2 1 1 ...
##  $ US         : Factor w/ 2 levels "No","Yes": 2 2 2 2 1 2 1 2 1 2 ...
rf_fit <-   fit(rf_spec, Sales ~ ., data = Carseats)

Question Three

Preparing data for confusion matrix

predictions <- predict(rf_fit, new_data = Carseats)
predicted_values <-factor(predictions$.pred_class, levels=levels(Carseats$Sales))
reference_values <- factor(Carseats$Sales, levels =
levels(Carseats$Sales))

Creating a confusion matrix

library("caret")
## Loading required package: lattice
## 
## Attaching package: 'caret'
## The following objects are masked from 'package:yardstick':
## 
##     precision, recall, sensitivity, specificity
## The following object is masked from 'package:purrr':
## 
##     lift
conf_matrix <- confusionMatrix(data = predicted_values, reference =
reference_values)

Showing the matrix

print(conf_matrix$overall)
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##      1.0000000      1.0000000      0.9908202      1.0000000      0.0100000 
## AccuracyPValue  McnemarPValue 
##      0.0000000            NaN

Calculating the accuracy rate

accuracy_rate <- conf_matrix$overall["Accuracy"]

cat("Accuracy Rate:",accuracy_rate, "\n")
## Accuracy Rate: 1

Question Four

Creating a variable importance plot using vip_plot with the fitted data

library(vip)
## 
## Attaching package: 'vip'
## The following object is masked from 'package:utils':
## 
##     vi
vip_plot <- vip(rf_fit) 

print(vip_plot)

Intepretation of Variable Importance Plot

When interpreting this plot, we are looking at the impact of various variables on sales as stated through the variable importance graph. It overall explores the relationship between said variables and our Sales with most significant variables listed in descending order. We can see that the top three variables are population, income, price, and competitors price with advertising, education, shelving location, urban and US being at the bottom. Clearly, the higher the population is, the more sales they recieve based on more foot traffic and the general need for seats. Following, we can see the purchasing of car seats is heavily reliant on economic factors like income, price, and competitor pricing. This means that Car seat sellers could benefit from competitive pricing, “economy” versions, and providing sales and discounts. This suggestions relate back to the importance of costs and income on the Sales and its direct relationship. They can also spend less money on shelving locations and displays as well as potentially move some advertising costs into creating discounts. Additionally, putting as much effort into urban as non-urban would be valuable as we can see urban does have limited impact.