Trouble with Stan for new stan user

I am using stan to run MCMC for a Gaussian Mixture model. But I am facing a bug, the stan code I use is:

data {
  int<lower=0> N;
  int<lower=0> K;
  int<lower=0> D;
  vector[D] x[N];
transformed data {
  vector<lower=0>[K] alpha0_vec;
  for (k in 1:K) {
    alpha0_vec[k] <- 1.0/K;
parameters {
  simplex[K] theta;
  vector[D] mu[K];
  vector<lower=0>[D] sigma[K];

model {
  theta ~ dirichlet(alpha0_vec);
  for (k in 1:K){
    mu[k] ~ normal(0.0, 1.0/sigma[k]);
    sigma[k] ~ inv_gamma(1.0, 1.0);
  for (n in 1:N) {
    real ps[K];
    for (k in 1:K){
      ps[k] <- log(theta[k]) + normal_log(x[n], mu[k], sigma[k]);

When I run it in r using code:

data<-read.csv(“data.csv”,header = T)
gmm_data = list(D = 768,
N = 500,
M = 6,
x = t(data))

fit <- stan(file = ‘test.stan’, data = gmm_data, chains = 2, iter = 10)

It gives me the bug:


Info (non-fatal): assignment operator <- deprecated in the Stan language; use = instead.
No matches for:

real / vector

Available argument signatures for operator/:

int / int
real / real
vector / real
row vector / real
matrix / real

Expression is ill formed
error in ‘model4675c183ae8_GMM’ at line 22, column 37

20:   theta ~ dirichlet(alpha0_vec);
21:   for (k in 1:K){
22:     mu[k] ~ normal(0.0, 1.0/sigma[k]);
23:     sigma[k] ~ inv_gamma(1.0, 1.0);

How could I fix this?

Is sigma a precision parameter in your model?

I am also fairly new to Stan, so just out of curiosity: what does K do in the following line?


this line declares an array sigma of size K, where each entry in the array is a vector with size D

1 Like

I think you need pointwise division in the line where you calculate/“sample” \mu_k:

rep_vector(1.0, D) ./ sigma[k].

Does that work?

1 Like

Yes, it is precision parameter.

@Max_Mantei’s solution should work. BTW: in Stan you might find it easier to parameterize with the standard deviation and then generate the precision as a generated quantity if needed.