## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 6,
  fig.height = 4,
  dpi = 110
)

## ----fit-workflow-------------------------------------------------------------
library(uniml)

data <- read.csv(
  system.file("extdata", "uniml-cvd-mortality.csv", package = "uniml")
)
set.seed(123)
data <- data[1:400, ]

spec <- uniml_spec(
  task_type = "binary",
  outcome = "died",
  positive = "yes",
  id = "id"
)
spec <- set_preprocess(
  spec,
  impute = "median_mode",
  scale = "zscore",
  encode = "onehot"
)
spec <- set_feature_selection(spec, methods = "univariate")
spec <- set_learners(spec, "cart", tune = FALSE)
spec <- set_evaluation(spec, ci = "none", calibration = "none")

split <- make_split(
  as_uniml_data(data, spec),
  prop = c(0.8, 0.2),
  stratify = TRUE,
  seed = 123
)
result <- run_workflow(
  spec,
  train = split$train$data,
  validation = split$validation$data
)
length(result$selection$selected_features)

## ----explain------------------------------------------------------------------
explained <- explain_shap(
  result,
  model = "best",
  n_explain = 30,
  bg_n = 18,
  seed = 123
)

explained$shap
head(explained$shap$importance, 6)

## ----direct-learner-----------------------------------------------------------
learner <- result$models[[1L]]$learner
explanation <- explain_shap(
  learner,
  data = result$preprocess$train[, setdiff(
    names(result$preprocess$train), "died"
  )],
  n_explain = 20,
  bg_n = 14,
  seed = 123,
  positive = "yes"
)
explanation$models

## ----importance, fig.cap = "Mean absolute SHAP value per feature."------------
plot_shap_importance(explained)

## ----beeswarm, fig.cap = "Distribution and direction of individual contributions."----
plot_shap_beeswarm(explained, max_display = 8)

## ----dependence, fig.cap = "SHAP dependence for one feature."-----------------
plot_shap_dependence(explained, feature = "age")

## ----waterfall, fig.cap = "Single-observation waterfall for the first explained row."----
plot_shap_waterfall(explained, row_id = 1)

## ----thresholds, eval = FALSE-------------------------------------------------
# thresholds <- extract_thresholds(
#   explained$shap,
#   target = "age",
#   min_n = 20,
#   min_unique = 8
# )
# 
# thresholds$zero_crossings
# thresholds$paper_ready

