Generated Quantities Error

Hello. i’m trying to use generated quantities to make posterior predictions on the data. I keep getting errors similar to the ones below and I’m not sure what i’m doing wrong.

reinstatement_model = """
data {
    int<lower=0> n; // number policy term years
    int<lower=0> NonCatcvrcnt[n]; // claims
    int<lower=0, upper = 1> alertflag[n]; //alert flag
}

parameters {
    real<lower=0> mu;
    real beta;

}

model {
       mu ~ normal(0,3);
       beta ~ normal(0,1);
       NonCatcvrcnt ~ poisson_log(mu + alertflag[n]*beta);
}

generated quantities {
    real y_hat;
    
    for (i in 1:n){
            y_hat[i] = poisson_rng(mu+alertflag*beta[i]);
            }
    }

"""

This is the error I’m getting.

ValueError: Failed to parse Stan model 'anon_model_d3fd60c562818cb28d1edea0f2095bc8'. Error message:
SYNTAX ERROR, MESSAGE(S) FROM PARSER:
Too many indexes, expression dimensions=0, indexes found=1
 error in 'unknown file name' at line 24, column 55
  -------------------------------------------------
    22:     
    23:     for (i in 1:n){
    24:             y_hat[i] = poisson_rng(mu+alertflag*beta[i]);
                                                              ^
    25:             }
  -------------------------------------------------

beta is just a single number (i.e. a scalar), but in the generated quantities you’ve attempted to index it with beta[i].

Thanks. I fixed to this:

generated quantities {
    real y_hat[n];
    
    for (i in 1:n){
            y_hat[i] = poisson_rng(mu+alertflag[n]*beta);
            }
    }

It compiled but the sampling gives a RuntimeError: std::bad_alloc error message.

This conversation is converging over with Analyzing the posterior prediction samples - #6 by Jordan_Howell

1 Like