File size: 9,983 Bytes
41592fb
 
 
8302f40
41592fb
8302f40
41592fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bda1fa
41592fb
 
 
 
 
 
 
 
6bda1fa
41592fb
 
 
 
 
 
 
 
6bda1fa
41592fb
 
 
 
 
 
 
 
6bda1fa
41592fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bda1fa
41592fb
 
 
 
 
 
 
 
6bda1fa
41592fb
 
 
 
 
 
 
 
6bda1fa
41592fb
 
 
 
 
 
 
 
6bda1fa
41592fb
 
 
b98d704
 
 
 
 
 
 
41592fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2815870
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
suppressPackageStartupMessages(library(dplyr))
suppressPackageStartupMessages(library(fastshap)) # for fast (approximate) Shapley values
suppressPackageStartupMessages(library(caret))
#suppressPackageStartupMessages(library(doMC))

#registerDoMC(cores = 10)


p_function_G <-
  function(object, newdata)
    caret::predict.train(object, newdata = newdata, type = "prob")[, "G"]
p_function_GM <-
  function(object, newdata)
    caret::predict.train(object, newdata = newdata, type = "prob")[, "GM"]
p_function_R <-
  function(object, newdata)
    caret::predict.train(object, newdata = newdata, type = "prob")[, "R"]
p_function_W <-
  function(object, newdata)
    caret::predict.train(object, newdata = newdata, type = "prob")[, "W"]

# DEPRECATED
calculate_shap_deprecated <- function(dataset,model,nsim=10) {
#  library(doParallel)
#  registerDoParallel(8)
  
  trainset <- dataset %>%  na.omit() %>%
    as.data.frame()
  trainset_y <- dataset %>%
    select(Activity) %>%
    na.omit() %>%
    unlist() %>%
    unname()
  trainset <- trainset %>% select(-Activity)
  trainset_G <- trainset[which(trainset_y == "G"), ]
  trainset_GM <- trainset[which(trainset_y == "GM"), ]
  trainset_R <- trainset[which(trainset_y == "R"), ]
  trainset_W <- trainset[which(trainset_y == "W"), ]
  
  
  # Compute fast (approximate) Shapley values using 50 Monte Carlo repetitions
  message(" - Calculating SHAP values for class G")
  shap_values_G <-
    fastshap::explain(
      model,
      X = trainset,
      pred_wrapper = p_function_G,
      nsim = nsim,
      newdata = trainset_G
    )
  message(" - Calculating SHAP values for class GM")
  shap_values_GM <-
    fastshap::explain(
      model,
      X = trainset,
      pred_wrapper = p_function_GM,
      nsim = nsim,
      newdata = trainset_GM
    )
  message(" - Calculating SHAP values for class R")
  shap_values_R <-
    fastshap::explain(
      model,
      X = trainset,
      pred_wrapper = p_function_R,
      nsim = nsim,
      newdata = trainset_R
    )
  message(" - Calculating SHAP values for class W")
  shap_values_W <-
    fastshap::explain(
      model,
      X = trainset,
      pred_wrapper = p_function_W,
      nsim = nsim,
      newdata = trainset_W
    #  adjust = TRUE
    )
  
 shap_values_GM$class<-"GM"
 shap_values_G$class<-"G"
 shap_values_R$class<-"R"
 shap_values_W$class<-"W" 
  
 shap_values<-rbind(shap_values_G,
                     shap_values_GM,
                     shap_values_R,
                     shap_values_W)
 shap_values
}


