Gonzalo Valdenebro

LinkedIn | GitHub

1. Introduction to data

This dataset provides a snapshot of user behavior on a social media platform associated with a tourism company. It includes essential information such as user identification, ticket purchase predictions, and key metrics related to user engagement, preferences, and demographic details. The dataset aims to unveil insights that can inform strategic decisions to enhance the customer experience and increase ticket sales for the tourism company.

2. Research Questions of the client

Research Question 1: Impact of Social Engagement

Client’s Inquiry: We were curious about the impact of social engagement, specifically regarding check-in likes. How does a customer’s involvement in giving likes during other check-ins influence their likelihood of purchasing a ticket next month?

Research Question 2: Effect of Company Engagement

Client’s Inquiry: The client is interested in understanding the influence of customers following their company’s account on their likelihood of purchasing a ticket. How does being a CompanyFollower affect the chances of buying a ticket next month?

Research Question 3: Website Interaction and Ticket Purchases

Client’s Inquiry: The client is interested in exploring the relationship between the number of visits to our website and the likelihood of customers purchasing a ticket. How do YearlyAvgPageVisits correlate with the odds of buying a ticket next month?

3. Cleaning the environment and loading packages

rm(list = ls())
library(rpart)
library(rpart.plot)
library(ggplot2)
library(pROC)
## Type 'citation("pROC")' for a citation.
## 
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
## 
##     cov, smooth, var
library(explore)
library(RColorBrewer)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.2     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ lubridate 1.9.3     ✔ tibble    3.2.1
## ✔ purrr     1.0.1     ✔ tidyr     1.3.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the ]8;;http://conflicted.r-lib.org/conflicted package]8;; to force all conflicts to become errors
library(dplyr)
library(kableExtra)
## 
## Attaching package: 'kableExtra'
## 
## The following object is masked from 'package:dplyr':
## 
##     group_rows
library(viridis)
## Loading required package: viridisLite
library(RColorBrewer)
library(bookdown)

4. Loading the data

cv = read.csv('Data/CustomerBehaviourTourism.csv', stringsAsFactors = TRUE) 

This is my data. It is cool. There are 11760 rows in my data.

5. Exploratory Data Analysis

5.1. Exploring the data structure

#str(cv)

5.2. Exploring the summary statistics

#summary(cv)

5.3. Missing Values

  • Yearly_avg_view_on_travel_page [int]: 581
  • total_likes_on_outstation_checkin_given [int]: 381
  • Yearly_avg_comment_on_travel_page [int]: 206
  • Adult_flag [int]: 1
  • Daily_Avg_mins_spend_on_traveling_page [int]: 1

6. Data Cleaning

6.2.1. Clean the following_company_page column

The following_company_page column should be either “Yes” or “No” values, but I come to find that it contains Yes, No, Yeso, , 1, 0. Which are distributed by the following order:

  • 0 : 5
  • 1 : 12
  • Yes : 3284
  • No : 8355
  • Empty: 103
  • Yeso : 1

Action Plan: Collapse the following_company_page values to “Yes” and “No”, by making the “1” equal to “Yes” and the “0” to “No”, since there is only 1 observation with the value “Yeso”, I will delete that row.

cv <- cv %>%
  mutate(CompanyFollower = ifelse(following_company_page %in% c(0, "No"), "No",
                                  ifelse(following_company_page %in% c(1, "Yes"), "Yes", NA)))
# Function to impute mode
impute_mode <- function(x) {
  mode_value <- names(sort(table(x), decreasing = TRUE))[1]
  x[x == "NA" | is.na(x)] <- mode_value
  return(x)
}

# Impute mode for the 'PreferredLocation' column
cv$CompanyFollower <- impute_mode(cv$CompanyFollower)
cv %>%
  group_by(CompanyFollower, Taken_product) %>%
  summarise(count = n()) %>%
  ggplot(aes(x = reorder(factor(CompanyFollower), count), y = count, fill = Taken_product)) +
  geom_bar(stat = "identity", position = "fill") +
  coord_flip() +
  labs(title = "Customer Following Page  & Buying a Ticket",
       x = "Customer Follow's Page",
       y = "Proportion",
       fill = "Buys a ticket next month") +
  scale_fill_brewer(palette = "Paired") +  # Use "Paired" palette
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
## `summarise()` has grouped output by 'CompanyFollower'. You can override using
## the `.groups` argument.

6.2.2. Clean the member_in_family column

The member_in_family column should have only 1, 2, 3, 4, 5 and 10, but I found that it contains the following 2, 1, 4, Three, 3, 5, 10. Which are distributed by the following order:

  • 1 : 1349
  • 2 : 2256
  • 3 : 4561
  • 4 : 3184
  • 5 : 384
  • 10 : 11
  • Three: 15

Action Plan: Collapse the member_in_family values to 1, 2, 3, 4, 5, 10 and the observations containing the “Three” values, equal to “3” and given that we only have 384 for family size of 5 and 11 for family size of 10, I am going to collapse them into a value called “5+” so that it does not affect the model prediction

cv <- cv %>%
  mutate(FamilyMembers = case_when(
    member_in_family == "Three" ~ "3",
    member_in_family %in% c("5", "10") ~ "5+",
    TRUE ~ as.character(member_in_family)
  ))

6.2.2.1. Graphing the member_in_family column

cv %>%
  group_by(FamilyMembers, Taken_product) %>%
  summarise(count = n()) %>%
  ggplot(aes(x = reorder(factor(FamilyMembers), count), y = count, fill = Taken_product)) +
  geom_bar(stat = "identity", position = "fill") +
  coord_flip() +
  labs(title = "Customer Family Member's & Buying a Ticket",
       x = "Customer Family Member's",
       y = "Proportion",
       fill = "Buys a ticket next month") +
  scale_fill_brewer(palette = "Paired") +  # Use "Paired" palette
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
## `summarise()` has grouped output by 'FamilyMembers'. You can override using the
## `.groups` argument.

6.2.3. Clean the working_flag column

The working_flag column should have only “Yes” or “No” values, but I found that it contains the following No, Yes, 0. Which are distributed by the following order:

  • Yes : 1808
  • No : 9951
  • 0 : 1

Action Plan: Collapse the working_flag value of 0 to “Yes”

