Group Members:
| Matric Number | Name |
|---|---|
| 23056541 | Nicolas Sia Zheng Lim |
| 22099603 | Ong Xi Yan |
| 22113856 | Tan Jia Hui |
| 23060317 | Alicia Chua Yang Qin |
| 23053571 | Che Jia Min |
E‑commerce has exploded exponentially especially after covid-19 pandemic. Therefore, the shipping mode is important for user to manage the shipment lead time and on the end user’s satisfaction. E-commerce shipping includes order taking and processing, product selection and packaging at a warehouse, label printing, shipment, and even handling returns. That might sound simple enough. If you’ve seen a well-run warehouse, it might even look simply. Though, the various moving parts add a degree of complexity that varies according to the kinds and sizes of goods you sell, the areas you’ll deliver to, the shipping options and speeds you select, and more.
In this paper, our goal is to identify the trends and patterns in the data that can provide actionable insights for an international e-commerce company as they would like to know which type of service is more suitable by the client.
What are the factors that most influence the on-time delivery of products?
How does the delivery performance of the products affect customer satisfaction in terms of customer rating scores?
How can we use the dataset information to build models that tell us the chances of a shipment being late and help estimate the cost of the product?
To discover the factors that influence whether products are delivered on time, identifying potential areas for logistics improvement.
To explore how different variables, such as the number of customer care calls and customer ratings, relate to service satisfaction.
To develop predictive models to determine the likelihood of a shipment being late and the product cost needed based on various variables in the dataset.
Title: “E-Commerce Shipping Data”
Year : 2020
This dataset delves into the realm of international e-commerce, capturing the intricacies of an established company specializing in electronic products. With a keen interest in unraveling key insights from their extensive customer database, the company aims to leverage advanced machine learning techniques for a comprehensive understanding of their clientele.
Containing 10,999 observations across 12 variables, this dataset serves as a valuable resource for model building and analysis. For those eager to explore the dynamics of customer behavior and predictive modeling in the context of electronic product shipping.
The dataset is accessible on Kaggle via the following link: https://www.kaggle.com/datasets/prachi13/customer-analytics
| No. | Variables | Description |
|---|---|---|
| 1. | ID | Customers’ ID number. |
| 2. | Warehouse_block | The company operates a large warehouse divided into blocks (A, B, C, D, F). |
| 3. | Mode_of_Shipment | Products are shipped using various modes, including Ship, Flight, and Road. |
| 4. | Customer_care_calls | Count of calls made for shipment inquiries. |
| 5. | Customer_rating | Ratings provided by customers, ranging from 1 (Lowest/Worst) to 5 (Highest/Best). |
| 6. | Cost_of_the_Product | Product cost in US Dollars. |
| 7. | Prior_purchases | Number of previous purchases made by the customers. |
| 8. | Product_importance | Categorization of product importance into low, medium, or high. |
| 9. | Gender | Classification of customers as Male or Female. |
| 10. | Discount_offered | Discount provided for the specific product. |
| 11. | Weight_in_gms | Weight of the product measured in grams. |
| 12. | Reached.on.Time_Y.N | Target variable indicating whether the product reached on time (0 for Yes, 1 for No). |
In this phase, the procedures involve recognizing elements within the data that are incorrect, incomplete, inaccurate, irrelevant, or missing. Subsequently, necessary adjustments are made, which may entail modifications, replacements, or deletions to enhance the overall data quality.
The initial stage involves importing pertinent libraries and loading the dataset.
df_ship = read.csv("Shipping.csv")
head(df_ship)
## ID Warehouse_block Mode_of_Shipment Customer_care_calls Customer_rating
## 1 1 D Flight 4 2
## 2 2 F Flight 4 5
## 3 3 A Flight 2 2
## 4 4 B Flight 3 3
## 5 5 C Flight 2 2
## 6 6 F Flight 3 1
## Cost_of_the_Product Prior_purchases Product_importance Gender
## 1 177 3 low F
## 2 216 2 low M
## 3 183 4 low M
## 4 176 4 medium M
## 5 184 3 medium F
## 6 162 3 medium F
## Discount_offered Weight_in_gms Reached.on.Time_Y.N
## 1 44 1233 1
## 2 59 3088 1
## 3 48 3374 1
## 4 10 1177 1
## 5 46 2484 1
## 6 12 1417 1
Dimension of the raw data.
print(dim(df_ship))
## [1] 10999 12
Show the data structure of the raw data.
str(df_ship)
## 'data.frame': 10999 obs. of 12 variables:
## $ ID : int 1 2 3 4 5 6 7 8 9 10 ...
## $ Warehouse_block : chr "D" "F" "A" "B" ...
## $ Mode_of_Shipment : chr "Flight" "Flight" "Flight" "Flight" ...
## $ Customer_care_calls: int 4 4 2 3 2 3 3 4 3 3 ...
## $ Customer_rating : int 2 5 2 3 2 1 4 1 4 2 ...
## $ Cost_of_the_Product: int 177 216 183 176 184 162 250 233 150 164 ...
## $ Prior_purchases : int 3 2 4 4 3 3 3 2 3 3 ...
## $ Product_importance : chr "low" "low" "low" "medium" ...
## $ Gender : chr "F" "M" "M" "M" ...
## $ Discount_offered : int 44 59 48 10 46 12 3 48 11 29 ...
## $ Weight_in_gms : int 1233 3088 3374 1177 2484 1417 2371 2804 1861 1187 ...
## $ Reached.on.Time_Y.N: int 1 1 1 1 1 1 1 1 1 1 ...
The mean, median, first quartile, third quartile, minimum and maximum value of each columns are shown above.
print(summary(df_ship))
## ID Warehouse_block Mode_of_Shipment Customer_care_calls
## Min. : 1 Length:10999 Length:10999 Min. :2.000
## 1st Qu.: 2750 Class :character Class :character 1st Qu.:3.000
## Median : 5500 Mode :character Mode :character Median :4.000
## Mean : 5500 Mean :4.054
## 3rd Qu.: 8250 3rd Qu.:5.000
## Max. :10999 Max. :7.000
## Customer_rating Cost_of_the_Product Prior_purchases Product_importance
## Min. :1.000 Min. : 96.0 Min. : 2.000 Length:10999
## 1st Qu.:2.000 1st Qu.:169.0 1st Qu.: 3.000 Class :character
## Median :3.000 Median :214.0 Median : 3.000 Mode :character
## Mean :2.991 Mean :210.2 Mean : 3.568
## 3rd Qu.:4.000 3rd Qu.:251.0 3rd Qu.: 4.000
## Max. :5.000 Max. :310.0 Max. :10.000
## Gender Discount_offered Weight_in_gms Reached.on.Time_Y.N
## Length:10999 Min. : 1.00 Min. :1001 Min. :0.0000
## Class :character 1st Qu.: 4.00 1st Qu.:1840 1st Qu.:0.0000
## Mode :character Median : 7.00 Median :4149 Median :1.0000
## Mean :13.37 Mean :3634 Mean :0.5967
## 3rd Qu.:10.00 3rd Qu.:5050 3rd Qu.:1.0000
## Max. :65.00 Max. :7846 Max. :1.0000
#install the packages
#install.packages("tidyverse")
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.4 ✔ readr 2.1.4
## ✔ forcats 1.0.0 ✔ stringr 1.5.1
## ✔ ggplot2 3.4.4 ✔ tibble 3.2.1
## ✔ lubridate 1.9.3 ✔ tidyr 1.3.0
## ✔ purrr 1.0.2
## ── 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
missing_values<-df_ship %>% summarise_all(~ sum(is.na(.))) # use dplyr package
missing_values
## ID Warehouse_block Mode_of_Shipment Customer_care_calls Customer_rating
## 1 0 0 0 0 0
## Cost_of_the_Product Prior_purchases Product_importance Gender
## 1 0 0 0 0
## Discount_offered Weight_in_gms Reached.on.Time_Y.N
## 1 0 0 0
The dplyr package is used to check for any missing values in the dataset.There are no missing values in our data frame.
missing<-colSums(is.na(df_ship)) # using base package
# The columns: Gender,Warehouse_block, Mode_of shipment and Product_importance are categorical variables.
# They are converted to numerical variables using the recode() function in dplyr package for compatibility with machine learning models and ease of analysis.
# convert gender (categorical variable) to binary values (M = 0, F = 1)
df_ship <-df_ship %>% mutate(Gender = ifelse(Gender == "M",0,1))
head(df_ship)
## ID Warehouse_block Mode_of_Shipment Customer_care_calls Customer_rating
## 1 1 D Flight 4 2
## 2 2 F Flight 4 5
## 3 3 A Flight 2 2
## 4 4 B Flight 3 3
## 5 5 C Flight 2 2
## 6 6 F Flight 3 1
## Cost_of_the_Product Prior_purchases Product_importance Gender
## 1 177 3 low 1
## 2 216 2 low 0
## 3 183 4 low 0
## 4 176 4 medium 0
## 5 184 3 medium 1
## 6 162 3 medium 1
## Discount_offered Weight_in_gms Reached.on.Time_Y.N
## 1 44 1233 1
## 2 59 3088 1
## 3 48 3374 1
## 4 10 1177 1
## 5 46 2484 1
## 6 12 1417 1
# convert Warehouse_block (categorical variable) to numerical values (A = 0, B = 1, C = 2, D = 3, F = 4)
df_ship<-df_ship %>% mutate(Warehouse_block = recode(Warehouse_block, "A" = 0, "B" = 1, "C" = 2, "D" = 3, "F" = 4))
head(df_ship)
## ID Warehouse_block Mode_of_Shipment Customer_care_calls Customer_rating
## 1 1 3 Flight 4 2
## 2 2 4 Flight 4 5
## 3 3 0 Flight 2 2
## 4 4 1 Flight 3 3
## 5 5 2 Flight 2 2
## 6 6 4 Flight 3 1
## Cost_of_the_Product Prior_purchases Product_importance Gender
## 1 177 3 low 1
## 2 216 2 low 0
## 3 183 4 low 0
## 4 176 4 medium 0
## 5 184 3 medium 1
## 6 162 3 medium 1
## Discount_offered Weight_in_gms Reached.on.Time_Y.N
## 1 44 1233 1
## 2 59 3088 1
## 3 48 3374 1
## 4 10 1177 1
## 5 46 2484 1
## 6 12 1417 1
# convert Mode_of_Shipment (categorical variable) to numerical values (Ship = 0, Flight = 1, Road = 2)
df_ship<-df_ship %>% mutate(Mode_of_Shipment = recode(Mode_of_Shipment, "Ship" = 0, "Flight" = 1, "Road" = 2))
head(df_ship)
## ID Warehouse_block Mode_of_Shipment Customer_care_calls Customer_rating
## 1 1 3 1 4 2
## 2 2 4 1 4 5
## 3 3 0 1 2 2
## 4 4 1 1 3 3
## 5 5 2 1 2 2
## 6 6 4 1 3 1
## Cost_of_the_Product Prior_purchases Product_importance Gender
## 1 177 3 low 1
## 2 216 2 low 0
## 3 183 4 low 0
## 4 176 4 medium 0
## 5 184 3 medium 1
## 6 162 3 medium 1
## Discount_offered Weight_in_gms Reached.on.Time_Y.N
## 1 44 1233 1
## 2 59 3088 1
## 3 48 3374 1
## 4 10 1177 1
## 5 46 2484 1
## 6 12 1417 1
# convert Product_importance (categorical variable) to numerical values (low = 0, medium = 1, high =2)
df_ship<-df_ship %>% mutate(Product_importance = recode(Product_importance, "low" = 0, "medium" = 1, "high" = 2))
head(df_ship)
## ID Warehouse_block Mode_of_Shipment Customer_care_calls Customer_rating
## 1 1 3 1 4 2
## 2 2 4 1 4 5
## 3 3 0 1 2 2
## 4 4 1 1 3 3
## 5 5 2 1 2 2
## 6 6 4 1 3 1
## Cost_of_the_Product Prior_purchases Product_importance Gender
## 1 177 3 0 1
## 2 216 2 0 0
## 3 183 4 0 0
## 4 176 4 1 0
## 5 184 3 1 1
## 6 162 3 1 1
## Discount_offered Weight_in_gms Reached.on.Time_Y.N
## 1 44 1233 1
## 2 59 3088 1
## 3 48 3374 1
## 4 10 1177 1
## 5 46 2484 1
## 6 12 1417 1
# Calculate the percentage of missing values in each column
missing_percentage <- df_ship %>%
summarise_all(~ mean(is.na(.)) * 100)
missing_percentage
## ID Warehouse_block Mode_of_Shipment Customer_care_calls Customer_rating
## 1 0 0 0 0 0
## Cost_of_the_Product Prior_purchases Product_importance Gender
## 1 0 0 0 0
## Discount_offered Weight_in_gms Reached.on.Time_Y.N
## 1 0 0 0
#Find duplicate value
duplicate_counts <- df_ship%>%
group_by(across(everything())) %>%
summarise(duplicate_count = n() - 1) %>%
filter(duplicate_count > 0)
## `summarise()` has grouped output by 'ID', 'Warehouse_block',
## 'Mode_of_Shipment', 'Customer_care_calls', 'Customer_rating',
## 'Cost_of_the_Product', 'Prior_purchases', 'Product_importance', 'Gender',
## 'Discount_offered', 'Weight_in_gms'. You can override using the `.groups`
## argument.
duplicate_counts
## # A tibble: 0 × 13
## # Groups: ID, Warehouse_block, Mode_of_Shipment, Customer_care_calls,
## # Customer_rating, Cost_of_the_Product, Prior_purchases, Product_importance,
## # Gender, Discount_offered, Weight_in_gms [0]
## # ℹ 13 variables: ID <int>, Warehouse_block <dbl>, Mode_of_Shipment <dbl>,
## # Customer_care_calls <int>, Customer_rating <int>,
## # Cost_of_the_Product <int>, Prior_purchases <int>, Product_importance <dbl>,
## # Gender <dbl>, Discount_offered <int>, Weight_in_gms <int>,
## # Reached.on.Time_Y.N <int>, duplicate_count <dbl>
# Export Clean dataset
write_csv(df_ship,"clean_shipping.csv")
str(df_ship)
## 'data.frame': 10999 obs. of 12 variables:
## $ ID : int 1 2 3 4 5 6 7 8 9 10 ...
## $ Warehouse_block : num 3 4 0 1 2 4 3 4 0 1 ...
## $ Mode_of_Shipment : num 1 1 1 1 1 1 1 1 1 1 ...
## $ Customer_care_calls: int 4 4 2 3 2 3 3 4 3 3 ...
## $ Customer_rating : int 2 5 2 3 2 1 4 1 4 2 ...
## $ Cost_of_the_Product: int 177 216 183 176 184 162 250 233 150 164 ...
## $ Prior_purchases : int 3 2 4 4 3 3 3 2 3 3 ...
## $ Product_importance : num 0 0 0 1 1 1 0 0 0 1 ...
## $ Gender : num 1 0 0 0 1 1 1 1 1 1 ...
## $ Discount_offered : int 44 59 48 10 46 12 3 48 11 29 ...
## $ Weight_in_gms : int 1233 3088 3374 1177 2484 1417 2371 2804 1861 1187 ...
## $ Reached.on.Time_Y.N: int 1 1 1 1 1 1 1 1 1 1 ...
sum(duplicated(df_ship))
## [1] 0
library(ggplot2)
library(corrplot)
## corrplot 0.92 loaded
library(colormap)
library(reshape2)
##
## Attaching package: 'reshape2'
## The following object is masked from 'package:tidyr':
##
## smiths
data <- read.csv("clean_shipping.csv")
numerical_cols <- names(data)[sapply(data, is.numeric)]
par(mfrow=c(2, 2), mar=c(4, 4, 2, 1))
for (col in numerical_cols) {
boxplot(data[[col]], main=col, col='blue')
}
ID: Appears to be a unique identifier for each record. It’s not useful for analysis and usually removed or ignored.
Warehouse_block and Mode_of_Shipment: These categorical variables don’t have outliers, which is typical for such data types.
Customer_care_calls: There are a few outliers indicating some customers made a lot more calls than typical. This may warrant further investigation to understand the reasons behind the high number of calls.
Customer_rating: The distribution is uniform, indicating that the ratings are evenly distributed with no outliers.
Cost_of_the_Product: No visible outliers, but there is a slight skewness towards higher values. It might indicate that while most products fall within a certain price range, there are some products that are significantly more expensive.
Prior_purchases: There are several outliers indicating that some customers have made many more purchases than the average customer.
Product_importance: As a binary variable, there are no outliers.
Gender: Likely a binary variable, so the concept of outliers doesn’t apply.
Discount_offered: Significant outliers are present, indicating occasional very large discounts compared to the norm.
Weight_in_gms: There are outliers at the lower end, indicating some products are much lighter than the rest.
Reached.on.Time_Y.N: As a binary variable, there are no outliers.
cor_matrix <- cor(data[numerical_cols], use="complete.obs")
# Plot the correlation matrix
corrplot(cor_matrix, method="color", addCoef.col="black",
tl.col="black",number.cex=0.7)
Strong Negative Correlation:
Moderate Positive Correlation:
No or Weak Correlation:
data <- data[, !names(data) %in% c("ID")]
head(data)
## Warehouse_block Mode_of_Shipment Customer_care_calls Customer_rating
## 1 3 1 4 2
## 2 4 1 4 5
## 3 0 1 2 2
## 4 1 1 3 3
## 5 2 1 2 2
## 6 4 1 3 1
## Cost_of_the_Product Prior_purchases Product_importance Gender
## 1 177 3 0 1
## 2 216 2 0 0
## 3 183 4 0 0
## 4 176 4 1 0
## 5 184 3 1 1
## 6 162 3 1 1
## Discount_offered Weight_in_gms Reached.on.Time_Y.N
## 1 44 1233 1
## 2 59 3088 1
## 3 48 3374 1
## 4 10 1177 1
## 5 46 2484 1
## 6 12 1417 1
The boxplots allow visually compare the median and range of the number of calls across the different product importance categories. As graph shows if products with higher stated importance levels tend to generate more or fewer customer care calls on average. The distribution shows whether the call volume also differs in spread across the categories.
data$Product_importance <- factor(data$Product_importance,
levels = c(0, 1, 2),
labels = c("Low", "Medium", "High"))
ggplot(data, aes(x=Product_importance, y=Customer_care_calls)) +
geom_boxplot() +
labs(title="Customer Care Calls by Product Importance",
x = "Product Importance",
y = "Number of Calls")
Overall, the grouped bar chart above shows that the number of products that were delayed is more compared to those that have reached on time in almost all levels of prior purchases. As the number of prior purchases increases, the probability for the products to be delayed also increases. Businesses tend to be complacent with loyal and frequent customers as they assume that these customers might be more lenient and forgiving of delays. The delay might also be due to logistic challenges, which includes shipping and inventory issues.
ggplot(data, aes(x = Reached.on.Time_Y.N, y = after_stat(count), fill = factor(Prior_purchases))) +
geom_bar(position = position_dodge(width = 0.9), stat = "count") +
geom_text(aes(label = after_stat(count)), vjust = 1.6, position = position_dodge(width = 0.9), stat = "count", color = "black", size = 3.5) +
labs(title = "Numbers of Prior purchases Across On-time delivery performance",
x = "Product Importance",
y = "Count of Each prior purchases",
fill = "Prior Purchases") +
scale_fill_brewer(palette = "Set2") +
theme_minimal() +
theme(legend.position = "bottom")
The bar chart indicates that customer ratings are fairly evenly distributed between genders across all rating levels. There is no significant difference in the number of ratings given by males and females, suggesting that gender does not influence customer ratings.
data$Gender <- factor(data$Gender, labels = c("Male", "Female"))
ggplot(data, aes(x = Customer_rating, fill = Gender)) +
geom_bar(position = "dodge") +
geom_text(aes(label = after_stat(count)), stat = "count", position = position_dodge(width = 0.9), vjust = -0.25, size = 2) +
scale_fill_manual(values = c("Male" = "blue", "Female" = "red"), name = "Gender") +
labs(title = "Customer Ratings by Gender",
x = "Customer Rating",
y = "Count of Ratings") +
theme_minimal()
correlation_coefficient <- cor(data$Customer_care_calls, data$Customer_rating, use = "complete.obs")
print(paste("Correlation Coefficient:", correlation_coefficient))
## [1] "Correlation Coefficient: 0.0122088041763853"
The box plot shows customer ratings across different frequencies of prior purchases. Ratings are consistent across all levels of prior purchases, indicating that the number of prior purchases does not significantly influence customer ratings.
data$Prior_purchases <- as.factor(data$Prior_purchases)
data$Reached.on.Time_Y.N <- as.factor(data$Reached.on.Time_Y.N)
ggplot(data, aes(x = Prior_purchases, y = Customer_rating)) +
geom_boxplot() +
labs(title = "Customer Rating by Prior Purchases", x = "Prior Purchases", y = "Customer Rating") +
theme_minimal()
The scatter plot examining the link between Customer Care Calls and Customer Ratings reveals no clear pattern. With a correlation coefficient of 0.0122, the data indicates there is no meaningful relationship between the two variables, suggesting that the number of calls to customer care does not affect how customers rate the service.
ggplot(data, aes(x = Customer_care_calls, y = Customer_rating)) +
geom_point() +
labs(title = "Scatter Plot of Customer Care Calls vs Customer Rating",
x = "Customer Care Calls",
y = "Customer Rating")
correlation_coefficient <- cor(data$Customer_care_calls, data$Customer_rating, use = "complete.obs")
print(paste("Correlation Coefficient:", correlation_coefficient))
## [1] "Correlation Coefficient: 0.0122088041763853"
The box plot comparing product costs to customer ratings shows no clear trend linking higher prices to better ratings. Costs vary widely for all ratings, suggesting that the price of a product does not consistently affect customer satisfaction.
# Box plot
ggplot(data, aes(x = as.factor(Customer_rating), y = Cost_of_the_Product)) +
geom_boxplot() +
theme_minimal() +
labs(title = "Box Plot of Cost of the Product by Customer Rating",
x = "Customer Rating",
y = "Cost of the Product")
cor_coeff <- cor(data$Cost_of_the_Product, data$Customer_rating, use = "complete.obs")
print(paste("Correlation Coefficient:", cor_coeff))
## [1] "Correlation Coefficient: 0.00926952458002357"
As the number of prior purchases increases, there is no clear indication that customers receive more discounts. In fact, the trend line suggests a slight negative correlation, with discounts marginally decreasing as prior purchases go up. This could imply that the company’s discounting policy does not favor rewarding repeat purchases with increased discounts. Instead, discounts may be influenced by other factors or promotions that are not directly related to the number of purchases a customer has previously made.
ggplot(data, aes(x = Prior_purchases, y = Discount_offered)) +
geom_point(aes(color = Prior_purchases), alpha = 0.5) +
geom_smooth(method = "lm", se = FALSE, color = "darkblue") +
scale_color_brewer(type = "seq", palette = "Reds") +
labs(title = "Relationship Between Prior Purchases and Discount Offered",
x = "Number of Prior Purchases",
y = "Discount Offered (%)") +
theme_minimal() +
theme(legend.position = "bottom")
## `geom_smooth()` using formula = 'y ~ x'
Products that were delivered on time tend to have a lower median weight than those that were delayed. While there is overlap in the weight ranges between on-time and delayed products, the heavier products are more represented in the delayed category. This could suggest that heavier products have a higher likelihood of not meeting delivery deadlines, potentially due to the logistics challenges associated with transporting heavier items.
data$Reached.on.Time_Y.N <- factor(data$Reached.on.Time_Y.N, levels = c(0, 1), labels = c("On Time", "Delayed"))
count_deliveries <- table(data$Reached.on.Time_Y.N)
print(count_deliveries)
##
## On Time Delayed
## 4436 6563
data$Reached.on.Time_Y.N <- factor(data$Reached.on.Time_Y.N, labels = c("On Time", "Delayed"))
ggplot(data, aes(x = Reached.on.Time_Y.N, y = Weight_in_gms, fill = Reached.on.Time_Y.N)) +
geom_boxplot() +
labs(title = "Box Plot of Product Weight vs Delivery Timeliness",
x = "Delivery Timeliness",
y = "Weight in Grams") +
scale_fill_brewer(palette = "Set1") +
theme_minimal()
variable <- data$numerical_cols
Q1 <- quantile(variable, 0.25)
Q3 <- quantile(variable, 0.75)
IQR <- Q3 - Q1
# Define the lower and upper bounds
lower_bound <- Q1 - 1.5 * IQR
upper_bound <- Q3 + 1.5 * IQR
# Remove outliers
data_no_outliers <- subset(data, numerical_cols >= lower_bound & numerical_cols <= upper_bound)
Split data into 80:20 ratio.
library(caret)
## Loading required package: lattice
##
## Attaching package: 'caret'
## The following object is masked from 'package:purrr':
##
## lift
library(e1071)
library(rpart)
library(class)
library(knitr)
library(pROC)
## Type 'citation("pROC")' for a citation.
##
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
##
## cov, smooth, var
data <- read.csv("clean_shipping.csv")
columns_to_drop <- c("Gender", "Mode_of_Shipment", "Warehouse_block")
data <- data[, !(names(data) %in% columns_to_drop)]
# Data Splitting
set.seed(2345)
intrain <- createDataPartition(y = data$Reached.on.Time_Y.N, p = 0.8, list = FALSE)
training <- data[intrain,]
testing <- data[-intrain,]
# Separate predictors and target
X_train <- training[, -which(names(training) == "Reached.on.Time_Y.N")]
y_train <- training$Reached.on.Time_Y.N
X_test <- testing[, -which(names(testing) == "Reached.on.Time_Y.N")]
y_test <- testing$Reached.on.Time_Y.N
preProcValues <- preProcess(X_train, method = c("center", "scale"))
X_train_scaled <- predict(preProcValues, X_train)
X_test_scaled <- predict(preProcValues, X_test)
# KNN
k <- 5
knn_pred <- knn(train = X_train_scaled, test = X_test_scaled, cl = y_train, k = k)
knn_pred_factor <- factor(knn_pred, levels = levels(factor(y_test)))
y_test_factor <- factor(y_test, levels = levels(factor(y_test)))
knn_report <- confusionMatrix(knn_pred_factor, y_test_factor)
knn_report
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 552 399
## 1 346 902
##
## Accuracy : 0.6612
## 95% CI : (0.641, 0.681)
## No Information Rate : 0.5916
## P-Value [Acc > NIR] : 1.15e-11
##
## Kappa : 0.3052
##
## Mcnemar's Test P-Value : 0.05676
##
## Sensitivity : 0.6147
## Specificity : 0.6933
## Pos Pred Value : 0.5804
## Neg Pred Value : 0.7228
## Prevalence : 0.4084
## Detection Rate : 0.2510
## Detection Prevalence : 0.4325
## Balanced Accuracy : 0.6540
##
## 'Positive' Class : 0
##
# Logistic Regression
log_model <- glm(Reached.on.Time_Y.N ~ ., data = training, family = "binomial")
log_pred <- predict(log_model, X_test_scaled, type = "response")
log_pred_class <- ifelse(log_pred > 0.5, 1, 0)
log_pred_factor <- factor(log_pred_class, levels = c(0, 1))
y_test_factor <- factor(y_test, levels = c(0, 1))
log_report <- confusionMatrix(log_pred_factor, y_test_factor)
log_report
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 0 0
## 1 898 1301
##
## Accuracy : 0.5916
## 95% CI : (0.5708, 0.6123)
## No Information Rate : 0.5916
## P-Value [Acc > NIR] : 0.5092
##
## Kappa : 0
##
## Mcnemar's Test P-Value : <2e-16
##
## Sensitivity : 0.0000
## Specificity : 1.0000
## Pos Pred Value : NaN
## Neg Pred Value : 0.5916
## Prevalence : 0.4084
## Detection Rate : 0.0000
## Detection Prevalence : 0.0000
## Balanced Accuracy : 0.5000
##
## 'Positive' Class : 0
##
#Linear Regression
lin_model <- lm(Reached.on.Time_Y.N ~ ., data = training)
lin_pred <- predict(lin_model, X_test_scaled)
lin_pred_class <- ifelse(lin_pred > 0.5, 1, 0)
lin_pred_factor <- factor(lin_pred_class, levels = levels(factor(y_test)))
y_test_factor <- factor(y_test, levels = levels(factor(y_test)))
lin_report <- confusionMatrix(lin_pred_factor, y_test_factor)
lin_report
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 0 0
## 1 898 1301
##
## Accuracy : 0.5916
## 95% CI : (0.5708, 0.6123)
## No Information Rate : 0.5916
## P-Value [Acc > NIR] : 0.5092
##
## Kappa : 0
##
## Mcnemar's Test P-Value : <2e-16
##
## Sensitivity : 0.0000
## Specificity : 1.0000
## Pos Pred Value : NaN
## Neg Pred Value : 0.5916
## Prevalence : 0.4084
## Detection Rate : 0.0000
## Detection Prevalence : 0.0000
## Balanced Accuracy : 0.5000
##
## 'Positive' Class : 0
##
# Decision Tree
tree_model <- rpart(Reached.on.Time_Y.N ~ ., data = training, method = "class")
tree_pred <- predict(tree_model, X_test_scaled, type = "class")
tree_pred_factor <- factor(tree_pred, levels = levels(factor(y_test)))
y_test_factor <- factor(y_test, levels = levels(factor(y_test)))
tree_report <- confusionMatrix(tree_pred_factor, y_test_factor)
tree_report
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 0 0
## 1 898 1301
##
## Accuracy : 0.5916
## 95% CI : (0.5708, 0.6123)
## No Information Rate : 0.5916
## P-Value [Acc > NIR] : 0.5092
##
## Kappa : 0
##
## Mcnemar's Test P-Value : <2e-16
##
## Sensitivity : 0.0000
## Specificity : 1.0000
## Pos Pred Value : NaN
## Neg Pred Value : 0.5916
## Prevalence : 0.4084
## Detection Rate : 0.0000
## Detection Prevalence : 0.0000
## Balanced Accuracy : 0.5000
##
## 'Positive' Class : 0
##
training$Reached.on.Time_Y.N <- factor(training$Reached.on.Time_Y.N, levels = c(0, 1))
testing$Reached.on.Time_Y.N <- factor(testing$Reached.on.Time_Y.N, levels = c(0, 1))
#Tuning KNN
knn_tune_grid <- expand.grid(k = 1:20)
knn_tune <- train(
Reached.on.Time_Y.N ~ .,
data = training,
method = "knn",
tuneGrid = knn_tune_grid,
preProcess = c("center", "scale"),
trControl = trainControl(method = "cv", number = 10)
)
# Display KNN results
print(knn_tune$bestTune)
## k
## 17 17
print(knn_tune$results)
## k Accuracy Kappa AccuracySD KappaSD
## 1 1 0.6451187 0.2624534 0.016799060 0.03391605
## 2 2 0.6456876 0.2654950 0.019164890 0.03890070
## 3 3 0.6546619 0.2870634 0.019109671 0.03964089
## 4 4 0.6578432 0.2927118 0.012569412 0.02444904
## 5 5 0.6631838 0.3081912 0.012709184 0.02576840
## 6 6 0.6621571 0.3064915 0.009733519 0.01999760
## 7 7 0.6610240 0.3083919 0.014447788 0.02797344
## 8 8 0.6693225 0.3249960 0.015484657 0.02847576
## 9 9 0.6663675 0.3210043 0.014029372 0.02663667
## 10 10 0.6655733 0.3200390 0.012257728 0.02267669
## 11 11 0.6703475 0.3323786 0.014100408 0.02884658
## 12 12 0.6703454 0.3331001 0.012328109 0.02502876
## 13 13 0.6668238 0.3282158 0.011133314 0.02357956
## 14 14 0.6660269 0.3262217 0.009544233 0.02032646
## 15 15 0.6640973 0.3252703 0.011051400 0.02305996
## 16 16 0.6645532 0.3257799 0.014232997 0.02731760
## 17 17 0.6708010 0.3402678 0.011620141 0.02330169
## 18 18 0.6697804 0.3387677 0.013555856 0.02760157
## 19 19 0.6677327 0.3366104 0.010150742 0.02124821
## 20 20 0.6677334 0.3368706 0.013514654 0.02699913
# Tuning Logistic Regression
log_tune_grid <- expand.grid(.alpha = 0, .lambda = seq(0.001, 0.1, length = 10))
log_tune <- train(
Reached.on.Time_Y.N ~ .,
data = training,
method = "glmnet",
tuneGrid = log_tune_grid,
preProcess = c("center", "scale"),
trControl = trainControl(method = "cv", number = 10)
)
# Display Logistic Regression results
print(log_tune$bestTune)
## alpha lambda
## 3 0 0.023
print(log_tune$results)
## alpha lambda Accuracy Kappa AccuracySD KappaSD
## 1 0 0.001 0.6491016 0.2719130 0.02253989 0.04601935
## 2 0 0.012 0.6491016 0.2719130 0.02253989 0.04601935
## 3 0 0.023 0.6492160 0.2712920 0.02337772 0.04813907
## 4 0 0.034 0.6477379 0.2659807 0.02330499 0.04871969
## 5 0 0.045 0.6455786 0.2588039 0.02285598 0.04846383
## 6 0 0.056 0.6451243 0.2557658 0.02391492 0.05092836
## 7 0 0.067 0.6462607 0.2559172 0.02354253 0.05034404
## 8 0 0.078 0.6445565 0.2502910 0.02418387 0.05244938
## 9 0 0.089 0.6436472 0.2466220 0.02486898 0.05368585
## 10 0 0.100 0.6420562 0.2411167 0.02545891 0.05505793
# Tuning Linear Regression
lin_tune_grid <- expand.grid(.alpha = 0, .lambda = seq(0.001, 0.1, length = 10))
lin_tune <- train(
Reached.on.Time_Y.N ~ .,
data = training,
method = "glmnet",
tuneGrid = lin_tune_grid,
preProcess = c("center", "scale"),
trControl = trainControl(method = "cv", number = 10)
)
# Display Logistic Linear Regression
print(lin_tune$bestTune)
## alpha lambda
## 2 0 0.012
print(lin_tune$results)
## alpha lambda Accuracy Kappa AccuracySD KappaSD
## 1 0 0.001 0.6477222 0.2686933 0.01871961 0.03823131
## 2 0 0.012 0.6477222 0.2686933 0.01871961 0.03823131
## 3 0 0.023 0.6472678 0.2670589 0.01799174 0.03703510
## 4 0 0.034 0.6468119 0.2637420 0.01897808 0.03894787
## 5 0 0.045 0.6456761 0.2590346 0.01779902 0.03651026
## 6 0 0.056 0.6463576 0.2585067 0.01917099 0.04001209
## 7 0 0.067 0.6440839 0.2512918 0.01920980 0.04022001
## 8 0 0.078 0.6429475 0.2472039 0.02053219 0.04325495
## 9 0 0.089 0.6424926 0.2444776 0.02073020 0.04371457
## 10 0 0.100 0.6418108 0.2411150 0.02038546 0.04292044
# Tuning Decision Tree
tree_tune_grid <- expand.grid(.cp = seq(0.001, 0.1, length = 10))
tree_tune <- train(
Reached.on.Time_Y.N ~ .,
data = training,
method = "rpart",
tuneGrid = tree_tune_grid,
trControl = trainControl(method = "cv", number = 10)
)
# Display Decision Tree results
print(tree_tune$bestTune)
## cp
## 10 0.1
print(tree_tune$results)
## cp Accuracy Kappa AccuracySD KappaSD
## 1 0.001 0.6723848 0.3609902 0.012653459 0.0336200
## 2 0.012 0.6861370 0.4212768 0.008517751 0.0138505
## 3 0.023 0.6861370 0.4212768 0.008517751 0.0138505
## 4 0.034 0.6861370 0.4212768 0.008517751 0.0138505
## 5 0.045 0.6861370 0.4212768 0.008517751 0.0138505
## 6 0.056 0.6861370 0.4212768 0.008517751 0.0138505
## 7 0.067 0.6861370 0.4212768 0.008517751 0.0138505
## 8 0.078 0.6861370 0.4212768 0.008517751 0.0138505
## 9 0.089 0.6861370 0.4212768 0.008517751 0.0138505
## 10 0.100 0.6861370 0.4212768 0.008517751 0.0138505
# Gather best tuning results
results <- data.frame(
Model = c("KNN", "Logistic Regression", "Decision Tree", "Linear Regression"),
Best_Parameters = c(
toString(knn_tune$bestTune),
toString(log_tune$bestTune),
toString(tree_tune$bestTune),
toString(lin_tune$bestTune)
),
Accuracy = c(
max(knn_tune$results$Accuracy),
max(log_tune$results$Accuracy),
max(tree_tune$results$Accuracy),
max(lin_tune$results$Accuracy)
)
)
# Display the table
kable(results, caption = "Best Tuning Results for Models")
| Model | Best_Parameters | Accuracy |
|---|---|---|
| KNN | 17 | 0.6708010 |
| Logistic Regression | 0, 0.023 | 0.6492160 |
| Decision Tree | 0.1 | 0.6861370 |
| Linear Regression | 0, 0.012 | 0.6477222 |
Our project focused on optimizing international e-commerce shipping strategies during the COVID-19 pandemic. After we employed various machine learning models, we chose Decision Tree model for its high performance of 69% accuracy score. Its simplicity and ability to reveal key factors for shipping efficiency and customer satisfaction make it valuable for strategic planning. These insights are essential for improving service, meeting customer needs, and enhancing warehouse efficiency in the competitive e-commerce market.