Hi all

I work a Latent Class model following the post LCA previous post. The model works fine and identify the parameters estimates that make sense, replicating the example from LCA ML , with the respective data set

The issue that I am stuck now is on how to define the log_lik object in the generated quantities block. This because I want to use LOO to compare models to find the best number of classes.

As the element define target += log_sum_exp(ps) has size C (number of classes) instead of the size of the data set ( matrix[J, I] y)

Thanks for any guidance

```
data {
int<lower=1> I; // number of items
int<lower=1> J; // number of respondents
matrix[J, I] y; // score for obs n
int<lower=1> C; // # of attribute profiles (latent classes)
}
parameters {
simplex[C] nu;
// average intercept and main effect
real mean_intercept;
real mean_maineffect;
// item level deviations from average effects
real dev_intercept[I];
real dev_maineffect[I];
}
transformed parameters {
matrix[I,C] pi; // Probability of correct response for each class on each item
vector[C] log_nu = log(nu);
real intercept[I];
real maineffect[I];
vector[I] master_pi;
vector[I] nonmaster_pi;
for (i in 1:I) {
intercept[i] = mean_intercept + dev_intercept[i];
maineffect[i] = mean_maineffect + dev_maineffect[i];
nonmaster_pi[i] = inv_logit(intercept[i]);
master_pi[i] = inv_logit(intercept[i] + maineffect[i]);
}
// Probability of correct response for each class on each item
for (c in 1:C) {
for (i in 1:I) {
pi[i,c] = master_pi[i]^(c - 1) * nonmaster_pi[i]^(1 - (c - 1));
}
}
}
model{
real ps[C];
real log_items[I];
// Priors
mean_intercept ~ normal(0, 5);
mean_maineffect ~ normal(0, 5);
dev_intercept ~ normal(0, 3);
dev_maineffect ~ normal(0, 3);
// Define model
for (j in 1:J) {
for (c in 1:C) {
for (i in 1:I) {
log_items[i] = y[j,i] * log(pi[i,c]) + (1 - y[j,i]) * log(1 - pi[i,c]);
}
ps[c] = log_nu[c] + sum(log_items);
}
target += log_sum_exp(ps);
}
}
generated quantities {
matrix[J,C] prob_resp_class; // posterior probabilities of respondent j being in latent class c
real log_items[I];
row_vector[C] prob_joint;
for (j in 1:J){
for (c in 1:C){
for (i in 1:I){
log_items[i] = y[j,i] * log(pi[i,c]) + (1 - y[j,i]) * log(1 - pi[i,c]);
}
prob_joint[c] = nu[c] * exp(sum(log_items));
}
prob_resp_class[j] = prob_joint/sum(prob_joint);
}
}
```