0

I have an automl model created with the H2O package. Currently, H2O only calculates Shapley values on tree-based models. I've used the IML package to calculate the values on the AML model. However, because I have a large number of features, the plot is too jumbled to read. I'm looking for a way to select/show only the top X number of features. I can't find anything in the IML CRAN PDF nor in other documentation I've found by Googling.

#initiate h2o
h2o.init()
h2o.no_progress()

#create automl model (data cleaning and train/test split not shown)
set.seed(1911)
num_models <- 10
aml <- h2o.automl(y = label, x = features,
                   training_frame = train.hex,
                   nfolds = 5,
                   balance_classes = TRUE,
                   leaderboard_frame = test.hex,
                   sort_metric = 'AUCPR',
                   max_models = num_models,
                   verbosity = 'info',
                   exclude_algos = "DeepLearning", #exclude for reproducibility
                   seed = 27)

# 1. create a data frame with just the features
features_eval <- as.data.frame(test) %>% dplyr::select(-target)

# 2. Create a vector with the actual responses
response <- as.numeric(as.vector(test$target))

# 3. Create custom predict function that returns the predicted values as a
#    vector (probability of purchasing in our example)
pred <- function(model, newdata)  {
  results <- as.data.frame(h2o.predict(model, as.h2o(newdata)))
  return(results[[3L]])
}

# example of prediction output
pred(aml, features_eval) %>% head()

#create predictor needed
predictor.aml <- Predictor$new(
  model = aml, 
  data = features_eval, 
  y = response, 
  predict.fun = pred,
  class = "classification"
  )

high <- predict(aml, test.hex) %>% .[,3] %>% as.vector() %>% which.max()

high_prob_ob <- features_eval[high, ]

shapley <- Shapley$new(predictor.aml, x.interest = high_prob_ob, sample.size = 200) 

plot(shapley, sort = TRUE)

Any suggestions/help appreciated.

Thank you, Brian

Brian Head
  • 57
  • 4

1 Answers1

0

I can offer a hacky solution that utilizes the fact that iml uses ggplot2 to plot.

N <- 10 # number of features to show

# Capture the ggplot2 object
p <- plot(shapley, sort = TRUE)

# Modify it so it shows only top N features
print(p + scale_x_discrete(limits=rev(p$data$feature.value[order(-p$data$phi)][1:N])))
Tomáš Frýda
  • 546
  • 3
  • 8