vignettes/articles/explainer_tutorial_binary_classification.Rmd
explainer_tutorial_binary_classification.Rmd
This is an R Markdown Notebook. When you execute code within the notebook, the results appear beneath the code.
Try executing this chunk by clicking the Run button within the chunk or by placing your cursor inside it and pressing Ctrl+Shift+Enter.
This is an example on how to use the package “explainer” developed by Ramtin Zargari Marandi (email:ramtin.zargari.marandi@regionh.dk)
This first code chunk loads a dataset and creates a binary classification task and train a “random forest” model using mlr3 package.
Sys.setenv(LANG = "en") # change R language to English!
RNGkind("L'Ecuyer-CMRG") # change to L'Ecuyer-CMRG in case it uses default "Mersenne-Twister"
library("explainer")
# set seed for reproducibility
seed <- 246
set.seed(seed)
# load the BreastCancer data from the mlbench package
data("BreastCancer", package = "mlbench")
# keep the target column as "Class"
target_col <- "Class"
# change the positive class to "malignant"
positive_class <- "malignant"
# keep only the predictor variables and outcome
mydata <- BreastCancer[, -1] # 1 is ID
# remove rows with missing values
mydata <- na.omit(mydata)
# create a vector of sex categories
sex <- sample(c("Male", "Female"), size = nrow(mydata), replace = TRUE)
# create a vector of sex categories
mydata$age <- as.numeric(sample(seq(18,60), size = nrow(mydata), replace = TRUE))
# add a sex column to the mydata data frame (for fairness analysis)
mydata$sex <- factor(sex, levels = c("Male", "Female"), labels = c(1, 0))
# create a classification task
maintask <- mlr3::TaskClassif$new(id = "my_classification_task",
backend = mydata,
target = target_col,
positive = positive_class)
# create a train-test split
set.seed(seed)
splits <- mlr3::partition(maintask)
# add a learner (machine learning model base)
# library("mlr3learners")
# library("mlr3extralearners")
# mlr_learners$get("classif.randomForest")
# here we use random forest for example (you can use any other available model)
# mylrn <- mlr3::lrn("classif.randomForest", predict_type = "prob")
library("mlr3learners")
## Warning: package 'mlr3learners' was built under R version 4.1.3
## Loading required package: mlr3
mylrn <- mlr3::lrn("classif.ranger", predict_type = "prob")
# train the model
mylrn$train(maintask, splits$train)
# make predictions on new data
mylrn$predict(maintask, splits$test)
## <PredictionClassif> for 226 observations:
## row_ids truth response prob.malignant prob.benign
## 2 benign malignant 0.8358405 0.1641595238
## 3 benign benign 0.0010000 0.9990000000
## 4 benign malignant 0.8758770 0.1241230159
## ---
## 655 malignant malignant 0.9152730 0.0847269841
## 665 malignant malignant 0.9993333 0.0006666667
## 683 malignant malignant 0.9147024 0.0852976190
The following code chunk uses eSHAP_plot function to estimate SHAP values for the test set and create an interactive SHAP plot. This is an enhanced SHAP plot that means it provides additional information such as whether the predictions were correct (TP or TN). The color mapping provides enhanced visual inspection of the SHAP plot.
## Warning: package 'plotly' was built under R version 4.1.3
## Loading required package: ggplot2
## Warning: package 'ggplot2' was built under R version 4.1.3
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
# enhanced SHAP plot
SHAP_output <- eSHAP_plot(task = maintask,
trained_model = mylrn,
splits = splits,
sample.size = 30,
seed = seed,
subset = .8)
## Warning: Ignoring unknown aesthetics: text
## Warning: `gather_()` was deprecated in tidyr 1.2.0.
## Please use `gather()` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was generated.
# display the SHAP plot
myplot <- SHAP_output[[1]]
myplot
The following plot displays SHAP values associate with the predicted probabilities.
SHAP_output[[5]]
## `geom_smooth()` using formula 'y ~ x'
The following code chunk uses eCM_plot function to visualize the confusion matrix to evaluate model performance for the train and test sets. More information can be found here: https://en.wikipedia.org/wiki/Confusion_matrix https://cran.r-project.org/web/packages/cvms/vignettes/Creating_a_confusion_matrix.html
# enhanced confusion matrix
confusionmatrix_plot <- eCM_plot(task = maintask,
trained_model = mylrn,
splits = splits)
## Warning in pal_name(palette, type): Unknown palette Green
## Warning in pal_name(palette, type): Unknown palette Green
print(confusionmatrix_plot)
## $train_set
##
## $test_set
The provided code chunk employs the eDecisionCurve function to conduct “decision curve analysis” on the test set within the model. For an in-depth understanding of this methodology, interested readers are encouraged to explore the following authoritative references:
Decision Curve Analysis: https://en.wikipedia.org/wiki/Decision_curve_analysis “Decision curve analysis: a novel method for evaluating prediction models” by Andrew J. Vickers and Elia B. Elkin. Link: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2577036/ These references offer comprehensive insights into the principles and applications of decision curve analysis, providing a solid foundation for further exploration and understanding of the methodology employed in the presented code.
# enhanced decision curve plot
eDecisionCurve(task = maintask,
trained_model = mylrn,
splits = splits,
seed = seed)
By running the next code chunk, you will get the following model evaluation metrics and visualizations:
AUC (Area Under the Curve): AUC quantifies the binary classification model’s performance by assessing the area under the ROC curve, which plots sensitivity against 1-specificity across various threshold values. A value of 0.5 suggests random chance performance, while 1 signifies perfect classification.
BACC (Balanced Accuracy): BACC addresses class imbalance by averaging sensitivity and specificity. Ranging from 0 to 1, a score of 0 indicates chance performance, and 1 signifies perfect classification.
MCC (Matthews Correlation Coefficient): MCC evaluates binary classification model quality, considering true positives, true negatives, false positives, and false negatives. Ranging from -1 to 1, -1 represents complete disagreement, 0 implies chance performance, and 1 indicates perfect classification.
BBRIER (Brier Score): BBRIER gauges the accuracy of probabilistic predictions by measuring the mean squared difference between predicted probabilities and true binary outcomes. Values range from 0 to 1, with 0 indicating perfect calibration and 1 indicating poor calibration.
PPV (Positive Predictive Value): PPV, or precision, measures the proportion of true positive predictions out of all positive predictions made by the model.
NPV (Negative Predictive Value): NPV quantifies the proportion of true negative predictions out of all negative predictions made by the model.
Specificity: Specificity calculates the proportion of true negative predictions out of all actual negative cases in a binary classification problem.
Sensitivity: Sensitivity, also known as recall or true positive rate, measures the proportion of true positive predictions out of all actual positive cases in a binary classification problem.
PRAUC (Precision-Recall Area Under the Curve): PRAUC assesses binary classification model performance based on precision and recall, quantifying the area under the precision-recall curve. A PRAUC value of 1 indicates perfect classification performance.
Additionally, the analysis involves the visualization of ROC and Precision-Recall curves for both development and test sets.
eROC_plot(task = maintask,
trained_model = mylrn,
splits = splits)
## [[1]]
##
## [[2]]
## pred_results$score(measures = mlr3::msrs(meas))
## auc 1.00
## bacc 0.99
## mcc 0.97
## bbrier 0.01
## ppv 0.96
## npv 1.00
## specificity 0.98
## sensitivity 0.99
## prauc 1.00
##
## [[3]]
## pred_results_test$score(measures = mlr3::msrs(meas))
## auc 0.99
## bacc 0.98
## mcc 0.94
## bbrier 0.03
## ppv 0.94
## npv 0.99
## specificity 0.97
## sensitivity 0.99
## prauc 0.99
By running the next code chunk, you will get ROC and Precision Recall curves for the development and test sets this time with probability threshold information.
ePerformance(task = maintask,
trained_model = mylrn,
splits = splits)
## [[1]]
##
## [[2]]
##
## [[3]]
Now we can get the outputs from eSHAP_plot function to apply clustering on SHAP values
shap_Mean_wide <- SHAP_output[[2]]
shap_Mean_long <- SHAP_output[[3]]
shap <- SHAP_output[[4]]
ShapFeaturePlot(shap_Mean_long)
Partial dependence plots (PDPs): PDPs can be used to visualize the marginal effect of a single feature on the model prediction.
ShapPartialPlot(shap_Mean_long = shap_Mean_long)
fval_predprob <- reshape2::dcast(shap, sample_num + pred_prob + predcorrectness ~ feature, value.var = "feature.value")
## Warning: package 'shiny' was built under R version 4.1.3
library(ggplot2)
# assuming your data.table is named `fval_predprob`
ui <- fluidPage(
titlePanel("Feature Plot"),
sidebarLayout(
sidebarPanel(
selectInput("x_feature", "X-axis Feature:",
choices = names(fval_predprob)),
selectInput("y_feature", "Y-axis Feature:",
choices = names(fval_predprob)),
width = 2,
actionButton("stop_button", "Stop")
),
mainPanel(
plotOutput("feature_plot")
)
)
)
server <- function(input, output) {
# create a reactive value for the app state
app_state <- reactiveValues(running = TRUE)
output$feature_plot <- renderPlot({
ggplot(fval_predprob, aes(x = .data[[input$x_feature]], y = .data[[input$y_feature]], fill = pred_prob)) +
geom_tile() +
scale_fill_gradient(low = "white", high = "steelblue", limits = c(0, 1)) +
xlab(input$x_feature) +
ylab(input$y_feature) +
labs(shape = "correct prediction") +
egg::theme_article()
})
# observe the stop button
observeEvent(input$stop_button, {
app_state$running <- FALSE
})
# stop the app if the running state is FALSE
observe({
if(!app_state$running) {
stopApp()
}
})
}
shinyApp(ui = ui, server = server)
str(shap_Mean_long)
## Classes 'data.table' and 'data.frame': 1991 obs. of 9 variables:
## $ feature : chr "Bare.nuclei" "Bare.nuclei" "Bare.nuclei" "Bare.nuclei" ...
## $ mean_phi : num 0.0649 0.0649 0.0649 0.0649 0.0649 ...
## $ Phi : num -0.0729 -0.0549 0.1379 -0.0656 0.0763 ...
## $ f_val : num 0 0 1 0 1 ...
## $ unscaled_f_val : num 1 1 10 1 10 10 10 8 10 1 ...
## $ sample_num : int 1 2 3 4 5 6 7 8 9 10 ...
## $ correct_prediction: Factor w/ 2 levels "Incorrect","Correct": 2 2 2 2 2 2 2 2 2 2 ...
## $ pred_prob : num 0.0101 0 0.9974 0 0.9953 ...
## $ pred_class : Factor w/ 2 levels "malignant","benign": 2 2 1 2 1 1 1 1 1 2 ...
## - attr(*, ".internal.selfref")=<externalptr>
# This is the data table that includes SHAP values in wide format. Each row contains sample_num as sample ID and the SHAP values for each feature.
shap_Mean_wide
## sample_num Bare.nuclei Bl.cromatin Cell.shape Cell.size Cl.thickness
## 1: 1 -0.07287679 -0.055106455 -0.05081765 -0.05486442 0.006185291
## 2: 2 -0.05493719 -0.037173757 -0.06098050 -0.06545296 -0.058971164
## 3: 3 0.13789815 0.058754683 0.12870026 0.14223449 0.086605714
## 4: 4 -0.06555385 -0.039005370 -0.05229164 -0.05542087 -0.020331402
## 5: 5 0.07631368 0.057564815 0.08233381 0.10147267 0.066846164
## ---
## 177: 177 0.05812723 -0.003085053 0.12915488 0.13961897 0.128036243
## 178: 178 -0.04882468 -0.037083942 -0.08432108 -0.08397559 -0.046736878
## 179: 179 -0.03473627 0.057561190 0.11510476 0.16816315 0.094001693
## 180: 180 0.09945423 0.055944339 0.09418344 0.13291114 0.118309683
## 181: 181 -0.04265656 -0.041917169 -0.06204106 -0.08122761 -0.005213492
## Epith.c.size Marg.adhesion Mitoses Normal.nucleoli age
## 1: -0.036799418 -0.012048362 -4.142672e-03 -0.06693828 -0.0005918519
## 2: -0.017381746 -0.019521518 -1.975688e-03 -0.04963878 -0.0011856085
## 3: 0.005817246 0.056002963 -5.232540e-04 0.06682265 0.0005759524
## 4: 0.004501958 -0.032337470 -1.226614e-03 -0.02490021 -0.0003635450
## 5: 0.008760952 0.013999048 -2.830688e-06 0.07287598 0.0049224868
## ---
## 177: 0.038181551 0.012632763 -2.112698e-04 0.08742757 0.0005067460
## 178: -0.021231347 -0.022494031 -3.343995e-03 -0.04009484 0.0004915344
## 179: 0.039792011 0.028834180 -2.312566e-03 0.09089204 -0.0009586772
## 180: 0.026060185 0.025889206 3.372354e-03 0.06535484 -0.0011364550
## 181: -0.026952292 -0.004596962 -3.159630e-03 -0.03913471 0.0016819048
## sex
## 1: 0.0004041534
## 2: 0.0008017989
## 3: -0.0006172751
## 4: -0.0009955026
## 5: -0.0023246296
## ---
## 177: -0.0008160582
## 178: -0.0007487037
## 179: 0.0006310317
## 180: -0.0009093651
## 181: 0.0011641005
# This is the data table of SHAP values in long format and includes feature name, mean_phi_test: mean shap value for the feature across samples, scaled feature values, shap values for each feature, sample ID, and whether the prediction was correct (i.e. predicted class = actual class)
shap_Mean_long
## feature mean_phi Phi f_val unscaled_f_val sample_num
## 1: Bare.nuclei 0.064888550 -0.0728767908 0 1 1
## 2: Bare.nuclei 0.064888550 -0.0549371876 0 1 2
## 3: Bare.nuclei 0.064888550 0.1378981481 1 10 3
## 4: Bare.nuclei 0.064888550 -0.0655538502 0 1 4
## 5: Bare.nuclei 0.064888550 0.0763136772 1 10 5
## ---
## 1987: sex 0.001461838 -0.0008160582 0 1 177
## 1988: sex 0.001461838 -0.0007487037 0 1 178
## 1989: sex 0.001461838 0.0006310317 1 2 179
## 1990: sex 0.001461838 -0.0009093651 0 1 180
## 1991: sex 0.001461838 0.0011641005 1 2 181
## correct_prediction pred_prob pred_class
## 1: Correct 0.01012143 benign
## 2: Correct 0.00000000 benign
## 3: Correct 0.99736667 malignant
## 4: Correct 0.00000000 benign
## 5: Correct 0.99533333 malignant
## ---
## 1987: Correct 0.97105238 malignant
## 1988: Correct 0.00000000 benign
## 1989: Correct 0.97433016 malignant
## 1990: Correct 0.99744762 malignant
## 1991: Correct 0.01433579 benign
SHAP clustering is a method to better understand why a model may perform better for some patients than others. Here for example, you can identify patient subgroups that have specific patterns that are different from other subgroups and that explains why the model you developed have perhaps better or worse performance for those patients than the average performance for the whole dataset. You can see the difference in the SHAP plots that if you group all together provide the overall SHAP summary plot. Again here the edges reflect how features may interact with each other in each individual sample (instance).
# the number of clusters can be changed
SHAP_plot_clusters <- SHAPclust(task = maintask,
trained_model = mylrn,
splits = splits,
shap_Mean_wide = shap_Mean_wide,
shap_Mean_long = shap_Mean_long,
num_of_clusters = 3,
seed = seed,
subset = .8)
## sample_num feature Phi cluster mean_phi f_val
## 1: 1 Bare.nuclei -0.072876791 2 0.064888550 0.0000000
## 2: 1 Bl.cromatin -0.055106455 2 0.044719981 0.2000000
## 3: 1 Cell.shape -0.050817650 2 0.082139614 0.0000000
## 4: 1 Cell.size -0.054864418 2 0.093647011 0.0000000
## 5: 1 Cl.thickness 0.006185291 2 0.046419402 0.5555556
## ---
## 1987: 181 Marg.adhesion -0.004596962 2 0.030218047 0.2222222
## 1988: 181 Mitoses -0.003159630 2 0.003487597 0.0000000
## 1989: 181 Normal.nucleoli -0.039134709 2 0.051280701 0.0000000
## 1990: 181 age 0.001681905 2 0.003487652 0.7380952
## 1991: 181 sex 0.001164101 2 0.001461838 1.0000000
## unscaled_f_val correct_prediction pred_prob pred_class
## 1: 1 Correct 0.01012143 benign
## 2: 2 Correct 0.01012143 benign
## 3: 1 Correct 0.01012143 benign
## 4: 1 Correct 0.01012143 benign
## 5: 6 Correct 0.01012143 benign
## ---
## 1987: 3 Correct 0.01433579 benign
## 1988: 1 Correct 0.01433579 benign
## 1989: 1 Correct 0.01433579 benign
## 1990: 49 Correct 0.01433579 benign
## 1991: 2 Correct 0.01433579 benign
## Warning: Ignoring unknown aesthetics: text
# note that the subset must be the same value as the SHAP analysis done earlier
# display the SHAP cluster plots
SHAP_plot_clusters[[1]]
# display the confusion matrices corresponding to the SHAP clusters (patient subsets determined by SHAP clusters)
SHAP_plot_clusters[[2]]
Sometimes we would like to investigate whether our model performs fairly well for different subgroups based on categories of variables such as sex.
# you should decide what variables to use to be tested
# here we chose sex from the variables existing in the dataset
Fairness_results <- eFairness(task = maintask,
trained_model = mylrn,
splits = splits,
target_variable = "sex",
var_levels = c("Male", "Female"))
## Warning in verify_d(data$d): D not labeled 0/1, assuming benign = 0 and
## malignant = 1!
## Warning in verify_d(data$d): D not labeled 0/1, assuming benign = 0 and
## malignant = 1!
## Warning in verify_d(data$d): D not labeled 0/1, assuming benign = 0 and
## malignant = 1!
# ROC curves for the subgroups for the development (left) and test (right) sets
Fairness_results[[1]]
# performance in the subgroups for the development set
Fairness_results[[2]]
## Male Female
## auc 1.00 1.00
## bacc 0.99 0.99
## mcc 0.96 0.97
## bbrier 0.01 0.01
## ppv 0.95 0.98
## npv 1.00 0.99
## specificity 0.97 0.99
## sensitivity 1.00 0.99
## prauc 1.00 1.00
# performance in the subgroups for the test set
Fairness_results[[3]]
## Male Female
## auc 0.99 0.99
## bacc 0.99 0.97
## mcc 0.96 0.93
## bbrier 0.03 0.03
## ppv 0.94 0.94
## npv 1.00 0.99
## specificity 0.97 0.96
## sensitivity 1.00 0.98
## prauc 0.99 0.98
# get model parameters
model_params <- mylrn$param_set
print(data.table::as.data.table(model_params))
## id class lower upper
## 1: alpha ParamDbl -Inf Inf
## 2: always.split.variables ParamUty NA NA
## 3: class.weights ParamUty NA NA
## 4: holdout ParamLgl NA NA
## 5: importance ParamFct NA NA
## 6: keep.inbag ParamLgl NA NA
## 7: max.depth ParamInt 0 Inf
## 8: min.node.size ParamInt 1 Inf
## 9: min.prop ParamDbl -Inf Inf
## 10: minprop ParamDbl -Inf Inf
## 11: mtry ParamInt 1 Inf
## 12: mtry.ratio ParamDbl 0 1
## 13: num.random.splits ParamInt 1 Inf
## 14: num.threads ParamInt 1 Inf
## 15: num.trees ParamInt 1 Inf
## 16: oob.error ParamLgl NA NA
## 17: regularization.factor ParamUty NA NA
## 18: regularization.usedepth ParamLgl NA NA
## 19: replace ParamLgl NA NA
## 20: respect.unordered.factors ParamFct NA NA
## 21: sample.fraction ParamDbl 0 1
## 22: save.memory ParamLgl NA NA
## 23: scale.permutation.importance ParamLgl NA NA
## 24: se.method ParamFct NA NA
## 25: seed ParamInt -Inf Inf
## 26: split.select.weights ParamUty NA NA
## 27: splitrule ParamFct NA NA
## 28: verbose ParamLgl NA NA
## 29: write.forest ParamLgl NA NA
## id class lower upper
## levels nlevels is_bounded
## 1: Inf FALSE
## 2: Inf FALSE
## 3: Inf FALSE
## 4: TRUE,FALSE 2 TRUE
## 5: none,impurity,impurity_corrected,permutation 4 TRUE
## 6: TRUE,FALSE 2 TRUE
## 7: Inf FALSE
## 8: Inf FALSE
## 9: Inf FALSE
## 10: Inf FALSE
## 11: Inf FALSE
## 12: Inf TRUE
## 13: Inf FALSE
## 14: Inf FALSE
## 15: Inf FALSE
## 16: TRUE,FALSE 2 TRUE
## 17: Inf FALSE
## 18: TRUE,FALSE 2 TRUE
## 19: TRUE,FALSE 2 TRUE
## 20: ignore,order,partition 3 TRUE
## 21: Inf TRUE
## 22: TRUE,FALSE 2 TRUE
## 23: TRUE,FALSE 2 TRUE
## 24: jack,infjack 2 TRUE
## 25: Inf FALSE
## 26: Inf FALSE
## 27: gini,extratrees,hellinger 3 TRUE
## 28: TRUE,FALSE 2 TRUE
## 29: TRUE,FALSE 2 TRUE
## levels nlevels is_bounded
## special_vals default storage_type tags
## 1: <list[0]> 0.5 numeric train
## 2: <list[0]> <NoDefault[3]> list train
## 3: <list[0]> list train
## 4: <list[0]> FALSE logical train
## 5: <list[0]> <NoDefault[3]> character train
## 6: <list[0]> FALSE logical train
## 7: <list[1]> integer train
## 8: <list[1]> integer train
## 9: <list[0]> 0.1 numeric train
## 10: <list[0]> 0.1 numeric train
## 11: <list[1]> <NoDefault[3]> integer train
## 12: <list[0]> <NoDefault[3]> numeric train
## 13: <list[0]> 1 integer train
## 14: <list[0]> 1 integer train,predict,threads
## 15: <list[0]> 500 integer train,predict,hotstart
## 16: <list[0]> TRUE logical train
## 17: <list[0]> 1 list train
## 18: <list[0]> FALSE logical train
## 19: <list[0]> TRUE logical train
## 20: <list[0]> ignore character train
## 21: <list[0]> <NoDefault[3]> numeric train
## 22: <list[0]> FALSE logical train
## 23: <list[0]> FALSE logical train
## 24: <list[0]> infjack character predict
## 25: <list[1]> integer train,predict
## 26: <list[0]> list train
## 27: <list[0]> gini character train
## 28: <list[0]> TRUE logical train,predict
## 29: <list[0]> TRUE logical train
## special_vals default storage_type tags
The current R package has been developed with the following dependencies, ensuring its functionality and compatibility: For a detailed reference on each package, please consult the respective documentation and citation information available on CRAN (Comprehensive R Archive Network) or the official package repositories.
## Warning: package 'report' was built under R version 4.1.3
oursessionreport <- report(sessionInfo())
summary(oursessionreport)
## The analysis was done using the R Statistical language (v4.1.2; R Core Team,
## 2021) on Windows 10 x64, using the packages plotly (v4.10.0), ggplot2 (v3.3.6),
## mlr3 (v0.14.0), report (v0.5.1), mlr3learners (v0.5.3), magrittr (v2.0.3),
## shiny (v1.7.4) and explainer (v1.0.1).
oursessionreport_df <- as.data.frame(oursessionreport)
data.table::fwrite(oursessionreport_df, file = paste0("sessioninfo",seed,".xlsx"))
summary(as.data.frame(oursessionreport))
## Package | Version
## ----------------------
## explainer | 1.0.1
## ggplot2 | 3.3.6
## magrittr | 2.0.3
## mlr3 | 0.14.0
## mlr3learners | 0.5.3
## plotly | 4.10.0
## R | 4.1.2
## report | 0.5.1
## shiny | 1.7.4