Bayesian Beta regression Model -- Error in jags: Invalid parent value - r

I'm trying to run a Bayesian pooled model in jags through R and getting an error message
I found from people who have encountered similar problems that it could be triggered by values of the priors, negative value, log of negative, syntax errors etc. I have eliminated all of these but the error persists.
## just for the prediction
pred.jac <- seq(min(test.bayes$Latitude), max(test.bayes$Latitude), 10)
data = list(
jac = test.bayes$Jaccard,
lat = test.bayes$Latitude,
pred.jac = pred.jac)
inits = list(
list(alpha = 1, beta = 2.5, sigma = 50),
list(alpha = 2, beta = 1.5, sigma = 20),
list(alpha = 3, beta = 0.75, sigma = 10))
{
sink("BetaPooledJAGS.R")
cat("
model{
# priors
alpha ~ dnorm(0, 0.0001)
beta ~ dnorm(0, 0.0001)
sigma ~ dunif(0, 10)
# likelihood
for (i in 1:length(jac)) {
mu[i] <- alpha + beta * lat[i]
a[i] <- ((1 - mu[i]) / (sigma^2) - 1 / mu[i]) * mu[i]^2
b[i] <- alpha * (1 / mu[i] - 1)
jac[i] ~ dbeta(a[i], b[i])
}
# predicted jaccard as derived quantities
for (i in 1:length(pred.jac)) {
mu_pred[i] <- alpha + beta * lat[i]
mu_pred1[i] <- exp(mu_pred[i])
}
}
",fill = TRUE)
sink()
}
n.adapt = 3000
n.update = 5000
n.iter = 5000
jm.pooled = jags.model(file="BetaPooledJAGS.R", data = data, n.adapt = n.adapt, inits = inits, n.chains = length(inits))
When I run the code, I get the error below:
Error in jags.model(file = "BetaPooledJAGS.R", data = data, n.adapt = n.adapt, : Error in node jac[1] Invalid parent values
Here's the link to a subset of my data.
https://fil.email/IuwgYhKs

You're getting negative values for b with those initials if lat is positive, and b must be > 0 in a beta distribution, in JAGS, and more generally.
E.g. using initials from inits[[1]]:
mu = 1 + 2.5*lat
assuming lat is positive, then mu > 1
b = 1 * (1/mu-1)
And 1/mu < 1 if mu>1, so 1/mu - 1 < 0.
Therefore
b = 1*-ve so b<0

Related

JAGS mixture of normals with regression for the mean of the normals

I'm working on a dataset where the target variable y is likely distributed as a mixture of normals. The data is the score difference between two teams in an fps game, and my objective is to predict which team will win.
To do so I have 4 variables:
abilityA: the mean of the ranks of players in team A
abilityB: the mean of the ranks of players in team B
mapA: the mean of the kda (kills\deaths\assists) of the players of team A in that particular map
mapB: the mean of the kda (kills\deaths\assists) of the players of team B in that particular map
My JAGS code is the following:
# MODEL SPECIFICATION
model {
# Likelihood:
for( i in 1 : N ) {
Y[i] ~ dnorm(mu[z[i]], precision)
mu[z[i]] = b0 + b1*abilityA[i] + b2*mapA[i] - (b3 + b4*abilityB[i] + b5*mapB[i])
z[i] ~ dcat( omega )
}
#Priors
b0 ~ dnorm(0, 0.5)
b1 ~ dnorm(0, 0.5)
b2 ~ dnorm(0, 0.5)
b3 ~ dnorm(0, 0.5)
b4 ~ dnorm(0, 0.5)
b5 ~ dnorm(0, 0.5)
precision ~ dgamma( 0.01 , 0.01 )
sd_n = sqrt(1/precision)
omega ~ ddirch( c(1,1,1) )
}
...but I get the following error:
Error in jags.model(model.file, data = data, inits = init.values, n.chains = n.chains, :
RUNTIME ERROR:
Compilation error on line 11.
Unknown variable z
Either supply values for this variable with the data
or define it on the left hand side of a relation.
Reproducible example
With the following R code the error is reproducible
library(readr)
library(dplyr)
library(MASS)
library(R2jags)
library(VGAM)
library(mixtools)
curve(dnormm(x, p = c(0.3,0.7),
mu = c(-2,3),
sigma = c(1.3,1.3)), from = -10, to = 10, ylab = "Mixture",
lwd = 3, col = "darkgreen")
data.mixture <- list( Y = rnormm(1000, p = c(0.3,0.7), mu = c(-2,3), sigma = c(1.3,1.3)),
N = 1000
)
parameters <- c("sd_n")
iters = 1000
dugongjags = jags(data=data.mixture,
parameters.to.save=parameters,
model.file="./temp.txt",
n.chains=1,
n.iter=iters,
n.thin = 1, quiet = T)
This is jags code to save in a file called temp.txt
# MODEL SPECIFICATION
model {
# Likelihood:
for( i in 1 : N ) {
Y[i] ~ dnorm(mu[z[i]], precision)
mu[z[i]] = b
z[i] ~ dcat( omega )
}
#Priors
b ~ dnorm(0,0.5)
precision ~ dgamma( 0.01 , 0.01 )
sd_n = sqrt(1/precision)
omega ~ ddirch( c(1,1,1) )
}
I referred to this site to build the model. The thing is that in the following examples the means of the normals (mu[i]) is set with the prior, but is not possible in my case because of the dependency on the data (abilityA, mapA, ...).
http://doingbayesiandataanalysis.blogspot.com/2012/06/mixture-of-normal-distributions.html
https://www.coursera.org/lecture/mcmc-bayesian-statistics/mixture-model-in-jags-KDEVZ
Any idea?

Compilation Error in jags.model: Runtime Error: Index out of range while running linear mixed model

I am trying to run linear mixed model in JAGS in R.
I am trying to see influence of year as a random factor on speciesTotal.
My code is:
data_glmm<-read.csv("data_bbs_11_19.csv")
Nyear<-length(levels(as.factor(data_glmm$Year)))
Nyear<-9
jagsData_glmm<-with(data_glmm,
list(SpeciesTotal=SpeciesTotal,
StopTotal=StopTotal,
Stratum=Stratum,
Year=Year, N=length(SpeciesTotal), Nyear=Nyear))
lm1_jags <- function() {
for (i in 1:N){
SpeciesTotal[i] ~ dnorm(mu[i], tau) # tau is precision (1 / variance)
mu[i] <- alpha + a[Year[i]] + beta * StopTotal[i] # Random intercept for year
}
# Priors:
alpha ~ dnorm(0, 0.01) # intercept
sigma_a ~ dunif(0, 100) # standard deviation of random effect (variance between year)
tau_a <- 1 / (sigma_a * sigma_a) # convert to precision
for (j in 1:9){
a[j] ~ dnorm(0, tau_a) # random intercept for each year
}
beta ~ dnorm(0, 0.01) # slope
sigma ~ dunif(0, 100) # standard deviation of fixed effect (variance within year)
tau <- 1 / (sigma * sigma) # convert to precision
}
init_values <- function(){
list(alpha = rnorm(1), sigma_a = runif(1), beta = rnorm(1), sigma = runif(1))
}
params <- c("alpha", "beta", "sigma", "sigma_a")
fit_lm3 <- jags(data = jagsData_glmm, inits = init_values, parameters.to.save = params, model.file = lm1_jags, n.chains = 3, n.iter = 20000, n.burnin = 5000, n.thin = 10, DIC = F)
While running this code, I am getting following error:
Error in jags.model(model.file, data = data, inits = init.values, n.chains = n.chains, :
RUNTIME ERROR:
Compilation error on line 5.
Index out of range taking subset of a
Any suggestion would be really appreciated.

Model MLE finite values needed

I am trying to use mle to find the conditions of my model fitted to some data however I am getting the error L-BFGS-B needs finite values of 'fn'.
I am not really sure how to find where there are the non-finite values
sir.model2 = function(t, x, params){
# extract the state variables
S = x[1]
I = x[2]
R = x[3]
# extract the parameters
if(t<params['Time']){
beta = params['beta.1']
}else{
beta = params['beta.2']
}
gamma = params['gamma']
# compute the derivatives
dSdt = -beta * S * I
dIdt = beta * S * I - gamma * I
dRdt = gamma * I
# return the computed derivatives
list(c(dSdt, dIdt, dRdt))
}
# define the negative log likelihood function
NLL2 = function(beta.1,beta.2,time, gamma, I.init){
# specify the parameter values
params = c(beta.1 = beta.1,beta.2=beta.2,Time=time, gamma = gamma)
# specify the model's initial conditions
xstart = c(S = 1-I.init, I = I.init, R = 0)
# solve the differential equations
out = ode(func = sir.model2, y = xstart, times = times, parms = params)
out=as.data.frame(out)
out$beta[out$time<params['Time']]<-params['beta.1']
out$beta[out$time>=params['Time']]<-params['beta.2']
# calculate the negative log likelihood
-sum(dpois(data.edu$Cases, out$beta*out$S*out$I* N.edu, log=T))
}
m = mle(minuslogl = NLL2,
method="L-BFGS-B",
start = list(beta.1 = 1.5 * 1 / 7,beta.2 = 1.5 * 1 / 7,time=20, gamma = 1 / 7, I.init = 0.0001),
lower = list(beta.1 = .1, beta.2 =.1,time=.1 gamma = 1e-3, I.init = 1e-3),
upper = list(beta.1 = 5, beta.2 =5,time=107 gamma =5, I.init = 1-1e-3)
)
coef(m)

R JAGS: Dimension mismatch

I am trying to run a model in JAGS but I got the following error:
Error in jags.model(model.file, data = data, inits = init.values, n.chains = n.chains, :
RUNTIME ERROR:
Cannot insert node into m[1]. Dimension mismatch
The model I specified is
model = "model
{
for (i in 1:N) {
z[i] ~ dnorm(m[i],tau)
m[i] <- beta0 + beta1*x + beta2*y
}
beta0 ~ dnorm(0.0,1.0E-3)
beta1 ~ dnorm(0.0,1.0E-3)
beta2 ~ dnorm(0.0,1.0E-3)
tau ~ dgamma(0.01,0.01)
}"
Then I specify the data and the initial values. Finally, I run the model.
data = list(z = wolfcamp$data, x = wolfcamp$coords[,1], y = wolfcamp$coords[,2], N = length(wolfcamp$data))
parameters=c("beta0","beta1","beta2","tau")
init1 = list(beta0 = 0, beta1 = 0, beta2 = 0, tau = 0)
init2 = list(beta0 = 1, beta1 = 1, beta2 = 1, tau = 1)
initial.values=list(init1, init2)
model1=jags(data=data, inits=initial.values,
parameters.to.save=parameters,
model.file=textConnection(model),
n.chains=2,
n.burnin=1000,
n.iter=11000)
Can you help me? Do you know why I get this error?
Thanks in advance.
It looks like you are not indexing through the vectors x and y, which causes a dimension mismatch.
Change this line:
m[i] <- beta0 + beta1*x + beta2*y
to this:
m[i] <- beta0 + beta1*x[i] + beta2*y[i]
and you should be good to go (so long as x and y are of length N)

How to fit a model with and without an interaction in a JAGS regression model

I'm using this tutorial to wrap my head around JAGS code. In the section 'Same model with an additional categorical predictor' it states that "This model includes an interaction between sex and body length". How can I remove this so that there's no interaction?
Here's the full setup and model in R and JAGS.
First the data:
set.seed(42)
samplesize <- 50 # Larger sample size because we're fitting a more complex model
b_length <- sort(rnorm(samplesize)) # Body length
sex <- sample(c(0, 1), size = samplesize, replace = T) # Sex (0: female, 1: male)
int_true_f <- 30 # Intercept of females
int_true_m_diff <- 5 # Difference between intercepts of males and females
slope_true_f <- 10 # Slope of females
slope_true_m_diff <- -3 # Difference between slopes of males and females
mu <- int_true_f + sex * int_true_m_diff + (slope_true_f + sex * slope_true_m_diff) * b_length # True means
sigma <- 5 # True standard deviation of normal distributions
b_mass <- rnorm(samplesize, mean = mu, sd = sigma) # Body mass (response variable)
# Combine into a data frame:
snakes2 <- data.frame(b_length = b_length, b_mass = b_mass, sex = sex)
head(snakes2)
jagsdata_s2 <- with(snakes2, list(b_mass = b_mass, b_length = b_length, sex = sex, N = length(b_mass)))
JAGS code:
lm2_jags <- function(){
# Likelihood:
for (i in 1:N){
b_mass[i] ~ dnorm(mu[i], tau) # tau is precision (1 / variance)
mu[i] <- alpha[1] + sex[i] * alpha[2] + (beta[1] + beta[2] * sex[i]) * b_length[i]
}
# Priors:
for (i in 1:2){
alpha[i] ~ dnorm(0, 0.01)
beta[i] ~ dnorm(0, 0.01)
}
sigma ~ dunif(0, 100)
tau <- 1 / (sigma * sigma)
}
Initial values and run:
init_values <- function(){
list(alpha = rnorm(2), beta = rnorm(2), sigma = runif(1))
}
params <- c("alpha", "beta", "sigma")
fit_lm2 <- jags(data = jagsdata_s2, inits = init_values, parameters.to.save = params, model.file = lm2_jags,
n.chains = 3, n.iter = 12000, n.burnin = 2000, n.thin = 10, DIC = F)
The interaction term is contained in your calculation of mu. The sex changes how the formula between body length and body mass is defined, via the slope terms. To build a model where sex and body length are treated as independent with respect to how they affect body mass, you could do something like this:
mu <- int_true_f + (sex * int_true_m_diff) + b_length
The JAGS code would then become
lm2_jags <- function(){
# Likelihood:
for (i in 1:N){
b_mass[i] ~ dnorm(mu[i], tau) # tau is precision (1 / variance)
mu[i] <- alpha[1] + (sex[i] * alpha[2]) + (b_length[i] * alpha[3])
}
# Priors:
for (i in 1:3){
alpha[i] ~ dnorm(0, 0.01)
}
sigma ~ dunif(0, 100)
tau <- 1 / (sigma * sigma)
}

Resources