cv$IsWorking <- ifelse(cv$working_flag == "0", "No", as.character(cv$working_flag))

6.2.3.1. Graphing the working_flag column

cv %>%
  group_by(IsWorking, Taken_product) %>%
  summarise(count = n()) %>%
  ggplot(aes(x = reorder(factor(IsWorking), count), y = count, fill = Taken_product)) +
  geom_bar(stat = "identity", position = "fill") +
  coord_flip() +
  labs(title = "Customer Working Status & Buying a Ticket",
       x = "Customer Working Status",
       y = "Proportion",
       fill = "Buys a ticket next month") +
  scale_fill_brewer(palette = "Paired") +  # Use "Paired" palette
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
## `summarise()` has grouped output by 'IsWorking'. You can override using the
## `.groups` argument.

6.2.4. Clean the preferred_device column

The preferred_device column should have only “iOS”, “Android”, “iOS and Android”, “Tab”, “Laptop”, “Mobile” values, but I found that it contains the following iOS and Android, iOS, ANDROID, , Android, Android OS, Other, Others, Tab, Laptop, Mobile. Which are distributed by the following order:

  • iOS and Android : 4134
  • iOS : 1095
  • ANDROID : 134
  • Android : 315
  • Android OS : 145
  • Other : 2
  • Others : 2
  • Tab : 4172
  • Laptop : 1108
  • Mobile : 600
  • Empty : 53

Action Plan: Collapse the preferred_device values to “Mobile”, “Laptop”, “Tablet” and “Other” and the impute the missing values with the mode of the column after collapsing them

# Function to collapse device categories
collapse_device_categories <- function(device) {
  device <- tolower(device)
  if (device %in% c("android", "android os","ios","ios and android", "Mobile")) {
    return("Mobile")
  } else if (device %in% c("laptop")) {
    return("Laptop")
  } else if (device == "tab") {
    return("Tablet")
  } else if (device == "") {
    return("NA")
  } else{
    return("Other")
  }
}

# Apply the function to create the new column
cv$PreferedDevice <- sapply(cv$preferred_device, collapse_device_categories)

Impute the missing values with the mode

# Function to impute mode
impute_mode <- function(x) {
  mode_value <- names(sort(table(x), decreasing = TRUE))[1]
  x[x == "NA" | is.na(x)] <- mode_value
  return(x)
}

# Impute mode for the 'PreferredLocation' column
cv$PreferedDevice <- impute_mode(cv$PreferedDevice)

6.3.4.1. Graphing the PreferedDevice column

cv %>%
  group_by(PreferedDevice, Taken_product) %>%
  summarise(count = n()) %>%
  ggplot(aes(x = reorder(factor(PreferedDevice), count), y = count, fill = Taken_product)) +
  geom_bar(stat = "identity", position = "fill") +
  coord_flip() +
  labs(title = "Customer Prefered Device & Buying a Ticket",
       x = "Customer Prefered Device",
       y = "Proportion",
       fill = "Buys a ticket next month") +
  scale_fill_brewer(palette = "Paired") +  # Use "Paired" palette
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
## `summarise()` has grouped output by 'PreferedDevice'. You can override using
## the `.groups` argument.

6.2.5. Clean the preferred_location_type column

The preferred_location_type column should have only “Beach”, “Financial”, “Historical site”, “Medical”, “Other”, “Big Cities” and “(Other)” values, but I found that it contains the following Financial, Other, Medical, , Game, Social media, Entertainment, Tour and Travel, Movie, OTT, Tour Travel, Beach, Historical site, Big Cities, Trekking, Hill Stations. Which are distributed by the following order:

  • Beach : 2424
  • Financial : 2409
  • Historical site : 1856
  • Medical : 1845
  • Big Cities : 636
  • Other : 643
  • Game : 12
  • Social media : 633
  • Entertainment : 516
  • Tour and Travel : 47
  • Tour Travel : 0
  • Movie : 5
  • OTT(Over-the-top media services) : 7
  • Trekking : 528
  • Hill Stations : 108
  • Empty : 31

Action Plan: Collapse the preferred_location_type values to “Metropolitan Focus”, “Natural Exploration”, “Cultural Exploration”, “Media and Entertainment” and the observations from the other categories to be merged into the “Other” category given that their frequency is not very significant and it might affect my model’s results, the missing values will be imputed with the mode of the column after I collapse them

collapse_categories <- function(category) {
  if (category %in% c("Financial", "Big Cities", "Medical")) {
    return("Metropolitan Focus")
  } else if (category %in% c("Beach", "Trekking", "Hill Stations")) {
    return("Natural Exploration")
  } else if (category %in% c("Tour and Travel", "Historical site")) {
    return("Cultural Exploration")
  } else if (category %in% c("Game", "Social Media", "Entertainment", "Movie", "OTT")) {
    return("Media and Entertainment")
  } else if (category == "") {
    return("NA")
  } else {
    return("Other")
  }
}

# Apply the function to create the new column
cv$PreferredLocation <- sapply(cv$preferred_location_type, collapse_categories)

Impute the mode in the missing values

# Function to impute mode
impute_mode <- function(x) {
  mode_value <- names(sort(table(x), decreasing = TRUE))[1]
  x[x == "NA" | is.na(x)] <- mode_value
  return(x)
}

# Impute mode for the 'PreferredLocation' column
cv$PreferredLocation <- impute_mode(cv$PreferredLocation)

6.2.5.1. Graphing the PreferredLocation column

cv %>%
  group_by(PreferredLocation, Taken_product) %>%
  summarise(count = n()) %>%
  ggplot(aes(x = reorder(factor(PreferredLocation), count), y = count, fill = Taken_product)) +
  geom_bar(stat = "identity", position = "fill") +
  coord_flip() +
  labs(title = "Customer Prefered Location & Buying a Ticket",
       x = "Customer Prefered Location",
       y = "Proportion",
       fill = "Buys a ticket next month") +
  scale_fill_brewer(palette = "Paired") +  # Use "Paired" palette
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
## `summarise()` has grouped output by 'PreferredLocation'. You can override using
## the `.groups` argument.

6.2.6. Clean the yearly_avg_Outstation_checkins column

