Initialization error

My stan code is

data {
int<lower = 0> N; //total observations

//num of fixed effects
int<lower = 0> Nx; //mean model
int<lower = 0> Ng; //var model

//num of random effects
int<lower = 0> Nz; //both mean and var model

real y[N]; //observed data

//design matrices for fixed effects
matrix[N, Nx] x; //mean model
matrix[N, Ng] g; //var model

//design matrices for random effects
matrix<lower = 0, upper = 1>[N, Nz] z;
parameters {
//mean model
vector[Nx] beta; //fixed effects
vector[Nz] muAug; //random effects
real alphaMu; //working variable
real<lower = 0> invTauMuAugSq; //variance of random effects

//var model

vector[Ng] gamma; //fixed effects
vector[Nz] sigmaAug; //random effects
real alphaSigma; //working variable
real<lower = 0> invTauSigmaAugSq; //variance of random effects
transformed parameters {
vector[N] mu;
vector[Nz] u;
vector[N] logSigma;
vector[Nz] b;
vector<lower = 0>[N] sigma;

//mean model
mu = multiply(x, beta) + multiply(z, u);
u = alphaMu * muAug; //original random effects
//var model
logSigma = multiply(g, gamma) + multiply(z, b);
b = alphaSigma * sigmaAug; //original random effects
sigma = exp(logSigma);

model {
for (i in 1:N) {
y[i] ~ normal(mu[i], sigma[i]);

//priors for mean model
beta ~ normal(0, 100); //fixed effects
muAug ~ normal(0, 1/sqrt(invTauMuAugSq)); //augmented variable
invTauMuAugSq ~ gamma(2.5, 2);
alphaMu ~ normal(0, sqrt(5));

//priors for var model
gamma ~ normal(0, 100); //fixed effects
sigmaAug ~ normal(0, 1/sqrt(invTauSigmaAugSq)); //augmented variable
invTauSigmaAugSq ~ gamma(2.5, 2);
alphaSigma ~ normal(0, sqrt(5));


I got a message that

Initialization between (-2, 2) failed after 100 attempts.
Try specifying initial values, reducing ranges of constrained values, or reparameterizing the model.
[1] “Error in sampler$call_sampler(args_list[[i]]) : Initialization failed.”

It sounds like there should be some mistakes in my code but I cannot find it.
Can anyone find what the problem is?

u being used before it is defined.

how can I fix it then?

Switch the order of these rows; you can’t use u on right hand side before defining it on left hand side:


above the line that defines mu. Same thing with b. It should be

transformed parameters {
  vector[Nz] u = alphaMu * muAug;
  vector[N] mu = x * beta + z * u;
  vector[Nz] b = alphaSigma * sigmaAug;
  vector[N] logSigma = g * gamma + z * b;
  vector[N] sigma = exp(logSigma);

Thanks a lot! It works perfectly now.

1 Like