#' A new function for calcualting SHAP values
#' the function returns a dataframe with SHAP values in the same
#' order of the original dataset.
#' 
#' SHAP value dataframe also contains information about Animal and 
#' the prediction of the model. Notice that SHAP are calculated considering
#' the class (ground truth) and not the prediction. The prediction column is only
#' used for filtering ana analysis. The function `calculate_shapp_class()` can be
#' used for calculating SHAP values on prediction
#' 
#' @param dataset a dataset used for calcuating SHAP. The dataset is used for 
#' permutation during SHAP calculation and also each class is filtered and SHAP 
#' value for each class is calculated.
#' @param model a model 
#' @param nsim number of monte carlo simulation
#'
#' @return
#' @export
#'
#' @examples
calculate_shap <- function(dataset,model,nsim=10) {
  trainset <- dataset %>%  na.omit() %>%
    as.data.frame()
  trainset_y <- dataset %>%
    select(Activity) %>%
    na.omit() %>%
    unlist() %>%
    unname()
  ## Create an ID for maintaining the order
  trainset <- cbind(id=seq(1:nrow(trainset)), trainset)
  trainset <- trainset %>% select(-Activity)
  
  trainset_G <- trainset[which(trainset_y == "G"), ]
  trainset_GM <- trainset[which(trainset_y == "GM"), ]
  trainset_R <- trainset[which(trainset_y == "R"), ]
  trainset_W <- trainset[which(trainset_y == "W"), ]
  
  id <- c(trainset_G$id, 
          trainset_GM$id, 
          trainset_R$id,
          trainset_W$id)
  trainset <- trainset %>% select(-id)
  trainset_G <- trainset_G %>% select(-id)
  trainset_GM <- trainset_GM %>% select(-id)
  trainset_R <- trainset_R %>% select(-id)
  trainset_W <- trainset_W %>% select(-id)
  
  Anim <- c(trainset_G$Anim, 
            trainset_GM$Anim, 
            trainset_R$Anim,
            trainset_W$Anim)
  trainset <- trainset %>% select(-Anim)
  trainset_G <- trainset_G %>% select(-Anim)
  trainset_GM <- trainset_GM %>% select(-Anim)
  trainset_R <- trainset_R %>% select(-Anim)
  trainset_W <- trainset_W %>% select(-Anim)
  
  predictions <- c(trainset_G$predictions, 
                   trainset_GM$predictions, 
                   trainset_R$predictions,
                   trainset_W$predictions)
  trainset <- trainset %>% select(-predictions)
  trainset_G <- trainset_G %>% select(-predictions)
  trainset_GM <- trainset_GM %>% select(-predictions)
  trainset_R <- trainset_R %>% select(-predictions)
  trainset_W <- trainset_W %>% select(-predictions)
  
  # Compute fast (approximate) Shapley values using 50 Monte Carlo repetitions
  message(" - Calculating SHAP values for class G")
  shap_values_G <-
    fastshap::explain(
      model,
      X = trainset,
      pred_wrapper = p_function_G,
      nsim = nsim,
      newdata = trainset_G
    )
  message(" - Calculating SHAP values for class GM")
  shap_values_GM <-
    fastshap::explain(
      model,
      X = trainset,
      pred_wrapper = p_function_GM,
      nsim = nsim,
      newdata = trainset_GM
    )
  message(" - Calculating SHAP values for class R")
  shap_values_R <-
    fastshap::explain(
      model,
      X = trainset,
      pred_wrapper = p_function_R,
      nsim = nsim,
      newdata = trainset_R
    )
  message(" - Calculating SHAP values for class W")
  shap_values_W <-
    fastshap::explain(
      model,
      X = trainset,
      pred_wrapper = p_function_W,
      nsim = nsim,
      newdata = trainset_W
      #  adjust = TRUE
    )
  

  shap_values_G <- shap_values_G %>% as.data.frame()
  shap_values_GM <- shap_values_GM %>% as.data.frame()
  shap_values_R <- shap_values_R %>% as.data.frame()
  shap_values_W <- shap_values_W %>% as.data.frame()
  

  shap_values_G$class<-"G"
  shap_values_GM$class<-"GM"
  shap_values_R$class<-"R"
  shap_values_W$class<-"W" 
  
  shap_values<-rbind(shap_values_G,
                     shap_values_GM,
                     shap_values_R,
                     shap_values_W)
  
  shap_values <- shap_values %>% tibble::add_column(Anim)
  shap_values <- shap_values %>% tibble::add_column(predictions)
  #shap_values <-shap_values %>% tibble::add_column(id)
  shap_values[order(id),] 
}