The yearly_avg_Outstation_checkins column should have only 1, 2, 3, 7, 9 and 10 values, but I found that it contains the following 1, 24, 23, 27, 16, 15, 26, 19, 21, 11, 10, 25, 12, 18, 29, , 22, 14, 20, 28, 17, 13, , 5, 8, 2, 3, 9, 7, 6, 4*. Which are distributed by the following order:

  • 1 : 4543
  • 2 : 844
  • 3 : 336
  • 4 : 256
  • 5 : 261
  • 6 : 236
  • 7 : 336
  • 8 : 320
  • 9 : 340
  • 10 : 682
  • 11 : 229
  • 12 : 159
  • 13 : 150
  • 14 : 167
  • 15 : 206
  • 16 : 255
  • 17 : 160
  • 18 : 208
  • 20 : 199
  • 21 : 143
  • 22 : 152
  • 23 : 215
  • 24 : 223
  • 25 : 198
  • 26 : 199
  • 27 : 96
  • 28 : 180
  • 29 : 215
  • 30 : 0
  • Asterisk : 1
  • Empty : 75
# Assuming cv is your data frame
cv$yearly_avg_Outstation_checkins <- as.numeric(as.character(cv$yearly_avg_Outstation_checkins))
## Warning: NAs introduced by coercion
# Assuming cv is your data frame
cv$YearlyAvgCheckIns <- ifelse(cv$yearly_avg_Outstation_checkins <= 5, "1-5",
                               ifelse(cv$yearly_avg_Outstation_checkins <= 10, "5-10",
                                      ifelse(cv$yearly_avg_Outstation_checkins <= 15, "10-15",
                                             ifelse(cv$yearly_avg_Outstation_checkins <= 20, "15-20", "20+")
                                      )
                               ))

Impute the mode in the missing values

# Function to impute mode
impute_mode <- function(x) {
  mode_value <- names(sort(table(x), decreasing = TRUE))[1]
  x[x == "NA" | is.na(x)] <- mode_value
  return(x)
}

# Impute mode for the 'YearlyAvgCheckIns' column
cv$YearlyAvgCheckIns <- impute_mode(cv$YearlyAvgCheckIns)

6.2.5.1. Graphing the YearlyAvgCheckIns column

cv %>%
  group_by(YearlyAvgCheckIns, Taken_product) %>%
  summarise(count = n()) %>%
  ggplot(aes(x = reorder(factor(YearlyAvgCheckIns), count), y = count, fill = Taken_product)) +
  geom_bar(stat = "identity", position = "fill") +
  coord_flip() +
  labs(title = "Average Customer Check-In and Ticket Purchase Proportion",
       x = "Yearly Average Customer Check-In's",
       y = "Proportion",
       fill = "Buys a ticket next month") +
  scale_fill_brewer(palette = "Paired") +  # Use "Paired" palette
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
## `summarise()` has grouped output by 'YearlyAvgCheckIns'. You can override using
## the `.groups` argument.

6.2.7. Clean the Adult_flag column

The Adult_flag column should have only Yes or No values, but I found that it contains the following 0, 1, 3, 2, NA. Which are distributed by the following order:

  • 0 : NA
  • 1 : NA
  • 2 : NA
  • 3 : NA
  • NA : NA

Action Plan: Collapse the Adult_flag values to Yes or No, I will make all the values greater than 0 count as a Yes meaning that the customer is an Adult, and the rest a No, the missing values will be imputed with the mode of the column after I collapse them

# Assuming cv is your data frame
cv$IsAdult <- ifelse(cv$Adult_flag == 0, "No", "Yes")

Impute the null values with the mode

# Function to impute mode
impute_mode <- function(x) {
  mode_value <- names(sort(table(x), decreasing = TRUE))[1]
  x[x == "NA" | is.na(x)] <- mode_value
  return(x)
}

# Impute mode for the 'IsAdult' column
cv$IsAdult <- impute_mode(cv$IsAdult)

6.2.7.1. Graphing the IsAdult column

cv %>%
  group_by(IsAdult, Taken_product) %>%
  summarise(count = n()) %>%
  ggplot(aes(x = reorder(factor(IsAdult), count), y = count, fill = Taken_product)) +
  geom_bar(stat = "identity", position = "fill") +
  coord_flip() +
  labs(title = "Customer Group & Buying a Ticket",
       x = "Adult Customers",
       y = "Proportion",
       fill = "Buys a ticket next month") +
  scale_fill_brewer(palette = "Paired") +  # Use "Paired" palette
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))
## `summarise()` has grouped output by 'IsAdult'. You can override using the
## `.groups` argument.

6.3.5. Impute the median and mode of the column in all columns that have missing values

RandomForests cannot handle missing values so we have to do something. Preferably, we would not delete data, instead we impute

# Impute the median on NA values in the column Yearly_avg_view_on_travel_page 
cv$Yearly_avg_view_on_travel_page[is.na(cv$Yearly_avg_view_on_travel_page)] = median(cv$Yearly_avg_view_on_travel_page, na.rm = TRUE)

# Impute the median on NA values in the column total_likes_on_outstation_checkin_given
cv$total_likes_on_outstation_checkin_given[is.na(cv$total_likes_on_outstation_checkin_given)] = median(cv$total_likes_on_outstation_checkin_given, na.rm = TRUE)

# Impute the median on NA values in the column Yearly_avg_comment_on_travel_page
cv$Yearly_avg_comment_on_travel_page[is.na(cv$Yearly_avg_comment_on_travel_page)] = median(cv$Yearly_avg_comment_on_travel_page, na.rm = TRUE)

# Impute the median on NA values in the column Daily_Avg_mins_spend_on_traveling_page
cv$Daily_Avg_mins_spend_on_traveling_page[is.na(cv$Daily_Avg_mins_spend_on_traveling_page)] = median(cv$Daily_Avg_mins_spend_on_traveling_page, na.rm = TRUE)

# Impute the median on NA values in the column Daily_Avg_mins_spend_on_traveling_page
cv$yearly_avg_Outstation_checkins[is.na(cv$yearly_avg_Outstation_checkins)] = median(cv$yearly_avg_Outstation_checkins, na.rm = TRUE)

6.3.5. Remove the non-wanted columns

cv = subset(cv, select = -c(UserID, preferred_device, preferred_location_type, member_in_family, following_company_page, member_in_family, Adult_flag, working_flag))
#head(cv)

