Why the predicted values in BNLEARN changes each time I run the code?

117 views Asked by At

I am using BNLEARN package in R to predict a variable. I noticed each time I run the code, the predicted values keep updating. Can you explain why this happens?

my code is below:

res=hc(training, start = NULL, whitelist = NULL, blacklist = NULL, score = "loglik-g", debug = FALSE, restart = 0, perturb = 1000, max.iter = Inf, maxp = Inf, optimized = TRUE)

graphviz.plot(res) fitted = bn.fit(res, 
  training,
  keep.fitted = TRUE,
  debug = FALSE)

pred_train = predict(fitted,
  node = "beta",
  data=training,
  method = "bayes-lw",
  n=5)

pred_test = predict(fitted,
  node = "beta",
  data=test,
  method = "bayes-lw",
  n=5)
1

There are 1 answers

0
user20650 On

The documentation provides a good source of information. Specifically, when the method is "bayes-lw"

... the predicted values will differ in each call to predict() since this method is based on a stochastic simulation.

To get reproducible results between predict calls you can use set.seed().

An example based on ?bnlearn::predict.bn.fit :

library(bnlearn)  

training = bn.fit(model2network("[A][B][E][G][C|A:B][D|B][F|A:D:E:G]"),
           gaussian.test[1:2000, ])
test = gaussian.test[2001:nrow(gaussian.test), ]

# run without setting the seed for each individual predict call
set.seed(75537919)
predict(training, node = "F", data = test,  method = "bayes-lw")[1]
# [1] 20.48767
predict(training, node = "F", data = test,  method = "bayes-lw")[1]
# [1] 20.51471

And to make reproducible use set.seed before each predict call

set.seed(75537919)
p1 <- predict(training, node = "F", data = test,  method = "bayes-lw")

set.seed(75537919)
p2 <- predict(training, node = "F", data = test,  method = "bayes-lw")

all.equal(p1, p2)
# [1] TRUE