Search code examples
rbayesianbayesian-networksrjags

Generate predictions using JAGS


I have a parametrised linear Gaussian Bayesian network and I am trying to make predictions on the model using rjags. I can do this for one observation but do not know how to pass multiple observations. Here is an example

library(rjags)
library(coda)

Initial model

mod <- textConnection("model {
  mpg.hat <- (34.96055404 - 3.35082533* wt - 0.01772474* disp)
  wt      ~ dnorm(3.21725, 1/0.9784574^2)
  disp    ~ dnorm(230.7219, 1/123.9387^2)
  mpg     ~ dnorm(mpg.hat, 1/2.916555^2)
}")

# Evaluate and get prediction when wt=1 and disp is hidden
m <- jags.model(mod, n.chains = 1, n.adapt = 1000, data=list(wt=1, disp=NA))
update(m, 10000)
cs <- coda.samples(m,  c("mpg", "wt", "disp"),  1e5)
summary(cs)

This works as expected, however, I have multiple rows of data that I want to generate predictions for. If I try to extend the data=list( argument to include more rows it throws an error. So after rerunning the model text, and the following command I get the error

m <- jags.model(mod, n.chains = 1, n.adapt = 1000, data=list(wt=1:2, disp=1:2))

Error in jags.model(mod, n.chains = 1, n.adapt = 1000, data = list(wt = 1:2, :
Error in node dnorm(230.722,(a1/(a123.939^2)))
Length mismatch in Node::setValue

How do I extend this to more observations?


Solution

  • You need to iterate through the rows:

    mod <- textConnection("model {
      for (n in 1:N) {
        mpg.hat[n] <- (34.96055404 - 3.35082533* wt[n] - 0.01772474* disp[n])
        mpg[n]     ~ dnorm(mpg.hat[n], 1/2.916555^2)
        wt[n]      ~ dnorm(3.21725, 1/0.9784574^2)
        disp[n]    ~ dnorm(230.7219, 1/123.9387^2)
      }
    }")
    

    Note you will need to add N to your data list as well:

    data = list(N = 1, wt = 1, disp = NA)
    data = list(N = 2, wt = 1:2, disp = 1:2)