6.3.7. Rename the column header to a more readable name

# Dictionary mapping old column names to new names
column_name_mapping <- c(
  "Taken_product"                                 = "BuysProduct",                              
  "Yearly_avg_view_on_travel_page"                = "YearlyAvgPageVisits",           
  "total_likes_on_outstation_checkin_given"       = "TotalCheckInLikesGiven",   
  "yearly_avg_Outstation_checkins"                = "YearlyAvgCheckIns",       
  "Yearly_avg_comment_on_travel_page"             = "YearlyAvgComments",       
  "total_likes_on_outofstation_checkin_received"  = "TotalCheckInLikesReceived",
  "week_since_last_outstation_checkin"            = "WeeksSinceLastCheckIn",        
  "montly_avg_comment_on_company_page"            = "MonthAvgComments",         
  "travelling_network_rating"                     = "TravelNetworkRating",                   
  "Daily_Avg_mins_spend_on_traveling_page"        = "Avg_DailyMinPerView",
  "CompanyFollower"                               = "CompanyFollower",
  "FamilyMembers"                                 = "FamilyMembers",
  "IsWorking"                                     = "IsWorking" ,
  "PreferedDevice"                                = "PreferedDevice" ,
  "PreferredLocation"                             = "PreferredLocation",
  "YearlyAvgCheckIns"                             = "YearlyAvgCheckIns" , 
  "IsAdult"                                       = "IsAdult"
 )

# Rename the columns
names(cv) <- column_name_mapping
# Save the dataframe to the same CSV file
write.csv(cv, 'Data/CustomerBehaviour.csv', row.names = FALSE)
# Saving clean dataset 
summary(cv)
##  BuysProduct YearlyAvgPageVisits TotalCheckInLikesGiven YearlyAvgCheckIns
##  No :9864    Min.   : 35.0       Min.   :  3570         Min.   : 1.000   
##  Yes:1896    1st Qu.:233.0       1st Qu.: 16697         1st Qu.: 1.000   
##              Median :271.0       Median : 28076         Median : 4.000   
##              Mean   :280.3       Mean   : 28167         Mean   : 8.196   
##              3rd Qu.:322.0       3rd Qu.: 40115         3rd Qu.:14.000   
##              Max.   :464.0       Max.   :252430         Max.   :29.000   
##  YearlyAvgComments TotalCheckInLikesReceived WeeksSinceLastCheckIn
##  Min.   :  3.00    Min.   : 1009             Min.   : 0.000       
##  1st Qu.: 57.00    1st Qu.: 2941             1st Qu.: 1.000       
##  Median : 75.00    Median : 4948             Median : 3.000       
##  Mean   : 74.79    Mean   : 6532             Mean   : 3.204       
##  3rd Qu.: 92.00    3rd Qu.: 8393             3rd Qu.: 5.000       
##  Max.   :815.00    Max.   :20065             Max.   :11.000       
##  MonthAvgComments TravelNetworkRating Avg_DailyMinPerView CompanyFollower   
##  Min.   :  4.00   Min.   : 1.000      Min.   :  0.00      Length:11760      
##  1st Qu.: 17.00   1st Qu.: 2.000      1st Qu.:  8.00      Class :character  
##  Median : 22.00   Median : 3.000      Median : 12.00      Mode  :character  
##  Mean   : 28.66   Mean   : 2.713      Mean   : 13.82                        
##  3rd Qu.: 27.00   3rd Qu.: 4.000      3rd Qu.: 18.00                        
##  Max.   :500.00   Max.   :10.000      Max.   :270.00                        
##  FamilyMembers       IsWorking         PreferedDevice     PreferredLocation 
##  Length:11760       Length:11760       Length:11760       Length:11760      
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##  YearlyAvgCheckIns    IsAdult         
##  Length:11760       Length:11760      
##  Class :character   Class :character  
##  Mode  :character   Mode  :character  
##                                       
##                                       
## 

7. Predictive Modelling

For my predictive modelling, I choose the Random Forest given its simplicity to execute. Some of reasons why this model was the correct for this data and research problem was:

1. Automatic Variable Selection:

  • We get automatic variable selection, importance ranking so I am able to simply and fast collect the best variables for later tunning.

2. Ensemble Benefits:

  • Random Forest is an ensemble method, combining multiple trees to improve accuracy and generalization, making it more robust than individual models.

3. Reduction of Overfitting:

  • The algorithm’s inherent randomness helps mitigate over fitting, enhancing the model’s ability to generalize well to unseen data.

4. Handling Complexity:

  • Random Forest excels at capturing complex relationships and non-linear patterns in data, making it suitable for classification tasks with intricate decision boundaries.

7.1.Clean the environmnet

rm(list = ls())

7.2.Load packages required

library(rpart)
library(rpart.plot)
library(ggplot2)
library(pROC)
library(explore)
library(RColorBrewer)
library(tidyverse)
library(dplyr)
library(kableExtra)
library(rmarkdown)
library(randomForest)
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## Attaching package: 'randomForest'
## The following object is masked from 'package:dplyr':
## 
##     combine
## The following object is masked from 'package:ggplot2':
## 
##     margin

7.3. Read in cleaned data

# Importing clean dataset
cb_data <- read.csv('Data/CustomerBehaviour.csv', stringsAsFactors = TRUE)

7.4. Splitting data for train and test

7.4.1. Set seed for reproducibility

RNGkind(sample.kind = "default")
set.seed(2291352)

7.4.2. Split train and test data

I will be using a split of 80% for training and 20% for test data

train.idx = sample(x=1:nrow(cb_data), size = floor(0.8*nrow(cb_data)))
train.df = cb_data[train.idx,]
test.df = cb_data[-train.idx,]

7.5. Fitting a baseline model

myforest = randomForest(BuysProduct ~ .,
              data   = train.df,
              ntree  = 1000,
              mtry   = 4
              )

7.6. Tunning a random forest

Here I will tune a model by fitting and plotting the best (mtry), or in other words, the number of variables to randomly sample as candidates at each split. I am actually interested in finding the mtry that accounts for the lowest Out-of-Bag Error (OOB Error Rate), this rate is a measure of how well the model generalizes to unseen data.

