Slide 22
Slide 22 text
• DE DS Biz 1,000
Counterfactual Explanations
counterfactual_explanations <- function(model, current_x, desired_y) {
as_input <- function(x) tibble(ds = x[1], de = x[2], biz = x[3]) #
predict_num <- function(model, x) pull(predict(model, as_input(x))) # df numeric
constraint <- function(x) predict_num(model, x) - desired_y #
distance <- function(x) norm(current_x - x, type = "2") #
solution <- Rsolnp::solnp( #
pars = current_x + 1e-3,
fun = distance,
ineqfun = constraint,
ineqLB = 0,
ineqUB = 0.1,
LB = current_x,
UB = c(100, current_x[2] + 1e-2, 100), # DE
control = list(tol = 1e-5)
)
result <- list(
current_x = as_input(current_x), #
current_y = predict_num(model, current_x), #
desired_y = desired_y, #
required_x = as_input(solution$pars), #
predicted_y = predict_num(model, solution$pars) #
)
return(result)
}