Hi all,
Hope you all had a great weekend.
I am wondering if there is an easier way in nimble to extract cluster weights and within-cluster parameters that are aligned. Take the following simple nonparametric mixture of products of Bernoullis as an example:
# Nimble model code
bcode <- nimbleCode({
for(i in 1:N) {
for(j in 1:J) {
y[i, j] ~ dbern(ip[z[i], j])
}
}
for(i in 1:N) {
for(j in 1:J) {
ip[i, j] ~ dbeta(shape1 = 2, shape2 = 5)
}
}
z[1:N] ~ dCRP(conc = alpha, size = N)
alpha ~ dgamma(shape = 2, rate = 2)
})
For the second iteration, I can extract the cluster sizes and within-cluster parameter estimates as follows:
table(zSamples[2, ]) # cluster sizes
1 2 3 4 5
31 18 363 74 14
For each iteration, the within-cluster parameter estimates can be reorganized into a J (number of variables) by K (number of clusters) matrix:
ip.m <- matrix(ipSamples[2,], nrow=J, ncol=N, byrow=T) # J = 5 in this case
Then, for the first variable:
table(ip.m[1, zSamples[2,]])
0.03230 0.29045 0.37660 0.51149 0.87088
74 18 14 31 363
For the second variable:
table(ip.m[2, zSamples[2,]])
0.08561 0.51955 0.56262 0.61106 0.88537
74 14 18 31 363
The two sets of parameter estimates are not aligned if they are extracted using the table function. The ideal output I expect is as follows:
1 2 3 4 5
31 18 363 74 14
0.51149 0.29045 0.87088 0.03230 0.37660
31 18 363 74 14
0.61106 0.56262 0.88537 0.08561 0.51955
31 18 363 74 14
My way to solve this issue is cumbersome. But when it comes to a more complecated model, say the variables are polytomous with different number of categories, I do not know how to solve it:
# Nimble model
pcode <- nimbleCode({
for(i in 1:N) {
for(j in 1:J) {
y[i, j] ~ dcat(ip[z[i], j, 1:C[j]])
}
}
for(i in 1:N) {
for(j in 1:J) {
ip[i, j, 1:C[j]] ~ ddirch(beta[1:C[j]])
}
}
z[1:N] ~ dCRP(conc = alpha, size = N)
alpha ~ dgamma(shape = 2, rate = 2)
})
The code for the binary case is attached. Thank you very much.
Best,
Chris