Get sufficient and counterfactual explanations for a prediction
bfs_sfx_cfx.Rd
Get sufficient and counterfactual explanations for a prediction
Arguments
- predict_f
A function that takes in a dataframe of evidence and outputs a list with the prediction for each row.
- evidence
A dataframe of one row where all columns are of type factor.
- outcome
The resulting prediction for the evidence.
- expected
The expected prediction of the evidence (only for counterfactuals).
Examples
set.seed(40)
bn <- NULL
if (!requireNamespace("bnlearn", quietly = TRUE)) {
stop("bnlearn package needed to execute this functionality")
}
download.file("https://www.bnlearn.com/bnrepository/child/child.rda",
"child.rda", "auto",
quiet = TRUE
)
load("child.rda") # Load the popular CHILD Bayesian Network
file.remove("child.rda")
#> [1] TRUE
evidence <- data.frame(
LVHReport = factor(x = "yes", levels = dimnames(bn$LVHreport$prob)[[1]]),
LowerBodyO2 = factor(x = "5-12", levels = dimnames(bn$LowerBodyO2$prob)[[1]]),
CO2Report = factor(x = "<7.5", levels = dimnames(bn$CO2Report$prob)[[1]]),
XrayReport = factor(x = "Oligaemic", levels = dimnames(bn$XrayReport$prob)[[1]])
)
outcome <- predict(
object = bn, node = bn$Disease$node, data = evidence, method = "bayes-lw"
)
print(paste("Outcome: ", outcome))
#> [1] "Outcome: Fallot"
expected <- factor("TGA", levels = levels(outcome))
predict_f <- bnlearn_predict_wrapper(bn, bn$Disease$node, "bayes-lw", n = 500000)
r <- bfs_sfx_cfx(predict_f, evidence, outcome, expected)
print("Sufficient explanations:")
#> [1] "Sufficient explanations:"
print(data.table::rbindlist(r[["sfxs"]], fill = T))
#> XrayReport
#> 1: Oligaemic
print("Counterfactual explanations")
#> [1] "Counterfactual explanations"
print(data.table::rbindlist(r[["cfxs"]], fill = T))
#> XrayReport LowerBodyO2
#> 1: Normal <NA>
#> 2: Plethoric <NA>
#> 3: Grd_Glass <NA>
#> 4: Asy/Patchy <5