library(caret)
library(tidyverse)
library(pROC)
library(xgboost)
library(corrplot)
library(gridExtra)

path <- 'C:/dataset/'
train <- read.csv(paste0(path, 'train.csv'))[,-1]# remove id
test <- read.csv(paste0(path, 'test.csv'))[,-1]

# Use all train data
train_df <- train

# Inspect dataset
str(train_df)
## 'data.frame':    165034 obs. of  13 variables:
##  $ CustomerId     : int  15674932 15749177 15694510 15741417 15766172 15771669 15692819 15669611 15691707 15591721 ...
##  $ Surname        : chr  "Okwudilichukwu" "Okwudiliolisa" "Hsueh" "Kao" ...
##  $ CreditScore    : int  668 627 678 581 716 588 593 678 676 583 ...
##  $ Geography      : chr  "France" "France" "France" "France" ...
##  $ Gender         : chr  "Male" "Male" "Male" "Male" ...
##  $ Age            : num  33 33 40 34 33 36 30 37 43 40 ...
##  $ Tenure         : int  3 1 10 2 5 4 8 1 4 4 ...
##  $ Balance        : num  0 0 0 148883 0 ...
##  $ NumOfProducts  : int  2 2 2 1 2 1 1 1 2 1 ...
##  $ HasCrCard      : num  1 1 1 1 1 1 1 1 1 1 ...
##  $ IsActiveMember : num  0 1 0 1 1 0 0 0 0 1 ...
##  $ EstimatedSalary: num  181450 49504 184867 84561 15069 ...
##  $ Exited         : int  0 0 0 0 0 1 0 0 0 0 ...
# Check null values
null_col <- sapply(train_df, function(col) sum(is.na(col)))
null_col <- data.frame(Variable = names(null_col), Null_Num = null_col)
print(null_col)
##                        Variable Null_Num
## CustomerId           CustomerId        0
## Surname                 Surname        0
## CreditScore         CreditScore        0
## Geography             Geography        0
## Gender                   Gender        0
## Age                         Age        0
## Tenure                   Tenure        0
## Balance                 Balance        0
## NumOfProducts     NumOfProducts        0
## HasCrCard             HasCrCard        0
## IsActiveMember   IsActiveMember        0
## EstimatedSalary EstimatedSalary        0
## Exited                   Exited        0
# Check for outliers
summary(train_df)
##    CustomerId         Surname           CreditScore     Geography        
##  Min.   :15565701   Length:165034      Min.   :350.0   Length:165034     
##  1st Qu.:15633141   Class :character   1st Qu.:597.0   Class :character  
##  Median :15690169   Mode  :character   Median :659.0   Mode  :character  
##  Mean   :15692005                      Mean   :656.5                     
##  3rd Qu.:15756824                      3rd Qu.:710.0                     
##  Max.   :15815690                      Max.   :850.0                     
##     Gender               Age            Tenure         Balance      
##  Length:165034      Min.   :18.00   Min.   : 0.00   Min.   :     0  
##  Class :character   1st Qu.:32.00   1st Qu.: 3.00   1st Qu.:     0  
##  Mode  :character   Median :37.00   Median : 5.00   Median :     0  
##                     Mean   :38.13   Mean   : 5.02   Mean   : 55478  
##                     3rd Qu.:42.00   3rd Qu.: 7.00   3rd Qu.:119940  
##                     Max.   :92.00   Max.   :10.00   Max.   :250898  
##  NumOfProducts     HasCrCard     IsActiveMember   EstimatedSalary    
##  Min.   :1.000   Min.   :0.000   Min.   :0.0000   Min.   :    11.58  
##  1st Qu.:1.000   1st Qu.:1.000   1st Qu.:0.0000   1st Qu.: 74637.57  
##  Median :2.000   Median :1.000   Median :0.0000   Median :117948.00  
##  Mean   :1.554   Mean   :0.754   Mean   :0.4978   Mean   :112574.82  
##  3rd Qu.:2.000   3rd Qu.:1.000   3rd Qu.:1.0000   3rd Qu.:155152.47  
##  Max.   :4.000   Max.   :1.000   Max.   :1.0000   Max.   :199992.48  
##      Exited      
##  Min.   :0.0000  
##  1st Qu.:0.0000  
##  Median :0.0000  
##  Mean   :0.2116  
##  3rd Qu.:0.0000  
##  Max.   :1.0000
# Inspect dataset head
print(head(train_df, 20))
##    CustomerId        Surname CreditScore Geography Gender Age Tenure   Balance
## 1    15674932 Okwudilichukwu         668    France   Male  33      3      0.00
## 2    15749177  Okwudiliolisa         627    France   Male  33      1      0.00
## 3    15694510          Hsueh         678    France   Male  40     10      0.00
## 4    15741417            Kao         581    France   Male  34      2 148882.54
## 5    15766172      Chiemenam         716     Spain   Male  33      5      0.00
## 6    15771669       Genovese         588   Germany   Male  36      4 131778.58
## 7    15692819         Ch'ang         593    France Female  30      8 144772.69
## 8    15669611    Chukwuebuka         678     Spain   Male  37      1 138476.41
## 9    15691707          Manna         676    France   Male  43      4      0.00
## 10   15591721       Cattaneo         583   Germany   Male  40      4  81274.33
## 11   15635097         Fokine         599   Germany Female  27      6 161801.47
## 12   15674671           Chiu         687   Germany   Male  40      3  90432.92
## 13   15717962          Rossi         759     Spain   Male  71      9      0.00
## 14   15793029          Ts'ai         681    France   Male  47      5      0.00
## 15   15643294    Chukwuemeka         703    France Female  33      7 190566.65
## 16   15690958           Tung         549    France Female  25      5      0.00
## 17   15566543      Macdonald         602    France   Male  36      7      0.00
## 18   15679804       Esquivel         636    France   Male  36      4 117559.05
## 19   15671358     Hargreaves         645   Germany Female  55      8 120105.43
## 20   15650670          Ts'ui         559    France   Male  61      1 153711.26
##    NumOfProducts HasCrCard IsActiveMember EstimatedSalary Exited
## 1              2         1              0       181449.97      0
## 2              2         1              1        49503.50      0
## 3              2         1              0       184866.69      0
## 4              1         1              1        84560.88      0
## 5              2         1              1        15068.83      0
## 6              1         1              0       136024.31      1
## 7              1         1              0        29792.11      0
## 8              1         1              0       106851.60      0
## 9              2         1              0       142917.13      0
## 10             1         1              1       170843.07      0
## 11             2         1              0       109184.24      0
## 12             1         1              0         1676.92      0
## 13             1         1              1        93081.87      0
## 14             1         1              1        72945.68      0
## 15             1         1              1        79997.14      0
## 16             2         1              0       162260.93      0
## 17             2         0              1       135082.47      0
## 18             2         1              0       111573.30      0
## 19             1         1              0       125083.29      1
## 20             1         0              1       180890.40      1
# Check for duplication
dup_count <- sum(duplicated(train_df))
cat("Number of duplicate rows:", dup_count, "\n")
## Number of duplicate rows: 0
# Check uniqueness
surname_unique <- length(unique(train_df$Surname))
cat("Unique surnames:", surname_unique, "\n")
## Unique surnames: 2797
customerid_unique <- length(unique(train_df$CustomerId))
cat("Unique CustomerIds:", customerid_unique, "\n")
## Unique CustomerIds: 23221
cat_list <- c("Geography", "Gender", "NumOfProducts", "HasCrCard", "IsActiveMember", "Exited")
exit_table <- train_df[train_df$Exited == 1, ]

