RStan - Problem in stan_file model code - Variational Bayes - r

I am trying to do Variational inference, so that I can get the best approximating distribution with respect to the target distribution: a Normal-Inverse-Wishart.
Normal-Inverse-Wishart distribution
However when I compile the stan file with the model code it gives the error:
Error in stanc(file = file, model_code = model_code, model_name = ?>model_name, : 0
Syntax error in 'string', line 16, column 14 to column 15, parsing >error:
Expected "generated quantities {" or end of file after end of model >block.
I have tried to investigate what this is referring to but I require some help. My R code is:
stan_file <- "RStan VI model.stan"
stan_model <- rstan::stan_model(file = stan_file) // Error occurs at this line
The RStan file model code is:
data {
int<lower=1> N; // number of assets
real<lower=0> nu0; // prior confidence for sigma
matrix[N, N] sigma_0; // prior sigma
real<lower=0> T0; // prior confidence for mu
vector[N] mu0; // prior mu
}
parameters {
matrix[N, N] sigma;
vector[N] mu;
}
transformed parameters {
matrix[N, N] a;
matrix[N, N] b;
a = sigma0*nu0;
b = sigma/T0;
}
model {
target += inv_wishart_lpdf(sigma | nu0, a);
target += normal_lpdf(mu | mu0, b);
}
I even tried changing the last section of the model code to:
model {
sigma ~ inv_wishart(nu0, a);
mu ~ normal(mu0, b);
}
But still same error. Would anyone know what the error is and how I can fix it?
Many thanks.
Best,
Nihaar

Related

Need to fix Stan code for the generalized pareto distribution to take in real arguments rather than vectors

I am using the functions defined here: Extreme value analysis and user defined probability functions in Stan for modeling the data with a generalized pareto distribution, but my problem is that my model is in a for-loop and expects three real valued arguments, whereas, the gpd functions assume a vector, real, real argument.
I’m not so sure that my model chunk is so amenable to being vectorized, and so I was thinking I would need to have the gpd functions take in real valued arguments (but maybe I’m wrong).
I’d appreciate any help with switching the code around to achieve this. Here is my stan code
functions {
real gpareto_lpdf(vector y, real k, real sigma) {
// generalised Pareto log pdf
int N = rows(y);
real inv_k = inv(k);
if (k<0 && max(y)/sigma > -inv_k)
reject("k<0 and max(y)/sigma > -1/k; found k, sigma =", k, sigma)
if (sigma<=0)
reject("sigma<=0; found sigma =", sigma)
if (fabs(k) > 1e-15)
return -(1+inv_k)*sum(log1p((y) * (k/sigma))) -N*log(sigma);
else
return -sum(y)/sigma -N*log(sigma); // limit k->0
}
real gpareto_lcdf(vector y, real k, real sigma) {
// generalised Pareto log cdf
real inv_k = inv(k);
if (k<0 && max(y)/sigma > -inv_k)
reject("k<0 and max(y)/sigma > -1/k; found k, sigma =", k, sigma)
if (sigma<=0)
reject("sigma<=0; found sigma =", sigma)
if (fabs(k) > 1e-15)
return sum(log1m_exp((-inv_k)*(log1p((y) * (k/sigma)))));
else
return sum(log1m_exp(-(y)/sigma)); // limit k->0
}
}
data {
// the input data
int<lower = 1> n; // number of observations
real<lower = 0> value[n]; // value measurements
int<lower = 0, upper = 1> censored[n]; // vector of 0s and 1s
// parameters for the prior
real<lower = 0> a;
real<lower = 0> b;
}
parameters {
real k;
real sigma;
}
model {
// prior
k ~ gamma(a, b);
sigma ~ gamma(a,b);
// likelihood
for (i in 1:n) {
if (censored[i]) {
target += gpareto_lcdf(value[i] | k, sigma);
} else {
target += gpareto_lpdf(value[i] | k, sigma);
}
}
}
Here is how the log PDF could be adapted. This way, index arrays for subsetting y into censored and non-censored observations can be passed.
real cens_gpareto_lpdf(vector y, int[] cens, int[] no_cens, real k, real sigma) {
// generalised Pareto log pdf
int N = size(cens);
real inv_k = inv(k);
if (k<0 && max(y)/sigma > -inv_k)
reject("k<0 and max(y)/sigma > -1/k; found k, sigma =", k, sigma)
if (fabs(k) > 1e-15)
return -(1+inv_k)*sum(log1p((y[no_cens]) * (k/sigma))) -N*log(sigma) +
sum(log1m_exp((-inv_k)*(log1p((y[cens]) * (k/sigma)))));
else
return -sum(y[no_cens])/sigma -N*log(sigma) +
sum(log1m_exp(-(y[cens])/sigma));
}
Extend the data block: n_cens, n_not_cens, cens, and no_cens are values that need to supplied.
int<lower = 1> n; // total number of obs
int<lower = 1> n_cens; // number of censored obs
int<lower = 1> n_not_cens; // number of regular obs
int cens[n_cens]; // index set censored
int no_cens[n_not_cens]; // index set regular
vector<lower = 0>[n] value; // value measurements
Nonzero Parameters as suggested by gfgm:
parameters {
real<lower=0> k;
real<lower=0> sigma;
}
Rewrite the model block:
model {
// prior
k ~ gamma(a, b);
sigma ~ gamma(a,b);
// likelihood
value ~ cens_gpareto(cens, no_cens, k, sigma);
}
Disclaimer: I neither checked the formulas for sanity nor ran the model using test data. Just compiled via rstan::stan_model() which worked fine. gfgm's suggestion may be more convenient for post-processing / computing stuff in generated quantities etc. I'm not a Stan expert :-).
Edit:
Fixed divergence issue found by gfgm through simulation. The likelihood was ill-defined (N= rows(y) instead of N=size(cens). Runs fine now with gfgm's data (using set.seed(123) and rstan):
mean se_mean sd 2.5% 25% 50% 75% 97.5% n_eff Rhat
k 0.16 0.00 0.10 0.02 0.08 0.14 0.21 0.42 1687 1
sigma 0.90 0.00 0.12 0.67 0.82 0.90 0.99 1.16 1638 1
lp__ -106.15 0.03 1.08 -109.09 -106.56 -105.83 -105.38 -105.09 1343 1
You can get the model to accept a vector and avoid a for loop. In part you need to change the signature when you declare value but then also feed in as data the indices of the censored and uncensored observations.
I'm posting below code that runs on made up data, but the data I made up is just some random log-normal variates and not actual draws from a pareto so I have no idea if the model is recovering the parameters or what its coverage looks like. You'll probably want to do a bit of simulation based calibration to check the model.
The stan code:
functions {
real gpareto_lpdf(vector y, real k, real sigma) {
// generalised Pareto log pdf
int N = rows(y);
real inv_k = inv(k);
if (k<0 && max(y)/sigma > -inv_k)
reject("k<0 and max(y)/sigma > -1/k; found k, sigma =", k, sigma);
if (sigma<=0)
reject("sigma<=0; found sigma =", sigma);
if (fabs(k) > 1e-15)
return -(1+inv_k)*sum(log1p((y) * (k/sigma))) -N*log(sigma);
else
return -sum(y)/sigma -N*log(sigma); // limit k->0
}
real gpareto_lcdf(vector y, real k, real sigma) {
// generalised Pareto log cdf
real inv_k = inv(k);
if (k<0 && max(y)/sigma > -inv_k)
reject("k<0 and max(y)/sigma > -1/k; found k, sigma =", k, sigma);
if (sigma<=0)
reject("sigma<=0; found sigma =", sigma);
if (fabs(k) > 1e-15)
return sum(log1m_exp((-inv_k)*(log1p((y) * (k/sigma)))));
else
return sum(log1m_exp(-(y)/sigma)); // limit k->0
}
}
data {
// the input data
int<lower = 1> n; // number of observations
int<lower = 0> n_cens;
vector<lower = 0>[n] value; // value measurements
int<lower=1> cens_id[n_cens]; // the indices of censored observations
int<lower=1> nocens_id[n - n_cens]; // the indices of uncensored obs
// parameters for the prior
real<lower = 0> a;
real<lower = 0> b;
}
parameters {
real<lower=0> k;
real<lower=0> sigma;
}
model {
// prior
k ~ gamma(a, b);
sigma ~ gamma(a,b);
// likelihood
target += gpareto_lcdf(value[cens_id] | k, sigma);
target += gpareto_lpdf(value[nocens_id] | k, sigma);
}
This runs basically instantaneously on my mid-tier laptop using cmdstanr. You can run it with the R code
library(cmdstanr)
library(bayesplot)
gparet_mod <- cmdstan_model("gpareto_example.stan")
# make some fake data. This won't be correct and its
# no proper test of the capacity of the model to
# recover the parameters, just seeing if it runs
N <- 100
value <- rlnorm(N)
censored <- rbinom(N, 1, .5)
N_cens <- sum(censored)
cens_id <- which(censored == 1)
nocens_id <- which(censored == 0)
a <- b <- 2
dat <- list(n = N, n_cens = N_cens, value = value,
cens_id = cens_id, nocens_id = nocens_id,
a = a, b = b)
ests <- gparet_mod$sample(data = dat, parallel_chains = 2, chains = 2)
This produces what appear to be sane samples
ests$summary()
# A tibble: 3 × 10
variable mean median sd mad q5 q95 rhat ess_bulk ess_tail
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 lp__ -103. -103. 1.10 0.767 -105. -102. 1.00 750. 807.
2 k 0.316 0.296 0.135 0.131 0.128 0.557 1.00 665. 570.
3 sigma 0.691 0.685 0.113 0.110 0.511 0.887 1.00 772. 887.
And posterior distributions
mcmc_hist(ests$draws(variables = c("k", "sigma")))
I think the approach of Martin Arnold is a bit more elegant, but when I tried to get it to run on the same data the sampler broke down with divergences, so maybe I ported the model wrong or something needs tweaking.
Edit
Given the likelihood functions it makes more sense to constrain the parameters k and sigma to be positive. The model runs better and you'll get fewer error messages. I modified the stan code above to reflect this.

Writing a custom Probit function in Stan

I am trying to code a custom Probit function in Stan to improve my understanding of the Stan language and likelihoods. So far I've written the logarithm of the normal pdf but am receiving an error message that I've found to be unintelligible when I am trying to write the likelihood. What am I doing wrong?
Stan model
functions {
real normal_lpdf(real mu, real sigma) {
return -log(2 * pi()) / 2 - log(sigma)
- square(mu) / (2 * sigma^2);
}
real myprobit_lpdf(int y | real mu, real sigma) {
return normal_lpdf(mu, sigma)^y * (1 - normal_lpdf(mu, sigma))^(1-y);
}
}
data {
int N;
int y[N];
}
parameters {
real mu;
real<lower = 0> sigma;
}
model {
for (n in 1:N) {
target += myprobit_lpdf(y[n] | mu, sigma);
}
}
Error
PARSER EXPECTED:
Error in stanc(model_code = paste(program, collapse = "\n"), model_name = model_cppname, :
failed to parse Stan model 'Probit_lpdf' due to the above error.
R code to simulate data
## DESCRIPTION
# testing a Probit model
## DATA
N <- 2000
sigma <- 1
mu <- 0.3
u <- rnorm(N, 0, 2)
y.star <- rnorm(N, mu, sigma)
y <- ifelse(y.star > 0,1, 0)
data = list(
N = N,
y = y
)
## MODEL
out.stan <- stan("Probit_lpdf.stan",data = data, chains = 2, iter = 1000 )
The full error message is
SYNTAX ERROR, MESSAGE(S) FROM PARSER:
Probabilty functions with suffixes _lpdf, _lpmf, _lcdf, and _lccdf,
require a vertical bar (|) between the first two arguments.
error in 'model2a7252aef8cf_probit' at line 7, column 27
-------------------------------------------------
5: }
6: real myprobit_lpdf(real y, real mu, real sigma) {
7: return normal_lpdf(mu, sigma)^y * (1 - normal_lpdf(mu, sigma))^(1-y);
^
8: }
-------------------------------------------------
which is telling you that the normal_lpdf function excepts three inputs and a vertical bar separating the first from the second.
It is also not a good idea to give your function the same name as a function that is already in the Stan language, such as normal_lpdf.
But the functions you have written do not implement the log-likelihood of a probit model anyway. First, the standard deviation of the errors is not identified by the data, so you do not need sigma. Then, the correct expressions would be something like
real Phi_mu = Phi(mu);
real log_Phi_mu = log(Phi_mu);
real log1m_Phi_mu = log1m(Phi_mu);
for (n in 1:N)
target += y[n] == 1 ? log_Phi_mu : log1m_Phi_mu;
although that is just a slow way of doing
target += bernoulli_lpmf(y | Phi(mu));

Hierarchical Linear Mixture Model

I have implemented a stan hierarchical model with level 1 within groups to be a linear model and level 2 within subjects Gaussian mixture model. It means the slope obtained from level 1 is used by level model GMM to cluster. When I run the model it has a convergence problem.
WARNING:pystan:Maximum (flat) parameter count (1000) exceeded:
skipping diagnostic tests for n_eff and Rhat. To run all diagnostics call pystan.check_hmc_diagnostics(fit)
WARNING:pystan:2 of 500 iterations ended with a divergence (0.4 %).
WARNING:pystan:Try running with adapt_delta larger than 0.8 to remove the divergences.
WARNING:pystan:Chain 1: E-BFMI = 0.0611
WARNING:pystan:E-BFMI below 0.2 indicates you may need to reparameterize your model
Any comments on improving the model?
multi_level_model = """
data {
int<lower=0> N; // No of observations
int J; // No of subjects
int<lower=1,upper=J> RID[N];
vector[N] x; // Cognitive measure
}
parameters{
real a;
vector[J] b;
real mu_b;
real<lower=0,upper=2> sigma_b;
# Gaussian Parameters for level 2
ordered[2] mu;
real<lower=0> sigma[2];
real<lower=0, upper=1> theta;
}
transformed parameters {
vector[N] y_hat;
for(i in 1:N)
y_hat[i] <- a + x[i] * b[RID[i]];
}
model {
sigma_b ~ normal(0, 1);
b ~ normal (mu_b, sigma_b);
a ~ normal (0, 1);
sigma ~ normal(0, 1);
mu ~ normal(0, 1);
theta ~ beta(5, 5);
for (n in 1:J)
target += log_mix(theta,
normal_lpdf(b[n] | mu[1], sigma[1]),
normal_lpdf(b[n] | mu[2], sigma[2]));
}
"""

Setting up a Hierarchical Multinomial Processing Tree in Stan

I'm having trouble setting up a Hierarchical Multinomial Processing tree in Stan. As a starting point, I am trying to add a hierarchy to the simple model here:
https://github.com/stan-dev/example-models/blob/master/Bayesian_Cognitive_Modeling/CaseStudies/MPT/MPT_1_Stan.R
I'm not sure why the code does not work. Any help would be greatly appreciated.
Example Data (Based on Julia syntax):
Nsub = 2
Ntrials = 100
FCat = [20 60 20;30 50 20]
data {
// Number of subjects
int<lower=1> Nsub;
// Number of Trials
int<lower=1> Ntrials;
// Data
int<lower=0,upper=Ntrials> FCat[Nsub,4];
}
parameters {
vector<lower=0,upper=1>[Nsub] c;
vector<lower=0,upper=1>[Nsub] r;
vector<lower=0,upper=1>[Nsub] u;
real<lower=0> c_omega;
real<lower=0> r_omega;
real<lower=0> u_omega;
real<lower=0,upper=1> c_kappa;
real<lower=0,upper=1> r_kappa;
real<lower=0,upper=1> u_kappa;
}
transformed parameters {
simplex[4] theta[Nsub];
real<lower=0> c_A;
real<lower=0> c_B;
real<lower=0> r_A;
real<lower=0> r_B;
real<lower=0> u_A;
real<lower=0> u_B;
c_A <- c_kappa*c_omega;
c_B <- (1-c_kappa)*c_omega;
r_A <- r_kappa*r_omega;
r_B <- (1-r_kappa)*r_omega;
u_A <- u_kappa*u_omega;
u_B <- (1-u_kappa)*u_omega;
// Create category responses
for (i in 1:Nsub){
theta[i,1] <- c[i]*r[i];
theta[i,2] <- (1 - c[i])*sqrt(u[i]);
theta[i,3] <- (1 - c[i])*2*u[i]*(1 - u[i]);
theta[i,4] <- c[i]*(1 - r[i]) + (1 - c[i])*sqrt(1 - u[i]);
}
}
model {
// HyperPriors
c_omega ~ gamma(2,8);
r_omega ~ gamma(2,8);
u_omega ~ gamma(2,8);
c_kappa ~ beta(50,50);
r_kappa ~ beta(50,50);
u_kappa ~ beta(70,30);
// Priors
c ~ beta(c_A, c_B);
r ~ beta(r_A, r_B);
u ~ beta(u_A, u_B);
for (i in 1:Nsub){
FCat[i] ~ multinomial(theta[i]);
}
}
The sqrt() function just takes square roots of a scalar (real or int), returning a real.
You can use print() to see if your values sum to 1. Or you can do a test yourself and reject if they don't. The usual stick-breaking construction for a simplex is given in the manual in the simplex transform. The usual approach is to take the first value to be between 0 and 1, then the next to be some fraction of what's left (1 - first value), and so on. We also have softmax built in. You have to be careful with identifiability with a softmax parameterization --- the priors will matter unless you set one of the inputs to a constant.

Partially observed parameter in Stan

I am trying to migrate some code from JAGS to Stan. Say I have the following dataset:
N <- 10
nchoices <- 3
ncontrols <- 3
toydata <- list("y" = rbinom(N, nchoices - 1, .5),
"controls" = matrix(runif(N*ncontrols), N, ncontrols),
"N" = N,
"nchoices" = nchoices,
"ncontrols" = ncontrols)
and that I want to run a multinomial logit with the following code (taken from section 9.5 of the documentation):
data {
int N;
int nchoices;
int y[N];
int ncontrols;
vector[ncontrols] controls[N];
}
parameters {
matrix[nchoices, ncontrols] beta;
}
model {
for (k in 1:nchoices)
for (d in 1:ncontrols)
beta[k,d] ~ normal(0,100);
for (n in 1:N)
y[n] ~ categorical(softmax(beta * controls[n]));
}
I now want to fix the first row of beta to zero. In JAGS I would simply declare in the model block that
for (i in 1:ncontrols) {
beta[1,i] <- 0
}
but I am not sure about how to do this in Stan. I have tried many combinations along the lines of section 6.2 of the documentation (Partially Known Parameters) like, for instance,
parameters {
matrix[nchoices, ncontrols] betaNonObs;
}
transformed parameters {
matrix[nchoices, ncontrols] beta;
for (i in 1:ncontrols) beta[1][i] <- 0
for (k in 2:nchoices) beta[k] <- betaNonObs[k - 1]
}
but none of them work. Any suggestions?
It would be helpful to mention the error message. In this case, if beta is declared to be a matrix, then the syntax you want is the R-like syntax
beta[1,i] <- 0.0; // you also omitted the semicolon
To answer your broader question, I believe you were on the right track with your last approach. I would create a matrix of parameters in the parameters block called free_beta and copy those elements to another matrix declared in the model block called beta that has one extra row at the top for the fixed zeros. Like
data {
int N;
int nchoices;
int y[N];
int ncontrols;
vector[ncontrols] controls[N];
}
parameters {
matrix[nchoices-1, ncontrols] free_beta;
}
model {
// copy free beta into beta
matrix[nchoices,ncontrols] beta;
for (d in 1:ncontrols)
beta[1,d] <- 0.0;
for (k in 2:nchoices)
for (d in 1:ncontrols)
beta[k,d] <- free_beta[k-1,d];
// priors on free_beta, which execute faster this way
for (k in 1:(nchoices-1))
row(free_beta,k) ~ normal(0.0, 100.0);
// likelihood
for (n in 1:N)
y[n] ~ categorical(softmax(beta * controls[n]));
}

Resources