Random variable is nan

Hi,

library(ggplot2)
When running the model below I get an error:

Initialization between (-2, 2) failed after 100 attempts.

Can you advise how to resolve?

Thank you.

library(rstan)
set.seed(4)
N= 100
x = sample(1:100,N2, replace = T)
y = c(x[1:100]
.4+rnorm(100,8,7),3+x[101:200]*.9+rnorm(100,2,9))
g = rep(c(1,2), each = N)
data =data.frame(x=x, y = y,group = g)
ggplot(data , aes(x=x, y = y,group=g))+geom_line()+geom_point()
input = list( N= length(g), N_group = 2, group = g, Y=y, X=log(x))
fit = stan(file = “exp.stan”,data=input,seed=1,chains = 1 ,control =list(adapt_delta = .99))

params = rstan::extract(fit)
names(params)
print(summary(fit))
y = y
pred =params$ypp
ppc_stat_grouped(y, pred, group = g, stat = “median”)
ppc_stat_grouped(y, pred, group = g, stat = “mean”)

data{
int<lower=0> N;
int<lower =1> N_group;
int<lower=1,upper = N_group> group[N];
real X[N];
real Y[N];
}
parameters{
vector[N_group] a;
real a_mu;
real<lower=0> a_s;

vector[N_group] b;
real b_mu;
real<lower=0> b_s;

vector[N] mu;

vector[N] sigma0;
vector[N] sigma_x;
}

transformed parameters{
vector[N] sigma;
for(n in 1:N){
sigma[n] = exp(sigma0[n]+ X[n]*sigma_x[n]);
}
}

model{
b_mu~normal(0,2);
b_s~normal(2,2);
b~normal(b_mu,b_s);

a_mu~normal(0,1);
a_s~normal(2,2);
a~normal(a_mu,a_s);

sigma0~normal(0,.2);
sigma_x~normal(-5,1);

for(n in 1:N){
Y[n] ~ normal( a[group[n]]+X[n]*b[group[n]],sigma[n]);
}

}

generated quantities{
vector[N] ypp;
for(n in 1:N){
ypp[n] = normal_rng( a[group[n]]+X[n]*b[group[n]],sigma[n]);
}
}

Call stan with init_r = something less than 2 in order to reduce the dispersion of the starting values.

I think the issue is this line:

for(n in 1:N){
vector[N] y;
y[n] ~ normal( a[group[n]]+X[n]*b[group[n]],sigma[n]);
}

Here you’ve declared an uninitialised vector y (which defaults to nan for each entry), and then tried to model it. I can see that you’ve passed Y[N] as data, should this instead be:

for(n in 1:N){
Y[n] ~ normal( a[group[n]]+X[n]*b[group[n]],sigma[n]);
}
1 Like