# Helper function to calculate percentages for Exited categories
add_percentage_exited <- function(df, x_var) {
  total_count <- nrow(df)
  df %>%
    group_by_at(vars(x_var, "Exited")) %>%
    summarise(Count = n(), .groups = "drop") %>%
    mutate(Percentage = round(Count / total_count * 100, 1)) 
}

# Overall Exited distribution with percentages
p1 <- ggplot(train_df, aes(x = as.factor(Exited), fill = as.factor(Exited))) +
  geom_bar() +
  geom_text(stat = "count", aes(label = paste0(round(..count.. / sum(..count..) * 100, 1), "%")),
            position = position_stack(vjust = 0.5), size = 3.5) +
  scale_fill_manual(values = c("0" = "lightblue", "1" = "red"), labels = c("Exited = 0", "Exited = 1")) +
  labs(title = "Distribution of Exited", x = "Exited", y = "Count", fill = "Exited") +
  theme_minimal() +
  theme(legend.position = "none")  # Remove legend from individual plots

# Plot categorical variable distributions with percentages based on Exited
cat_list <- c("Geography", "Gender", "NumOfProducts", "HasCrCard", "IsActiveMember")
plots <- list()

for (cat in cat_list) {
  # Calculate percentage for each category grouped by Exited
  percentage_df <- add_percentage_exited(train_df, cat)
  
  # Ensure `Exited` is a factor
  percentage_df$Exited <- as.factor(percentage_df$Exited)
  
  # Create the plot
  p <- ggplot(percentage_df, aes_string(x = cat, y = "Count", fill = "Exited")) +
    geom_bar(stat = "identity", position = "stack") +  
    geom_text(aes(label = paste0(Percentage, "%")), position = position_stack(vjust = 0.5), size = 3.5) +
    scale_fill_manual(values = c("0" = "lightblue", "1" = "red"), labels = c("Exited = 0", "Exited = 1")) +
    labs(title = paste("Distribution of", cat), x = cat, y = "Count", fill = "Exited") +
    theme_minimal() +
    theme(legend.position = "none")  # Remove legend from individual plots
  plots[[cat]] <- p
}

# Create a shared legend
shared_legend <- ggplot(train_df, aes(x = Gender, fill = as.factor(Exited))) +
  geom_bar(position = "stack", stat = "count") +
  scale_fill_manual(values = c("0" = "lightblue", "1" = "red"), labels = c("Exited = 0", "Exited = 1")) +
  theme_minimal() +
  theme(legend.position = "bottom") +
  labs(fill = "Exited")

# Extract the shared legend
legend <- cowplot::get_legend(shared_legend)

# Arrange plots with shared legend
gridExtra::grid.arrange(
  do.call(gridExtra::arrangeGrob, c(list(p1), plots, ncol = 3, nrow = 2)),
  gridExtra::arrangeGrob(legend, ncol = 1),
  heights = c(10, 1)
)

# Numerical columns to plot
cumu_col <- c("CreditScore", "Age", "Balance", "EstimatedSalary")

# Store plots in a list
plots <- list()

for (col in cumu_col) {
  # Histogram grouped by Exited with count on the y-axis
  p_hist <- ggplot(train_df, aes_string(x = col, fill = "factor(Exited)")) +
    geom_histogram(bins = 30, alpha = 0.5, position = "identity", color = 'black') +
    scale_fill_manual(values = c("lightblue", "red"), labels = c("Exited = 0", "Exited = 1")) +
    labs(
      title = paste("Cumulative Distribution of", col),
      x = col,
      y = "Count",
      fill = "Exited"
    ) +
    theme_minimal() +
    theme(legend.position = "none")  # Remove legend for individual plots
  
  # Horizontal boxplot, grouped by Exited
  p_box <- ggplot(train_df, aes_string(x = col, y = "factor(Exited)", fill = "factor(Exited)")) +
    geom_boxplot() +
    #  coord_flip() +  # Flip the boxplot to horizontal
    scale_fill_manual(values = c("lightblue", "red"), labels = c("Exited = 0", "Exited = 1")) +
    labs(
      title = paste("Boxplot of", col),
      x = col,
      y = "Exited",
      fill = "Exited"
    ) +
    theme_minimal() +
    theme(legend.position = "none")  # Remove legend for individual plots
  
  # Add plots to the list
  plots[[paste0(col, "_hist")]] <- p_hist
  plots[[paste0(col, "_box")]] <- p_box
}

# Create a shared legend
shared_legend <- ggplot(train_df, aes(x = Age, fill = factor(Exited))) +
  geom_histogram(alpha = 0.5) +
  scale_fill_manual(values = c("lightblue", "red"), labels = c("Exited = 0", "Exited = 1")) +
  theme_minimal() +
  theme(legend.position = "bottom") +
  labs(fill = "Exited") +
  guides(fill = guide_legend(title.position = "top"))

# Extract legend
legend <- cowplot::get_legend(shared_legend)

# Arrange plots with shared legend
gridExtra::grid.arrange(
  do.call(gridExtra::arrangeGrob, c(plots, ncol = 2, nrow = 4)),
  gridExtra::arrangeGrob(legend, ncol = 1),
  heights = c(10, 1)
)

# Calculate percentages for Geography and Gender
geo_gender <- train_df %>%
  group_by(Geography, Gender) %>%
  summarise(
    TotalNum = n(),
    ExitedNum = sum(Exited),
    TotalPercentage = round(n() / nrow(train_df) * 100, 1),  
    ExitedPercentage = round(sum(Exited) / nrow(train_df) * 100, 1) 
  ) %>%
  ungroup()

geo_gender$Geography_Gender <- paste(geo_gender$Geography, geo_gender$Gender, sep = "_")

# Create the plot
p_geo_gender <- ggplot(geo_gender, aes(x = Geography_Gender, y = TotalNum)) +
  geom_bar(stat = "identity", fill = "lightblue") +
  geom_bar(aes(y = ExitedNum), stat = "identity", fill = "red", alpha = 0.8) +
  geom_text(aes(label = paste0(TotalPercentage, "%"), y = TotalNum + 50), color = "black", size = 3.5) +
  geom_text(aes(label = paste0(ExitedPercentage, "%"), y = ExitedNum + 50), color = "black", size = 3.5) + 
  labs(
    title = "Distribution of Exited by Geography and Gender",
    x = "Geography_Gender",
    y = "Count"
  ) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# Print the plot