Therefore, my tuning will be to loop trough all the possible mtry’s (number of variables the dataset has), record the OOB Error Rate and then pick the lowest for my further tunned model.

# A sequence of B (# of trees) that we want to try, we'll loop through each unique element in the vector below
mtry <- seq(1, 16)

# Make room for B, OOB error
keeps <- data.frame(mtry = rep(NA, length(mtry)),
                    OOB_err_rate = rep(NA, length(mtry)))

for (idx in 1:length(mtry)) {
  print(paste0("Fitting m = ", mtry[idx]))
  tempforest <- randomForest(BuysProduct ~ .,
                              data = train.df,
                              ntree = 1000,
                              mtry = mtry[idx])  # Dynamically changing mtry value
  
  # Record how many trees we tried
  keeps[idx, "mtry"] <- mtry[idx]
  
  # Record what our OOB error rate was
  keeps[idx, "OOB_err_rate"] <- mean(predict(tempforest) != train.df$BuysProduct)
}
## [1] "Fitting m = 1"
## [1] "Fitting m = 2"
## [1] "Fitting m = 3"
## [1] "Fitting m = 4"
## [1] "Fitting m = 5"
## [1] "Fitting m = 6"
## [1] "Fitting m = 7"
## [1] "Fitting m = 8"
## [1] "Fitting m = 9"
## [1] "Fitting m = 10"
## [1] "Fitting m = 11"
## [1] "Fitting m = 12"
## [1] "Fitting m = 13"
## [1] "Fitting m = 14"
## [1] "Fitting m = 15"
## [1] "Fitting m = 16"
# Find the row with the minimum OOB error rate
min_error_row <- keeps[which.min(keeps$OOB_err_rate), ]


p <- ggplot(data = keeps) +
  geom_line(aes(x = mtry, y = OOB_err_rate)) +
  geom_vline(xintercept = min_error_row$mtry, linetype = "dashed", color = "red") +
  geom_text(aes(label = min_error_row$mtry, x = min_error_row$mtry, y = min_error_row$OOB_err_rate + 0.01), color = "red") +
  theme_bw() +
  labs(x = "mtry", y = "OOB error rate")

print(p)

7.7. Tunning a random forest based on the lowest mtry

Now that I have tunned the models, it seems like the lowest OOB Error Rate was found at the 9th, so then I can use that to fine-tune the model.

Given that the “best mtry”, might vary and for reproducibility purposes, the “best mtry” value is directly picked from the above tuning in the fine-tunned model below. By doing so, I make sure that this code is more robust and allows adaptability to changes in new data.

FinalForest = randomForest(BuysProduct ~ .,
              data   = train.df,
              ntree  = 1000,
              mtry   =  min_error_row$mtry,
              importance = TRUE
              )
FinalForest
## 
## Call:
##  randomForest(formula = BuysProduct ~ ., data = train.df, ntree = 1000,      mtry = min_error_row$mtry, importance = TRUE) 
##                Type of random forest: classification
##                      Number of trees: 1000
## No. of variables tried at each split: 9
## 
##         OOB estimate of  error rate: 0.83%
## Confusion matrix:
##       No  Yes  class.error
## No  7881    3 0.0003805175
## Yes   75 1449 0.0492125984

7.8. Declaring the value of interest

In this case, I am interested in when the customer DOES buy a ticket next month. The variable in this case that refers to that is the predicted value BuysProduct = Yes, so I specify that in the code below.

pi_hat = predict(FinalForest, test.df, type = "prob")[,"Yes"]

7.9. Plot the ROC Curve

In order to understand the model predictive capabilities, I will plot the ROC Curve from where I expect to extract: Sensitivity, Specificity and AUC. The following are explained below:

Sensitivity (True Positive Rate): How good the test is at finding positive cases. Specificity (True Negative Rate): How good the test is at correctly identifying negative cases. AUC: Represents the ability of a model to distinguish between positive and negative examples.

rocCurve = roc(response = test.df$BuysProduct,
               predictor = pi_hat,
               levels = c("No","Yes"))
## Setting direction: controls < cases
plot(rocCurve,print.thres = TRUE, print.auc = TRUE)

pi_star <- coords(rocCurve, "best", ret = "threshold")$threshold[1]
sens <- coords(rocCurve, "best", ret = "sensitivity")$sensitivity
spec <- coords(rocCurve, "best", ret = "specificity")$specificity
AUC <- as.numeric(rocCurve$auc)

7.9.1. Interpreting the ROC Curve results

So, we may translate the above graph statistics to:

  • π* = 23.25, π* or Pi Star means that we would predict that a customer will buy a ticket next month when the probability of a cusomter buying a next month is of 23.25.
  • AUC = 99.88 (varies between 50% and 100% - closer to 1 is better).
  • Sensitivity: 0.9946237, We correctly predict when a customer will BUY a ticket next month 99.46% of the time, when the customer ended up buying a ticket next month.
  • Specificity: 0.9934343, We correctly predict when a customer will NOT BUY the ticket next month 99.34% of the time, when the customer never ended up buying a ticket next month.

The Sensitivity and Specificity shown above will only be archived if we set the Pi Star to 23.25%

7.10. Extracting the feature importance

By looking at the feature importance I expect to to understand how often and how much each feature contributes to making accurate predictions across all the trees in the forest.

# Make a column of predicted values (Yes or No)
pi_star = coords(rocCurve, "best", ret = "threshold")$threshold
test.df$forestPred= ifelse(pi_hat>pi_star, "Yes", "No")

7.11. Plotting the feature importance

# Extract variable importance
vi <- data.frame(Variable = rownames(FinalForest$importance),
                 Importance = FinalForest$importance[, "MeanDecreaseAccuracy"])

# Create the variable importance plot
library(ggplot2)
ggplot(data = vi) +
  geom_bar(aes(x = reorder(Variable, Importance), 
               weight = Importance),
           position = "identity") +
  coord_flip() +
  labs(x = "Variable Name", y = "Importance") +
  ggtitle("Variable Importance Plot for FinalForest Model")

8. Descriptive Modelling

In my analysis, the selection of a Binomial Generalized Linear Model (GLM) with a logit link was deliberate and guided by specific considerations:

1. Binary Outcome Nature:

  • The binary nature of our outcome variable (“Purchase_bin”) aligns seamlessly with the inherent strengths of a Binomial GLM.

