I am trying to generate predictions for a Dirichlet-multinomial distribution in Stan (for a saved custom model).
When I save this code, I get an error on the dirichlet_rng(alphas)
because I am sending dirichlet_rng(vector[ ])
and not dirichlet_rng(vector)
. What should my code look like? Would it be better to do a simple loop across all posteriors?
// This is testing implementation of a Dirichlet-multinomial model
functions {
}
data{
// Structural
int<lower=1> n_obs; // Number of observations
int<lower=2> n_cat; // Number of categories
// Population
vector[n_obs] x_new; // Input variable x
// Posteriors
int<lower = 1> n_iter; // Number of iterations for my samples
// Population effects parameters
real b_group_1_intercept[n_iter];
real b_group_1_x[n_iter];
real b_group_2_intercept[n_iter];
real b_group_2_x[n_iter];
real b_group_3_intercept[n_iter];
real b_group_3_x[n_iter];
}
transformed data{
vector[n_cat] alphas[n_iter * n_obs] ;
//vector[n_cat] responses[n_iter * n_obs] ;
for(iter in 1:n_iter)
{
for(obs in 1:n_obs)
{
// Linear Predictors for each group
real linear_predictor_group_1 = b_group_1_intercept[iter] + b_group_1_x[iter] * x_new[obs];
real linear_predictor_group_2 = b_group_2_intercept[iter] + b_group_2_x[iter] * x_new[obs];
real linear_predictor_group_3 = b_group_3_intercept[iter] + b_group_3_x[iter] * x_new[obs];
// Apply the link function to each group's linear predictor
real alpha_group_1 = exp(linear_predictor_group_1);
real alpha_group_2 = exp(linear_predictor_group_2);
real alpha_group_3 = exp(linear_predictor_group_3);
// Turn alphas into a vector
alphas[(obs-1) * iter + obs] = transpose([alpha_group_1, alpha_group_2, alpha_group_3]);
}
}
}
generated quantities{
vector[n_cat] responses[n_obs*n_iter]; // Response array
// Get final part
responses = multinomial_rng(dirichlet_rng(alphas);
}