Skip to content

Instantly share code, notes, and snippets.

@tpapp
Created November 14, 2014 10:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tpapp/c42f3f3a5f184fcd8403 to your computer and use it in GitHub Desktop.
Save tpapp/c42f3f3a5f184fcd8403 to your computer and use it in GitHub Desktop.
coding a multilevel logit in Stan, two categorical predictors, fast & efficient inference, proper (but vague) priors
data {
int N;
int a_N; // number of categories in a
int b_N; // number of categories in b
int c_N; // number of c coefficients (continuous)
int<lower=1, upper=a_N> a[N];
int<lower=1, upper=b_N> b[N];
matrix[N, c_N] c;
int<lower=0, upper=1> y[N];
}
parameters {
real intercept;
vector[a_N] a_coeff;
vector[b_N] b_coeff;
vector[c_N] c_coeff;
real<lower=0> sigma_a;
real<lower=0> sigma_b;
real<lower=0> sigma_c;
}
transformed parameters {
vector[a_N] normalized_a_coeff;
vector[b_N] normalized_b_coeff;
normalized_a_coeff <- a_coeff - a_coeff[1];
normalized_b_coeff <- b_coeff - b_coeff[1];
}
model {
vector[N] p; // probabilities
// priors
intercept ~ normal(0, 100);
sigma_a ~ cauchy(0, 5);
sigma_b ~ cauchy(0, 5);
sigma_c ~ cauchy(0, 5);
// level 1
a_coeff ~ normal(0, sigma_a);
b_coeff ~ normal(0, sigma_b);
c_coeff ~ normal(0, sigma_c);
// level 2
for (i in 1:N) {
p[i] <- a_coeff[a[i]] + b_coeff[b[i]];
}
y ~ bernoulli_logit(intercept + p + c * c_coeff);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment