LOAD LIBRARIES, DATA, AND WINNING ASSIGNMENT 3 MODEL

install.packages(c("kernelshap", "shapviz")) #no fastshap for my version of R
library(C50)
library(gmodels)
library(kernelshap)
library(shapviz)
library(ggplot2)


# Load dataset as per Assignment 3 
bank <- read.csv("bank-additional-full.csv", sep = ";", stringsAsFactors = TRUE)

# Drop 'duration' to prevent data leakage
bank$duration <- NULL

# 90/10 train/test split from Assignment 3
set.seed(12345)
train_sample <- sample(41188, 37069)
bank_train <- bank[train_sample, ]
bank_test  <- bank[-train_sample, ]

# Winning Experiment 3 model (C5.0 with 4x cost matrix + winnowing)
matrix_dim <- list(c("no", "yes"), c("no", "yes"))
names(matrix_dim) <- c("predicted", "actual")
error_cost_4x <- matrix(c(0, 1, 4, 0), nrow = 2, dimnames = matrix_dim)

m3_winnow <- C5.0(bank_train[-20], bank_train$y,
                  costs = error_cost_4x,
                  control = C5.0Control(winnow = TRUE))

# Check of which features survived winnowing
C5imp(m3_winnow)
##                Overall
## pdays           100.00
## nr.employed     100.00
## month            87.65
## age              87.48
## previous         10.97
## euribor3m         6.05
## job               5.30
## education         4.90
## emp.var.rate      0.66
## cons.conf.idx     0.30
## marital           0.00
## default           0.00
## housing           0.00
## loan              0.00
## contact           0.00
## day_of_week       0.00
## campaign          0.00
## poutcome          0.00
## cons.price.idx    0.00

CALCULATE SHAP VALUES (KERNELSHAP EXPLAINER)

# Extract only features actually used by m3_winnow (dropped features have 0 SHAP)
imp <- C5imp(m3_winnow)
active_vars <- rownames(imp)[imp$Overall > 0]
print(active_vars)
##  [1] "pdays"         "nr.employed"   "month"         "age"          
##  [5] "previous"      "euribor3m"     "job"           "education"    
##  [9] "emp.var.rate"  "cons.conf.idx"
# Reproducible samples sized for fast C5.0 prediction
set.seed(12345)
bg_ids   <- sample(nrow(bank_train), 50)
test_ids <- sample(nrow(bank_test), 100)

X_bg   <- bank_train[bg_ids, -20]
X_test <- bank_test[test_ids, -20]

# Prediction wrapper (1 = predicted 'yes', 0 = predicted 'no')
pfun <- function(object, newdata) {
  as.numeric(predict(object, newdata = newdata) == "yes")
}

# Compute Kernel SHAP values (should finish in ~15-30 seconds)
set.seed(12345)
ks <- kernelshap(
  object        = m3_winnow,
  X             = X_test,
  bg_X          = X_bg,
  pred_fun      = pfun,
  feature_names = active_vars,
  hybrid_degree = 1,
  max_iter      = 5
)
##   |                                                                              |                                                                      |   0%  |                                                                              |=                                                                     |   1%  |                                                                              |=                                                                     |   2%  |                                                                              |==                                                                    |   3%  |                                                                              |===                                                                   |   4%  |                                                                              |====                                                                  |   5%  |                                                                              |====                                                                  |   6%  |                                                                              |=====                                                                 |   7%  |                                                                              |======                                                                |   8%  |                                                                              |======                                                                |   9%  |                                                                              |=======                                                               |  10%  |                                                                              |========                                                              |  11%  |                                                                              |========                                                              |  12%  |                                                                              |=========                                                             |  13%  |                                                                              |==========                                                            |  14%  |                                                                              |==========                                                            |  15%  |                                                                              |===========                                                           |  16%  |                                                                              |============                                                          |  17%  |                                                                              |=============                                                         |  18%  |                                                                              |=============                                                         |  19%  |                                                                              |==============                                                        |  20%  |                                                                              |===============                                                       |  21%  |                                                                              |===============                                                       |  22%  |                                                                              |================                                                      |  23%  |                                                                              |=================                                                     |  24%  |                                                                              |==================                                                    |  25%  |                                                                              |==================                                                    |  26%  |                                                                              |===================                                                   |  27%  |                                                                              |====================                                                  |  28%  |                                                                              |====================                                                  |  29%  |                                                                              |=====================                                                 |  30%  |                                                                              |======================                                                |  31%  |                                                                              |======================                                                |  32%  |                                                                              |=======================                                               |  33%  |                                                                              |========================                                              |  34%  |                                                                              |========================                                              |  35%  |                                                                              |=========================                                             |  36%  |                                                                              |==========================                                            |  37%  |                                                                              |===========================                                           |  38%  |                                                                              |===========================                                           |  39%  |                                                                              |============================                                          |  40%  |                                                                              |=============================                                         |  41%  |                                                                              |=============================                                         |  42%  |                                                                              |==============================                                        |  43%  |                                                                              |===============================                                       |  44%  |                                                                              |================================                                      |  45%  |                                                                              |================================                                      |  46%  |                                                                              |=================================                                     |  47%  |                                                                              |==================================                                    |  48%  |                                                                              |==================================                                    |  49%  |                                                                              |===================================                                   |  50%  |                                                                              |====================================                                  |  51%  |                                                                              |====================================                                  |  52%  |                                                                              |=====================================                                 |  53%  |                                                                              |======================================                                |  54%  |                                                                              |======================================                                |  55%  |                                                                              |=======================================                               |  56%  |                                                                              |========================================                              |  57%  |                                                                              |=========================================                             |  58%  |                                                                              |=========================================                             |  59%  |                                                                              |==========================================                            |  60%  |                                                                              |===========================================                           |  61%  |                                                                              |===========================================                           |  62%  |                                                                              |============================================                          |  63%  |                                                                              |=============================================                         |  64%  |                                                                              |==============================================                        |  65%  |                                                                              |==============================================                        |  66%  |                                                                              |===============================================                       |  67%  |                                                                              |================================================                      |  68%  |                                                                              |================================================                      |  69%  |                                                                              |=================================================                     |  70%  |                                                                              |==================================================                    |  71%  |                                                                              |==================================================                    |  72%  |                                                                              |===================================================                   |  73%  |                                                                              |====================================================                  |  74%  |                                                                              |====================================================                  |  75%  |                                                                              |=====================================================                 |  76%  |                                                                              |======================================================                |  77%  |                                                                              |=======================================================               |  78%  |                                                                              |=======================================================               |  79%  |                                                                              |========================================================              |  80%  |                                                                              |=========================================================             |  81%  |                                                                              |=========================================================             |  82%  |                                                                              |==========================================================            |  83%  |                                                                              |===========================================================           |  84%  |                                                                              |============================================================          |  85%  |                                                                              |============================================================          |  86%  |                                                                              |=============================================================         |  87%  |                                                                              |==============================================================        |  88%  |                                                                              |==============================================================        |  89%  |                                                                              |===============================================================       |  90%  |                                                                              |================================================================      |  91%  |                                                                              |================================================================      |  92%  |                                                                              |=================================================================     |  93%  |                                                                              |==================================================================    |  94%  |                                                                              |==================================================================    |  95%  |                                                                              |===================================================================   |  96%  |                                                                              |====================================================================  |  97%  |                                                                              |===================================================================== |  98%  |                                                                              |===================================================================== |  99%  |                                                                              |======================================================================| 100%
shp <- shapviz(ks)

SHAP GLOBAL EXPLAINABILITY

# Print ranked mean absolute SHAP values to verify top 3 
global_imp <- sort(colMeans(abs(ks$S)), decreasing = TRUE)
print(round(global_imp, 4))
##   nr.employed         month         pdays  emp.var.rate     euribor3m 
##        0.1580        0.0528        0.0370        0.0122        0.0119 
##     education           age      previous           job cons.conf.idx 
##        0.0089        0.0073        0.0063        0.0036        0.0023
cat("\nTop 3 Global Features:\n")
## 
## Top 3 Global Features:
print(head(round(global_imp, 4), 3))
## nr.employed       month       pdays 
##      0.1580      0.0528      0.0370
# SHAP summary bar plot (average magnitude of impact per feature)
sv_importance(shp, kind = "bar", fill = "steelblue") +
  ggtitle("SHAP Global Feature Importance (m3_winnow)") +
  theme_minimal()

# Beeswarm shows direction (higher vs. lower impact)
sv_importance(shp, kind = "beeswarm") +
  ggtitle("SHAP Summary Beeswarm Plot (Direction of Feature Impact)") +
  theme_minimal()

SHAP LOCAL EXPLANATION (SINGLE TEST)

# Select one from  test sample (first client predicted to subscribe ('yes'))
sample_preds <- predict(m3_winnow, X_test)
local_id <- which(sample_preds == "yes")[1]

# Print the selected client's actual data, true label, and model prediction
cat("\nSelected Local Client (Row in X_test):", local_id, "\n")
## 
## Selected Local Client (Row in X_test): 3
print(bank_test[test_ids[local_id], ])
##       age     job marital education default housing loan  contact month
## 30354  47 unknown married   unknown      no      no   no cellular   apr
##       day_of_week campaign pdays previous    poutcome emp.var.rate
## 30354         thu        1   999        0 nonexistent         -1.8
##       cons.price.idx cons.conf.idx euribor3m nr.employed  y
## 30354         93.075         -47.1     1.365      5099.1 no
cat("Predicted Class:", as.character(sample_preds[local_id]), "\n")
## Predicted Class: yes
cat("Baseline Positive Rate:", round(ks$baseline, 4), "\n\n")
## Baseline Positive Rate: 0.1
# Print individual feature SHAP values sorted from highest positive to lowest negative
local_shap <- sort(ks$S[local_id, ], decreasing = TRUE)
print(round(local_shap, 4))
##         month           job     euribor3m     education      previous 
##        0.7695        0.0594        0.0554        0.0500        0.0178 
## cons.conf.idx  emp.var.rate           age         pdays   nr.employed 
##        0.0077        0.0037       -0.0150       -0.0195       -0.0290
# Local SHAP waterfall plot (shows pushes higher and lower from baseline)
sv_waterfall(shp, row_id = local_id) +
  ggtitle(paste("SHAP Local Explanation - Test Sample Client #", local_id))

ETHICS

# Check how much total global SHAP impact comes from socioeconomic/demographic 
sensitive_vars <- c("age", "job", "marital", "education", "housing", "loan", "default")
sens_share <- sum(global_imp[sensitive_vars]) / sum(global_imp) * 100
cat("\nShare of Total SHAP Importance from Socioeconomic/Demographic Features:",
    round(sens_share, 1), "%\n\n")
## 
## Share of Total SHAP Importance from Socioeconomic/Demographic Features: NA %
# Check predicted subscription rates across job and education on the full test set
full_test_preds <- predict(m3_winnow, bank_test)
cat("Predicted 'yes' Rate by Job Category:\n")
## Predicted 'yes' Rate by Job Category:
print(round(prop.table(table(bank_test$job, full_test_preds), margin = 1)[, "yes"] * 100, 1))
##        admin.   blue-collar  entrepreneur     housemaid    management 
##          19.8           4.2          10.6          17.8          12.9 
##       retired self-employed      services       student    technician 
##          45.5          22.5           6.7          52.8          14.8 
##    unemployed       unknown 
##          25.0          19.5
cat("\nPredicted 'yes' Rate by Education Level:\n")
## 
## Predicted 'yes' Rate by Education Level:
print(round(prop.table(table(bank_test$education, full_test_preds), margin = 1)[, "yes"] * 100, 1))
##            basic.4y            basic.6y            basic.9y         high.school 
##                15.2                 7.7                 6.8                12.2 
##          illiterate professional.course   university.degree             unknown 
##                 0.0                14.8                23.3                19.3