2. Interpretability through Odds Ratios:

  • The use of logistic regression with a logit link ensures easy interpretation, especially through odds ratios, enhancing the clarity of our findings.

3. Systematic Feature Inclusion:

  • A stepwise approach incorporates features based on importance, controlling model complexity and focusing on relevant variables.

4. Incorporation of Important Features:

  • Utilizing feature importance rankings from a Random Forest model enriches our logistic regression, capturing nuanced relationships.

5. AIC and BIC Model Evaluation:

  • Models are assessed using AIC and BIC, aiding in the selection of the most suitable model by balancing goodness of fit and simplicity.

6. Adaptability to Binomial Data:

  • GLMs are tailored for binomial outcomes, aligning the statistical framework with the distinctive characteristics of our data.

8.1. Create a bernoulli random variable

cb_data$Purchase_bin = ifelse(cb_data$BuysProduct == "Yes",1,0)

8.2. Fit models with different x variables based on the feature selection results

I will extract the feature importance variables from the above plot in order of importance, so that I can later extract the features for each different model. In other words, I will run trough all the models possible based on the importance plot to predict our predicted variable. I will start with the first model only having the most important variable shown on the graph, then I will add one feature at a time, fit that and extract the AIC and BIC.

# Order variable names by importance in descending order
variable_order <- vi$Variable[order(-vi$Importance)]

# Create an empty dataframe to store results
result_df <- data.frame(Model = character(), AIC = numeric(), BIC = numeric(), Features = character(), stringsAsFactors = FALSE)

# Loop through each model
for (i in seq_along(variable_order)) {
  # Build formula for the model
  formula <- as.formula(paste("Purchase_bin ~", paste(variable_order[1:i], collapse = " + ")))

  # Fit the model
  model <- glm(formula, data = cb_data, family = binomial(link = "logit"))

  # Get AIC and BIC
  aic_value <- AIC(model)
  bic_value <- BIC(model)

  # Get model features
  features <- paste(variable_order[1:i], collapse = ", ")

  # Store results in the dataframe
  result_df <- rbind(result_df, data.frame(Model = paste("model_", i, sep = ""), AIC = round(aic_value), BIC = round(bic_value), Features = features, stringsAsFactors = FALSE))
}

8.3. Compare the results of each model

The follwoing graph will showcase the AIC and BIC for each model made, here are the variables that each model had

  • Model 1 : TotalCheckInLikesReceived
  • Model 2 : TotalCheckInLikesReceived, CompanyFollower
  • Model 3 : TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits
  • Model 4 : TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult
  • Model 5 : TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven
  • Model 6 : TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn
  • Model 7 : TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn, YearlyAvgCheckIns
  • Model 8 : TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn, YearlyAvgCheckIns, Avg_DailyMinPerView
  • Model 9 : TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn, YearlyAvgCheckIns, Avg_DailyMinPerView, FamilyMembers
  • Model 10 : TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn, YearlyAvgCheckIns, Avg_DailyMinPerView, FamilyMembers, TravelNetworkRating
  • Model 11 : TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn, YearlyAvgCheckIns, Avg_DailyMinPerView, FamilyMembers, TravelNetworkRating, YearlyAvgCheckIns.1
  • Model 12 : TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn, YearlyAvgCheckIns, Avg_DailyMinPerView, FamilyMembers, TravelNetworkRating, YearlyAvgCheckIns.1, YearlyAvgComments
  • Model 13 : TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn, YearlyAvgCheckIns, Avg_DailyMinPerView, FamilyMembers, TravelNetworkRating, YearlyAvgCheckIns.1, YearlyAvgComments, PreferredLocation
  • Model 14 : TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn, YearlyAvgCheckIns, Avg_DailyMinPerView, FamilyMembers, TravelNetworkRating, YearlyAvgCheckIns.1, YearlyAvgComments, PreferredLocation, IsWorking
  • Model 15 : TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn, YearlyAvgCheckIns, Avg_DailyMinPerView, FamilyMembers, TravelNetworkRating, YearlyAvgCheckIns.1, YearlyAvgComments, PreferredLocation, IsWorking, PreferedDevice
  • Model 16 : TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn, YearlyAvgCheckIns, Avg_DailyMinPerView, FamilyMembers, TravelNetworkRating, YearlyAvgCheckIns.1, YearlyAvgComments, PreferredLocation, IsWorking, PreferedDevice, MonthAvgComments
result_df$Model <- factor(result_df$Model, levels = unique(result_df$Model))

# ggplot code
ggplot(data=result_df, aes(x=Model, y=AIC, group=1)) +
  geom_line(aes(color = "AIC")) +
  geom_point(aes(color = "AIC")) +
  
  geom_line(aes(y = BIC, color = "BIC")) +
  geom_point(aes(y = BIC, color = "BIC")) +
  
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  
  # Customize colors
  scale_color_manual(values = c("AIC" = "blue", "BIC" = "red"))+
  
  # Label y-axis
  labs(y = "AIC & BIC")

Although I am plotting both AIC and BIC, I will use the BIC statistic given the the size of our data could be considered big (number of rows in dataset: 11760) and usually for cases where n is larger, more parsimonious criteria, such as BIC, often seem better. On the other hand, cases where n is small, criteria with lower under-fitting rates, AIC could work better.

8.4. Final Model Variable Selection

That being said, looking at the above graph I could have chosen Model 15 given that it provides the lowest BIC: 8585 but given the purpose of this model (Descriptive), I am taking into account that a more modest model with less features to interpret will help with the interpretation of the model and the feature importance.

Additionally, looking back at the variable importance plot, the predictor variables that are added to the models after Model 7 (Model 8, Model 9..) represent a 37% or lower model importance, so that provides even more reasons to use Model 7 as my predictor model of choice.

8.4.1. Model with lowest BIC

Model 15 Predictor Variables: TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn, YearlyAvgCheckIns, Avg_DailyMinPerView, FamilyMembers, TravelNetworkRating, YearlyAvgCheckIns.1, YearlyAvgComments, PreferredLocation, IsWorking, PreferedDevice

8.4.2. Modest model

Model 7 Predictor Variables: TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn, YearlyAvgCheckIns