print(p_geo_gender)

# Correlation heatmap
library(corrplot)

# Convert categorical variables to numeric
train_encoded <- train_df
cat_cols <- names(Filter(is.character, train_encoded))
for (col in cat_cols) {
  train_encoded[[col]] <- as.numeric(factor(train_encoded[[col]]))
}

# Plot correlation heatmap
cor_matrix <- cor(train_encoded, use = "complete.obs")
corrplot(cor_matrix, method = "color", type = "full",tl.col = 'black', diag = T, addCoef.col = "black",
         tl.cex = 0.7, number.cex = 0.4,outline="gray",
         cl.cex = 0.6, pch.col = 'white')

# Split X and Y
X <- train_df %>% select(-Exited)
Y <- train_df$Exited

# Columns to be scaled
cumu_col <- c("CreditScore", "Age", "Balance", "EstimatedSalary")

# Apply standard scaling to numerical columns
preProcValues <- preProcess(X[, cumu_col], method = c("center", "scale"))
X[, cumu_col] <- predict(preProcValues, X[, cumu_col])

# Generate dummy variables for categorical columns
X <- X %>%
  mutate(Geography_France = as.integer(Geography == "France"),
         Geography_Germany = as.integer(Geography == "Germany"),
         Gender_Male = as.integer(Gender == "Male")) %>%
  select(-Geography, -Gender)

# Drop unnecessary columns
X <- X %>% select(-CustomerId, -Surname)

# Ensure alignment between X and Y to avoid losing data
X <- X[complete.cases(X), ]
Y <- Y[complete.cases(Y)]

# Check the shapes after alignment
cat("Shape of X after alignment:", dim(X), "\n")
## Shape of X after alignment: 165034 11
cat("Shape of Y after alignment:", length(Y), "\n")
## Shape of Y after alignment: 165034
# Split training and testing data
set.seed(123)
trainIndex <- createDataPartition(Y, p = 0.8, list = FALSE)
X_train <- X[trainIndex, ]
X_test <- X[-trainIndex, ]
y_train <- Y[trainIndex]
y_test <- Y[-trainIndex]
#Logistic_Regression
Logic_Regression <- function(X_train, y_train, X_test, y_test, description) {
  # Train the model
  model <- glm(y_train ~ ., data = data.frame(X_train, y_train), family = binomial(link = "logit"))
  
  # Make predictions
  y_prob <- predict(model, newdata = X_test, type = "response")
  y_pred <- ifelse(y_prob > 0.5, 1, 0)
  
  # Evaluation
  cat(description, "\n")
  conf_matrix <- confusionMatrix(as.factor(y_pred), as.factor(y_test), positive = "1")
  print(conf_matrix)
  
  # Draw Confusion Matrix
  conf_table <- as.data.frame(conf_matrix$table)
  colnames(conf_table) <- c("Prediction", "Reference", "Count")
  
  conf_matrix_plot <<- ggplot(conf_table, aes(x = Prediction, y = Reference)) +
    geom_tile(aes(fill = Count), color = "white") +
    scale_fill_gradient(low = "white", high = "lightblue") +
    geom_text(aes(label = Count), size = 6) +
    labs(
      title = "Confusion Matrix",
      x = "Predicted Label",
      y = "True Label"
    ) +
    theme_minimal() +
    theme(axis.text = element_text(size = 12), axis.title = element_text(size = 14))
  # ROC curve
  roc_obj <- roc(y_test, y_prob)
  auc_value <- auc(roc_obj)
  
  # Draw ROC curve
  plot.roc(roc_obj, main = "Logistic regression ROC Curve", col = "darkorange", lwd = 2,legacy.axes = TRUE)
  text(x = 0.6, y = 0.2, labels = sprintf("AUC = %.2f", auc_value), col = "black", cex = 1.2)
  
  cat("AUC:", auc_value, "\n")
  
  # Logistic regression equation
  coefficients <- summary(model)$coefficients
  intercept <- coefficients[1, 1]
  cat("logit(Exited) = ", sep = "")
  for (i in 2:nrow(coefficients)) {
    coef_value <- coefficients[i, 1]
    variable_name <- rownames(coefficients)[i]
    cat(sprintf("%+.2f*(%s) ", coef_value, variable_name))
  }
  cat(sprintf("%+.2f\n", intercept))
}

