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.
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?
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?
## Type 'citation("pROC")' for a citation.
##
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
##
## cov, smooth, var
## ── 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
##
## Attaching package: 'kableExtra'
##
## The following object is masked from 'package:dplyr':
##
## group_rows
## Loading required package: viridisLite
This is my data. It is cool. There are 11760 rows in my data.
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:
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.
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:
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)
))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.
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:
Action Plan: Collapse the working_flag value of 0 to “Yes”
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.
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:
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)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.
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:
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)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.
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:
# 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)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.
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:
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
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)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.
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)# 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
##
##
##
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:
2. Ensemble Benefits:
3. Reduction of Overfitting:
4. Handling Complexity:
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
I will be using a split of 80% for training and 20% for test data
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)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
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.
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.
## Setting direction: controls < cases
So, we may translate the above graph statistics to:
The Sensitivity and Specificity shown above will only be archived if we set the Pi Star to 23.25%
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.
# 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")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:
2. Interpretability through Odds Ratios:
3. Systematic Feature Inclusion:
4. Incorporation of Important Features:
5. AIC and BIC Model Evaluation:
6. Adaptability to Binomial Data:
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))
}The follwoing graph will showcase the AIC and BIC for each model made, here are the variables that each model had
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.
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.
Model 15 Predictor Variables: TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn, YearlyAvgCheckIns, Avg_DailyMinPerView, FamilyMembers, TravelNetworkRating, YearlyAvgCheckIns.1, YearlyAvgComments, PreferredLocation, IsWorking, PreferedDevice
Model 7 Predictor Variables: TotalCheckInLikesReceived, CompanyFollower, YearlyAvgPageVisits, IsAdult, TotalCheckInLikesGiven, WeeksSinceLastCheckIn, YearlyAvgCheckIns
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
## (Intercept) TotalCheckInLikesReceived CompanyFollowerYes
## 0.0142490255 -0.0001108890 1.4961520684
## YearlyAvgPageVisits IsAdultYes TotalCheckInLikesGiven
## -0.0051922958 -1.0975823108 -0.0000120972
## WeeksSinceLastCheckIn YearlyAvgCheckIns
## 0.1246230856 0.0299341535
## (Intercept) TotalCheckInLikesReceived CompanyFollowerYes
## 1.0143510 0.9998891 4.4644770
## YearlyAvgPageVisits IsAdultYes TotalCheckInLikesGiven
## 0.9948212 0.3336768 0.9999879
## WeeksSinceLastCheckIn YearlyAvgCheckIns
## 1.1327214 1.0303867
## 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
# 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%
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.
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.
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.
After the model coefficient interpretations, I will include some graphs to better understand the interpretations.
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")))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()`).
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")))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()`).
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")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.
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.
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.
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.
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.
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.
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.