Difference between ~ and target+=

Dear all,

I am learning how to specify a model in the model section of the stan code. If I want a hierarchy model of normal.

\mu \sim N(-2, 1)
\sigma2 \sim inv\_gamma (2,2)
X_n \sim N(\mu, \sigma^2)

Do I need to specify both “~” and “target +=” in my model section of stan code?

mu ~ normal(-2, 1);
sigma2 ~ inv_gamma(2, 2);
for(n in 1:N){
target += normal_lpdf(X[n]| mu, sigma2);
}
target += normal_lpdf(mu| -2, 1);
target += inv_gamma_lpdf(sigma2| 2, 2);

i.e do I need both

mu ~ normal(-2, 1);
sigma2 ~ inv_gamma(2, 2);

and

target += normal_lpdf(mu| -2, 1);
target += inv_gamma_lpdf(sigma2| 2, 2);

mu ~ normal(-2, 1); and target += normal_lpdf(mu| -2, 1); are two different notations to increment the total log probability used by Stan’s algorithm. So you don’t need both, you need to choose one. See here for more information.

4 Likes