#' Calculate SHAP values for a given PREDICTED class
#'
#' @param dataset the dataset used for permutation during SHAP calculation
#' @param new_data the new data we want to calculate SHAP
#' @param model  the model used for explanation
#' @param nsim  the number of Monte Carlos Simulations
#' @param function_class a wrapper function to obtain only a particular class
#' @param class_name the name of the class
#'
#' @return
#' @export
#'
#' @examples
#' 
#' # Calculate the SHAP values for class G on new data
#' shap_values_G <- calculate_shap_class(
#' dataset, 
#' new_data = newdata, 
#' model = goat_model 
#' nsim = 100, 
#' function_class = p_function_G,
#' class_name = "G")
#' 
#' 
calculate_shap_class <- function(dataset, new_data, model,nsim=10, 
                                 function_class, class_name = "G") {
  trainset <- dataset %>%  na.omit() %>%
    as.data.frame()
  trainset_y <- dataset %>%
    select(predictions) %>%
    na.omit() %>%
    unlist() %>%
    unname()
  
  trainset<- trainset %>%select (-Activity,-predictions,-Anim)
  new_data_class <- new_data 
  
  Anim <- new_data_class$Anim 
  new_data_class <- new_data_class %>% select(-Anim)
  
  Activity <- new_data_class$Activity
  new_data_class <- new_data_class %>% select(-Activity)
  
  predictions <- new_data_class$predictions
  new_data_class <- new_data_class %>% select(-predictions)
  
  # Compute fast (approximate) Shapley values using 50 Monte Carlo repetitions
  message(" - Calculating SHAP values for class ",class_name)
  shap_values_class <-
    fastshap::explain(
      model,
      X = trainset,
      pred_wrapper = function_class,
      nsim = nsim,
      newdata = new_data_class,
    )
  
  shap_values_class$class<-Activity
  shap_values<-shap_values_class
  
  shap_values <- shap_values %>% tibble::add_column(Anim)
  shap_values <- shap_values %>% tibble::add_column(predictions)
  shap_values
}

shap_summary_plot<-function(shap_values){
  summary_plot <-
    shap_values %>% reshape2::melt() %>% group_by(class, variable) %>% 
    summarise(mean = mean(abs(value))) %>% 
    arrange(desc(mean)) %>%
    ggplot() +
    ggdark::dark_theme_classic() +
    geom_col(aes(
      y = variable,
      x = mean,
      group = class,
      fill = class
    ), position = "stack") +
    xlab("Mean(|Shap Value|) Average impact on model output magnitude")
  summary_plot
  
}

shap_beeswarm_plot<-function(shap_values,dataset){
  
  shap_values <- shap_values %>% reshape2::melt()
  dataset<-dataset %>% mutate(class=Activity) %>% select(-Activity) %>% 
    reshape2::melt() %>% group_by(variable) %>% 
    mutate(value_scale=range01(value))
  
  beeswarm_plot<-cbind(shap_values, feature_value=dataset$value_scale) %>% 
    # filter(class=="GM") %>%
    ggplot()+
    facet_wrap(~class)+
    #ggdark::dark_theme_bw()+
    theme_classic()+
    geom_hline(yintercept=0, 
               color = "red", size=0.5)+
    ggforce::geom_sina(aes(x=variable,y=value,color=feature_value),size=0.5,bins=4,alpha=0.9,shape=15)+
    scale_colour_gradient(low = "yellow", high = "red", na.value = NA)+
    scale_colour_gradient(low = "skyblue", high = "orange", na.value = NA)+
    xlab("Feature")+ylab("SHAP value")+
    theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust=1))
  beeswarm_plot
}