8.5. Fitting chosen model

FinalModel = glm(BuysProduct ~ TotalCheckInLikesReceived + CompanyFollower + YearlyAvgPageVisits 
                 + IsAdult + TotalCheckInLikesGiven + WeeksSinceLastCheckIn + YearlyAvgCheckIns, 
          data = cb_data, 
          family = binomial(link = "logit"))

FinalModel
## 
## Call:  glm(formula = BuysProduct ~ TotalCheckInLikesReceived + CompanyFollower + 
##     YearlyAvgPageVisits + IsAdult + TotalCheckInLikesGiven + 
##     WeeksSinceLastCheckIn + YearlyAvgCheckIns, family = binomial(link = "logit"), 
##     data = cb_data)
## 
## Coefficients:
##               (Intercept)  TotalCheckInLikesReceived  
##                 0.0142490                 -0.0001109  
##        CompanyFollowerYes        YearlyAvgPageVisits  
##                 1.4961521                 -0.0051923  
##                IsAdultYes     TotalCheckInLikesGiven  
##                -1.0975823                 -0.0000121  
##     WeeksSinceLastCheckIn          YearlyAvgCheckIns  
##                 0.1246231                  0.0299342  
## 
## Degrees of Freedom: 11759 Total (i.e. Null);  11752 Residual
## Null Deviance:       10390 
## Residual Deviance: 8613  AIC: 8629
beta <- coef(FinalModel)
beta
##               (Intercept) TotalCheckInLikesReceived        CompanyFollowerYes 
##              0.0142490255             -0.0001108890              1.4961520684 
##       YearlyAvgPageVisits                IsAdultYes    TotalCheckInLikesGiven 
##             -0.0051922958             -1.0975823108             -0.0000120972 
##     WeeksSinceLastCheckIn         YearlyAvgCheckIns 
##              0.1246230856              0.0299341535
exp(beta)
##               (Intercept) TotalCheckInLikesReceived        CompanyFollowerYes 
##                 1.0143510                 0.9998891                 4.4644770 
##       YearlyAvgPageVisits                IsAdultYes    TotalCheckInLikesGiven 
##                 0.9948212                 0.3336768                 0.9999879 
##     WeeksSinceLastCheckIn         YearlyAvgCheckIns 
##                 1.1327214                 1.0303867
confint(FinalModel)
## Waiting for profiling to be done...
##                                   2.5 %        97.5 %
## (Intercept)               -2.466122e-01  2.758440e-01
## TotalCheckInLikesReceived -1.286254e-04 -9.356855e-05
## CompanyFollowerYes         1.386003e+00  1.606813e+00
## YearlyAvgPageVisits       -6.185949e-03 -4.210156e-03
## IsAdultYes                -1.208781e+00 -9.872058e-01
## TotalCheckInLikesGiven    -1.599126e-05 -8.222428e-06
## WeeksSinceLastCheckIn      1.039237e-01  1.452851e-01
## YearlyAvgCheckIns          2.386100e-02  3.598956e-02

8.6. Extracting Model Coefficients

# Extracting coefficient estimates
betahat <- coef(FinalModel)

# Extracting the diagonal of the covariance matrix
var_betahat <- vcov(FinalModel) %>% diag

# Calculating the quantile for a 95% confidence interval
quantile <- qnorm(c(0.025, 0.975))

# Calculating lower and upper bounds
lower <- betahat - sqrt(var_betahat) * quantile[2]
upper <- betahat + sqrt(var_betahat) * quantile[2]

# Exponentiating to get odds ratio CI's
odds_ratios <- exp(betahat)
lower_odds <- exp(lower)
upper_odds <- exp(upper)

# Creating a data frame with variable names and results
conf_df <- data.frame(
  Variable = names(betahat),
  Odds_Ratio = odds_ratios,
  Lower_Bound = lower_odds,
  Upper_Bound = upper_odds)

# Adding the OddsResult column based on the condition
conf_df$OddsResult <- ifelse(conf_df$Odds_Ratio >= 1, "Increase", "Decrease")

# Calculating the factor as a percentage and formatting it
conf_df$Factor_Percentage <- sprintf("%.4f%%", abs(1 - conf_df$Odds_Ratio) * 100)

# Printing the results
conf_df
##                                            Variable Odds_Ratio Lower_Bound
## (Intercept)                             (Intercept)  1.0143510   0.7811864
## TotalCheckInLikesReceived TotalCheckInLikesReceived  0.9998891   0.9998716
## CompanyFollowerYes               CompanyFollowerYes  4.4644770   3.9978751
## YearlyAvgPageVisits             YearlyAvgPageVisits  0.9948212   0.9938390
## IsAdultYes                               IsAdultYes  0.3336768   0.2986892
## TotalCheckInLikesGiven       TotalCheckInLikesGiven  0.9999879   0.9999840
## WeeksSinceLastCheckIn         WeeksSinceLastCheckIn  1.1327214   1.1095409
## YearlyAvgCheckIns                 YearlyAvgCheckIns  1.0303867   1.0241582
##                           Upper_Bound OddsResult Factor_Percentage
## (Intercept)                 1.3171095   Increase           1.4351%
## TotalCheckInLikesReceived   0.9999066   Decrease           0.0111%
## CompanyFollowerYes          4.9855371   Increase         346.4477%
## YearlyAvgPageVisits         0.9958043   Decrease           0.5179%
## IsAdultYes                  0.3727629   Decrease          66.6323%
## TotalCheckInLikesGiven      0.9999918   Decrease           0.0012%
## WeeksSinceLastCheckIn       1.1563863   Increase          13.2721%
## YearlyAvgCheckIns           1.0366531   Increase           3.0387%

8.7. Model Coefficient Interpretation

TotalCheckInLikesReceived: For each additional like the customer has given in other check-ins, the odds of a customer buying a ticket next month are estimated to Decrease by a factor of approximately 0.9998891.

  • This means that, on average, the odds of the event (customer buying a ticket) occurring Decrease by approximately 0.0111% for each additional like in other check-ins, holding other variables constant. The associated 95% confidence interval for this odds ratio is between approximately 0.9998716 and 0.9999066.

