I am building a ShinyDashboard assessment tool with a Bayesian network engine using bnlearn. It is a discrete network created using expert knowledge to build the conditional probability tables. The shiny front end is used to elicit evidence, however, when I try and apply the evidence at the back-end using cpquery, it is not working. If I hard code the evidence in the backend shiny server, it works. So I think it is something to do with accessing the input variables I am missing.
I have tried various ways of formatting the evidence for cpquery but to no avail and as I have said, tried hard coding values, which worked fine.
This works fine!
Index <- shiny::reactive({
cpquery(fitted = tdag,
event = (A == "High"), # event
evidence = ( (B == "Yes") & # evidence
(C == "Medium") &
(D == "Medium") &
(E == "Yes") &
(G == "High") &
(H == "Low")
), # end evidence
n = 1000000, # no of samples generated
debug = TRUE
) # end cpqery
}) # end reactive
This does not:
Index <- shiny::reactive({
# Create a string of the selected evidence
str1 <<- paste0(
"(B == '", input$BChoiceInp, "') & ",
"(C == '", input$CChoiceInp, "') & ",
"(D == '", input$DChoiceInp, "') & ",
"(E == '", input$EChoiceInp, "') & ",
"(G == '", input$GChoiceInp, "') & ",
"(H == '", input$HChoiceInp, "')"
)
cpquery(fitted = tdag,
event = (A == "High"), # event
evidence = (eval(parse(text = str1))), # evidence
n = 1000000, # no of samples generated
debug = TRUE
) # end cpqery
}) # end reactive
I have also tried using
str2 = "(A == "'High'")"
eval(parse(text = paste("cpquery(fitted,",str2,",",str1,", n = 100000, debug=TRUE)")))
Same result. The network runs but the result is as below - it does not seem to see the inputs.:
* checking which nodes are needed.
> event involves the following nodes: A
> evidence involves the following nodes: B C D E G H
> upper closure is ' A B C D E F G H I J '
> generating observations from 10 / 10 nodes.
* generated 10000 samples from the bayesian network.
> evidence matches 0 samples out of 10000 (p = 0).
> event matches 0 samples out of 0 (p = 0).
* generated 10000 samples from the bayesian network.
> evidence matches 0 samples out of 10000 (p = 0).
> event matches 0 samples out of 0 (p = 0).
This is the result with evidence hardcoded - works fine:
* generated 10000 samples from the bayesian network.
> evidence matches 39 samples out of 10000 (p = 0.0039).
> event matches 30 samples out of 39 (p = 0.7692308).
* generated 10000 samples from the bayesian network.
> evidence matches 33 samples out of 10000 (p = 0.0033).
> event matches 21 samples out of 33 (p = 0.6363636).
* generated 10000 samples from the bayesian network.
> evidence matches 36 samples out of 10000 (p = 0.0036).
> event matches 23 samples out of 36 (p = 0.6388889).
* generated a grand total of 1e+06 samples.
> event matches 2666 samples out of 4173 (p = 0.6388689)
Heeeelllp!