Logic_Regression(X_train, y_train, X_test, y_test, "Logistic Regression with initial data")
## Logistic Regression with initial data 
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction     0     1
##          0 24887  4339
##          1  1081  2699
##                                           
##                Accuracy : 0.8358          
##                  95% CI : (0.8317, 0.8398)
##     No Information Rate : 0.7868          
##     P-Value [Acc > NIR] : < 2.2e-16       
##                                           
##                   Kappa : 0.4113          
##                                           
##  Mcnemar's Test P-Value : < 2.2e-16       
##                                           
##             Sensitivity : 0.38349         
##             Specificity : 0.95837         
##          Pos Pred Value : 0.71402         
##          Neg Pred Value : 0.85154         
##              Prevalence : 0.21323         
##          Detection Rate : 0.08177         
##    Detection Prevalence : 0.11452         
##       Balanced Accuracy : 0.67093         
##                                           
##        'Positive' Class : 1               
## 

## AUC: 0.8235142 
## logit(Exited) = -0.07*(CreditScore) +0.83*(Age) -0.02*(Tenure) -0.12*(Balance) -0.89*(NumOfProducts) -0.17*(HasCrCard) -1.28*(IsActiveMember) +0.05*(EstimatedSalary) -0.01*(Geography_France) +1.13*(Geography_Germany) -0.66*(Gender_Male) +0.62
print(conf_matrix_plot)

#xgboost_model

xgboost_model <- function(X_train, y_train, X_test, y_test, description) {
  # Set seed for reproducibility
  set.seed(42)
  
  # Convert data to xgboost matrix format
  dtrain <- xgb.DMatrix(data = as.matrix(X_train), label = y_train)
  dtest <- xgb.DMatrix(data = as.matrix(X_test), label = y_test)
  
  # Set parameters
  params <- list(
    objective = "binary:logistic",
    eval_metric = "logloss",
    eta = 0.1,
    max_depth = 3,
    subsample = 0.8,
    colsample_bytree = 0.8
  )
  num_rounds <- 100
  
  # Train the model
  model <- xgb.train(
    params = params,
    data = dtrain,
    nrounds = num_rounds
  )
  
  # Make predictions
  y_prob <- predict(model, newdata = dtest)
  y_pred <- ifelse(y_prob > 0.5, 1, 0)
  
  # Evaluation
  cat(description, "\n")
  confusion <- confusionMatrix(as.factor(y_pred), as.factor(y_test), positive = "1")
  print(confusion)
  
  # ROC curve
  roc_obj <- roc(y_test, y_prob)
  auc_value <- auc(roc_obj)
  
  # Draw ROC curve
  plot.roc(roc_obj, main = "ROC Curve for XGBoost", col = "red", lwd = 2,legacy.axes = TRUE)
  text(x = 0.2, y = 0.2, labels = sprintf("AUC = %.2f", auc_value), col = "black", cex = 1.2)
  
  # Draw Confusion Matrix
  conf_table <- as.data.frame(confusion$table)
  colnames(conf_table) <- c("Prediction", "Reference", "Count")
  
  conf_matrix_plot <<- ggplot(conf_table, aes(x = Prediction, y = Reference)) +
    geom_tile(aes(fill = Count), color = "white") +
    scale_fill_gradient(low = "white", high = "lightblue") +
    geom_text(aes(label = Count), size = 6) +
    labs(
      title = "Confusion Matrix",
      x = "Predicted Label",
      y = "True Label"
    ) +
    theme_minimal() +
    theme(axis.text = element_text(size = 12), axis.title = element_text(size = 14))
}

# Call the xgboost_model function
xgboost_model(X_train, y_train, X_test, y_test, "XGBoost with initial data")
## XGBoost with initial data 
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction     0     1
##          0 24868  3218
##          1  1100  3820
##                                           
##                Accuracy : 0.8692          
##                  95% CI : (0.8655, 0.8728)
##     No Information Rate : 0.7868          
##     P-Value [Acc > NIR] : < 2.2e-16       
##                                           
##                   Kappa : 0.5621          
##                                           
##  Mcnemar's Test P-Value : < 2.2e-16       
##                                           
##             Sensitivity : 0.5428          
##             Specificity : 0.9576          
##          Pos Pred Value : 0.7764          
##          Neg Pred Value : 0.8854          
##              Prevalence : 0.2132          
##          Detection Rate : 0.1157          
##    Detection Prevalence : 0.1491          
##       Balanced Accuracy : 0.7502          
##                                           
##        'Positive' Class : 1               
## 

conf_matrix_plot