CompanyFollowerYes: If the individual follows the company account (CompanyFollowerYes),the odds of a customer buying a ticket next month are estimated to Increase by a factor of approximately 4.464477, times the odds of compared to a customer that does not follow the company account, holding all other vaiables constant.

  • This means that, on average, the odds of the event (customer buying a ticket) occurring Increase by approximately 346.4477%for each additional like in other check-ins, holding other variables constant. The associated 95% confidence interval for this odds ratio is between approximately 3.9978751 and 4.9855371.

YearlyAvgPageVisits: For each additional customer visit to the website on average, the odds of a customer buying a ticket next month are estimated to Decrease by a factor of approximately 0.9948212.

  • This means that, on average, the odds of the event (customer buying a ticket) occurring Decrease by approximately 0.5179% for each visit to the website on average per year, holding other variables constant. The associated 95% confidence interval for this odds ratio is between approximately 0.993839 and 0.9958043.

9. Graphing Model Variables

After the model coefficient interpretations, I will include some graphs to better understand the interpretations.

9.1. Graphing Total Likes and Product Purchase

Understanding how the customer being an adult or not and the likes they have given to previous destinations where they have Checked-In in the past affects whether they will buy a ticket next month or not.

ggplot(data = cb_data)+
  geom_histogram(aes(x = TotalCheckInLikesReceived, fill = BuysProduct), position = "fill", binwidth = 800) + 
  scale_fill_brewer("Customer\nBuys Product", palette = "Paired")+
  labs(x = "Total Check In Likes", y = "Proportion") +
  facet_wrap(~IsAdult, labeller = labeller(IsAdult = c(No = "Not Adult", Yes = "Adult")))

9.2. Graphing Yearly Average Page Visits and Product Purchase

Understanding how the customer being a follower or not and the yearly average number of visits to a certain page will affect to whether they will buy a ticket next month or not.

ggplot(data = cb_data)+
  geom_histogram(aes(x = YearlyAvgPageVisits, fill = BuysProduct), position = "fill", binwidth = 30) + 
  scale_fill_brewer("Customer\nBuys Product", palette = "Paired")+
  labs(x = "Yearly Avg Page Visits", y = "Proportion") +
  facet_wrap(~CompanyFollower, labeller = labeller(CompanyFollower = c(No = "Not Follower", Yes = "Follows")))
## Warning: Removed 8 rows containing missing values (`geom_bar()`).

9.3. Graphing Yearly Average Check-In’s and Product Purchase

Understanding how the customer being an adult or not and the yearly number of check-in’s they have completed in the past affects whether they will buy a ticket next month or not.

ggplot(data = cb_data)+
  geom_histogram(aes(x = YearlyAvgCheckIns, fill = BuysProduct), position = "fill", binwidth = 2) + 
  scale_fill_brewer("Customer\nBuys Product", palette = "Paired")+
  labs(x = "Yearly Avg Cutomer Check In's", y = "Proportion") +
  facet_wrap(~IsAdult, labeller = labeller(IsAdult = c(No = "Not Adult", Yes = "Adult")))

9.4. Graphing Yearly Average Check-In’s and Product Purchase

Understanding how the customer being an adult or not and the average number of pages they visited might affect whether the customer will buy a ticket next month or not.

ggplot(data = cb_data)+
  geom_histogram(aes(x = YearlyAvgPageVisits, fill = BuysProduct), position = "fill", binwidth = 30) + 
  scale_fill_brewer("Customer\nBuys Product", palette = "Paired")+
  labs(x = "Yearly Avg Cutomer Page Visits", y = "Proportion") +
  facet_wrap(~IsAdult, labeller = labeller(IsAdult = c(No = "Not Adult", Yes = "Adult")))
## Warning: Removed 12 rows containing missing values (`geom_bar()`).

9.5. Graphing Total Check-In’s Received and Product Purchase

Understanding how the total check-in likes received and the average number of pages a customer visits might affect whether the customer might buy a ticket next month or not.

ggplot(data = cb_data) +
  geom_point(aes(x =TotalCheckInLikesReceived, y = YearlyAvgPageVisits , colour = BuysProduct)) +
  labs(x = "Total Check In Likes Received", y = "Yearly Avg Page Visits") +
  scale_colour_brewer("Customer\nBuys Product", palette = "Paired")

10. Recommendations

10.1. Strategic Social Media Engagement:

Let’s develop a targeted social media engagement strategy to encourage more customers to follow our company’s account. Given the substantial positive impact of being a CompanyFollower, increasing our follower base has the potential to significantly boost ticket sales.

10.2. Enhanced Online Experience:

Despite the small impact, let’s consider optimizing our website to enhance the user experience. This could involve personalized content recommendations, targeted promotions, or other features aimed at increasing the conversion rate for website visits to ticket purchases.

10.3. Continuous Monitoring and Iteration:

We’ll establish a routine for monitoring the model’s performance and iterate as needed. While Model 7 has been chosen for its balance between simplicity and performance, periodic reassessment should be conducted to ensure continued relevance and accuracy.

11. Conclusions

11.1. Model Validation for Confidence:

Rest assured that the selected Model 7 demonstrates robust predictive performance, with a high AUC of 99.88%. The model’s ability to correctly identify both positive and negative cases (sensitivity and specificity exceeding 99%) instills confidence in its reliability.

11.2. Key Drivers of Ticket Purchases:

CompanyFollower emerges as a key driver of ticket purchases, emphasizing the importance of building and maintaining a strong social media presence. While social interactions (TotalCheckInLikesReceived) play a role, their impact is relatively small and may require a more nuanced understanding.

11.3. Balancing Complexity and Efficiency:

I’ve opted for Model 7 over more complex models based on the variable importance plot, with variables beyond Model 7 contributing 37% or less to the model. This choice strikes a balance between model performance and computational efficiency, ensuring we get the most value with the least complexity.

11.4. Decision-Making Threshold:

The suggested probability threshold of 0.2325 provides a balanced trade-off between sensitivity and specificity. This threshold can be fine-tuned based on our business considerations and the acceptable level of false positives and false negatives.

11.5. Continuous Improvement Journey:

Let’s emphasize the importance of ongoing monitoring and adaptation. As our customers’ behaviors and preferences evolve, the model should be regularly updated to ensure its continued relevance and accuracy in predicting ticket purchases.

12. References

  1. R Markdowon
  2. Dataset