<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/hierarchical-models-with-rstan-part-1/"></div></div><div><a data-url="https://www.r-bloggers.com/hierarchical-models-with-rstan-part-1/" data-counturl="https://www.r-bloggers.com/hierarchical-models-with-rstan-part-1/" data-count="horizontal" data-text="Hierarchical models with RStan (Part 1)" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://biologyforfun.wordpress.com/2016/11/10/hierarchical-models-with-rstan-part-1/"> R – biologyforfun</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Real-world data sometime show complex structure that call for the use of special models. When data are organized in more than one level, <a target="_blank" rel="nofollow" href="http://www.cambridge.org/de/academic/subjects/statistics-probability/statistical-theory-and-methods/data-analysis-using-regression-and-multilevelhierarchical-models?format=PB&isbn=9780521686891">hierarchical models</a> are the most relevant tool for data analysis. One classic example is when you record student performance from different schools, you might decide to record student-level variables (age, ethnicity, social background) as well as school-level variable (number of student, budget). In this post I will show how to fit such models using RStan. As there is much to say and try on such models I restrict myself in this post to a rather simple example, I will extend this to more complex situations in latter posts.</p>
<h2>A few words about RStan:</h2>
<p>If you don’t know anything about STAN and RStan make sure to check out <a target="_blank" rel="nofollow" href="http://mc-stan.org/">this</a> webpage. In a few words RStan is an R interface to the STAN programming language that let’s you fit Bayesian models. A classical workflow looks like this:</p>
<ol>
<li>Write a STAN model file ending with a .stan</li>
<li>In R fit the model using the <strong>RStan</strong> package passing the model file and the data to the <em>stan</em> function</li>
<li>Check model fit, a great way to do it is to use the <a target="_blank" rel="nofollow" href="https://cran.r-project.org/web/packages/shinystan/index.html"><strong>shinystan</strong></a> package</li>
</ol>
<h2>First example with simulated data:</h2>
<p>Say that we recorded the response of 10 different plant species to rising temperature and nitrogen concentration. We measured the biomass of 10 individuals per species along a gradient of both temperature and nitrogen concentration and we would like to know how these two variables affect plant biomass. In hierarchical model we let regression parameters vary between the species, this means that, for example, species A might have a more positive slope between temperature and biomass than species B. Note however that we do not fit separate regression to each species, rather the regression parameters for the different species are themselves being fitted to a statistical distribution.</p>
<p>In mathematical terms this example can be written:</p>
<p><img title="\mu_{ij} = \beta_{0j} + \beta_{1j} * Temperature_{ij} + \beta_{2j} * Nitrogen_{ij}" alt="\mu_{ij} = \beta_{0j} + \beta_{1j} * Temperature_{ij} + \beta_{2j} * Nitrogen_{ij}" class="latex" src="https://s0.wp.com/latex.php?latex=%5Cmu_%7Bij%7D+%3D+%5Cbeta_%7B0j%7D+%2B+%5Cbeta_%7B1j%7D+%2A+Temperature_%7Bij%7D+%2B+%5Cbeta_%7B2j%7D+%2A+Nitrogen_%7Bij%7D&bg=ffffff&%23038;fg=7a7c84&%23038;s=0"></p>
<p><img title="\beta_{0j} \sim N(\gamma_{0},\tau_{0})" alt="\beta_{0j} \sim N(\gamma_{0},\tau_{0})" class="latex" src="https://s0.wp.com/latex.php?latex=%5Cbeta_%7B0j%7D+%5Csim+N%28%5Cgamma_%7B0%7D%2C%5Ctau_%7B0%7D%29&bg=ffffff&%23038;fg=7a7c84&%23038;s=0"></p>
<p>… (same for all regression coefficients) …</p>
<p><img title="y_{ij} \sim N(\mu_{ij},\sigma)" alt="y_{ij} \sim N(\mu_{ij},\sigma)" class="latex" src="https://s0.wp.com/latex.php?latex=y_%7Bij%7D+%5Csim+N%28%5Cmu_%7Bij%7D%2C%5Csigma%29&bg=ffffff&%23038;fg=7a7c84&%23038;s=0"></p>
<p>For observations i: 1 … N and species j: 1 … J.</p>
<p>This is how such a model looks like in STAN:</p>
<pre>/*A simple example of an hierarchical model*/
data {
  int&lt;lower=1> N; //the number of observations
  int&lt;lower=1> J; //the number of groups
  int&lt;lower=1> K; //number of columns in the model matrix
  int&lt;lower=1,upper=J> id[N]; //vector of group indeces
  matrix[N,K] X; //the model matrix
  vector[N] y; //the response variable
}
parameters {
  vector[K] gamma; //population-level regression coefficients
  vector&lt;lower=0>[K] tau; //the standard deviation of the regression coefficients

  vector[K] beta[J]; //matrix of group-level regression coefficients
  real&lt;lower=0> sigma; //standard deviation of the individual observations
}
model {
  vector[N] mu; //linear predictor
  //priors
  gamma ~ normal(0,5); //weakly informative priors on the regression coefficients
  tau ~ cauchy(0,2.5); //weakly informative priors, see section 6.9 in STAN user guide
  sigma ~ gamma(2,0.1); //weakly informative priors, see section 6.9 in STAN user guide
  
  for(j in 1:J){
   beta[j] ~ normal(gamma,tau); //fill the matrix of group-level regression coefficients 
  }
  
  for(n in 1:N){
    mu[n] = X[n] * beta[id[n]]; //compute the linear predictor using relevant group-level regression coefficients 
  }

  //likelihood
  y ~ normal(mu,sigma);
}</pre>
<p>You can copy/paste the code into an empty text editor and save it under a .stan file.</p>
<p>Now we turn into R:</p>
<pre>#load libraries
library(rstan)
library(RColorBrewer)
#where the STAN model is saved
setwd(&quot;~/Desktop/Blog/STAN/&quot;)
#simulate some data
set.seed(20161110)
N&lt;-100 #sample size
J&lt;-10 #number of plant species
id&lt;-rep(1:J,each=10) #index of plant species
K&lt;-3 #number of regression coefficients
#population-level regression coefficient
gamma&lt;-c(2,-1,3)
#standard deviation of the group-level coefficient
tau&lt;-c(0.3,2,1)
#standard deviation of individual observations
sigma&lt;-1
#group-level regression coefficients
beta&lt;-mapply(function(g,t) rnorm(J,g,t),g=gamma,t=tau) 
#the model matrix
X&lt;-model.matrix(~x+y,data=data.frame(x=runif(N,-2,2),y=runif(N,-2,2)))
y&lt;-vector(length = N)
for(n in 1:N){
  #simulate response data
  y[n]&lt;-rnorm(1,X[n,]%*%beta[id[n],],sigma)
}
#run the model
m_hier&lt;-stan(file=&quot;hierarchical1.stan&quot;,data=list(N=N,J=J,K=K,id=id,X=X,y=y))</pre>
<p>The MCMC sampling takes place (took about 90 sec per chain on my computer), and then I got this warning message: <span>“Warning messages:</span><br>
<span>1: There were 61 divergent transitions after warmup. Increasing adapt_delta above 0.8 may help. See</span><br>
<span><a target="_blank" rel="nofollow" href="http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup">http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup</a> </span><br>
<span>2: Examine the pairs() plot to diagnose sampling problems”</span></p>
<p><span>Here is an explanation for this warning: “For some intuition, imagine walking down a steep mountain. If you take too big of a step you will fall, but if you can take very tiny steps you might be able to make your way down the mountain, albeit very slowly. Similarly, we can tell Stan to take smaller steps around the posterior distribution, which (in some but not all cases) can help avoid these divergences.” from <a target="_blank" rel="nofollow" href="http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup">here</a>. This issue occur quite often in hierarchical model with limited sample size, the simplest solution being to re-parameterize the model, in other words to re-write the equations so that the MCMC sampler has an easier time sampling the posterior distribution.</span></p>
<p>Below is a new STAN model with a non-centered parameterization (See Section 22.6 in STAN user guide):</p>
<pre>parameters {
  vector[K] gamma; //population-level regression coefficients
  vector&lt;lower=0>[K] tau; //the standard deviation of the regression coefficients
  //implementing Matt's trick
  vector[K] beta_raw[J];
  real&lt;lower=0> sigma; //standard deviation of the individual observations
}
transformed parameters {
  vector[K] beta[J]; //matrix of group-level regression coefficients
  //computing the group-level coefficient, based on non-centered parametrization based on section 22.6 STAN (v2.12) user's guide
  for(j in 1:J){
    beta[j] = gamma + tau .* beta_raw[j];
  }
}
model {
  vector[N] mu; //linear predictor
  //priors
  gamma ~ normal(0,5); //weakly informative priors on the regression coefficients
  tau ~ cauchy(0,2.5); //weakly informative priors, see section 6.9 in STAN user guide
  sigma ~ gamma(2,0.1); //weakly informative priors, see section 6.9 in STAN user guide
  for(j in 1:J){
   beta_raw[j] ~ normal(0,1); //fill the matrix of group-level regression coefficients 
  }
  for(n in 1:N){
    mu[n] = X[n] * beta[id[n]]; //compute the linear predictor using relevant group-level regression coefficients 
  }
  //likelihood
  y ~ normal(mu,sigma);
}</pre>
<p>Note that the <em>data </em>model block is identical in the two cases.</p>
<p>We turn back to R:</p>
<pre>#re-parametrize the model
m_hier&lt;-stan(file=&quot;hierarchical1_reparam.stan&quot;,data=list(N=N,J=J,K=K,id=id,X=X,y=y))
#no more divergent iterations, we can start exploring the model
#a great way to start is to use the shinystan library
#library(shinystan)
#launch_shinystan(m_hier)
#model inference
print(m_hier,pars=c(&quot;gamma&quot;,&quot;tau&quot;,&quot;sigma&quot;))
Inference for Stan model: hierarchical1_reparam.
4 chains, each with iter=2000; warmup=1000; thin=1; 
post-warmup draws per chain=1000, total post-warmup draws=4000.

          mean se_mean   sd  2.5%   25%   50%  75% 97.5% n_eff Rhat
gamma[1]  1.96    0.00 0.17  1.61  1.86  1.96 2.07  2.29  2075    1
gamma[2] -0.03    0.02 0.77 -1.53 -0.49 -0.04 0.43  1.55  1047    1
gamma[3]  2.81    0.02 0.49  1.84  2.52  2.80 3.12  3.79   926    1
tau[1]    0.34    0.01 0.21  0.02  0.19  0.33 0.46  0.79  1135    1
tau[2]    2.39    0.02 0.66  1.47  1.94  2.26 2.69  4.04  1234    1
tau[3]    1.44    0.01 0.41  0.87  1.16  1.37 1.65  2.43  1317    1
sigma     1.04    0.00 0.09  0.89  0.98  1.04 1.10  1.23  2392    1

Samples were drawn using NUTS(diag_e) at Thu Nov 10 14:11:41 2016.
For each parameter, n_eff is a crude measure of effective sample size,
and Rhat is the potential scale reduction factor on split chains (at 
convergence, Rhat=1).</pre>
<p>The regression parameters were all decently estimated except for the second slope coefficient, the simulated value was -1.</p>
<p>All MCMC samples for all coefficient can be easily extracted and used to compute whatever your interest is:</p>
<pre>#extract the MCMC samples
mcmc_hier&lt;-extract(m_hier)
str(mcmc_hier)

#plot average response to explanatory variables
X_new&lt;-model.matrix(~x+y,data=data.frame(x=seq(-2,2,by=0.2),y=0))
#get predicted values for each MCMC sample
pred_x1&lt;-apply(mcmc_hier$gamma,1,function(beta) X_new %*% beta)
#now get median and 95% credible intervals
pred_x1&lt;-apply(pred_x1,1,quantile,probs=c(0.025,0.5,0.975))
#same stuff for the second explanatory variables
X_new&lt;-model.matrix(~x+y,data=data.frame(x=0,y=seq(-2,2,by=0.2)))
pred_x2&lt;-apply(mcmc_hier$gamma,1,function(beta) X_new %*% beta)
pred_x2&lt;-apply(pred_x2,1,quantile,probs=c(0.025,0.5,0.975))</pre>
<p>Here we basically generated new model matrices where only one variable was moving at a time, this allowed us to get the model prediction for the effect of say temperature on plant biomass under average nutrient conditions. These predictions were obtained by multiplying the model matrix with the coefficients for each MCMC sample (the first apply command), and then we can get from these samples the median with 95% credible intervals (the second apply command).</p>
<p>Now we can plot this (code for the plots at the end of the post)</p>
<p><img sizes="(max-width: 800px) 100vw, 800px" alt="hier1" class="wp-image-1312" src="https://i0.wp.com/biologyforfun.files.wordpress.com/2016/11/hier1.png?w=456&ssl=1" data-recalc-dims="1"></p>
<p>Another important plot is the variation in the regression parameters between the species, again this is easily done using the MCMC samples:</p>
<pre>#now we could look at the variation in the regression coefficients between the groups doing caterpillar plots
ind_coeff&lt;-apply(mcmc_hier$beta,c(2,3),quantile,probs=c(0.025,0.5,0.975))
df_ind_coeff&lt;-data.frame(Coeff=rep(c(&quot;(Int)&quot;,&quot;X1&quot;,&quot;X2&quot;),each=10),LI=c(ind_coeff[1,,1],ind_coeff[1,,2],ind_coeff[1,,3]),Median=c(ind_coeff[2,,1],ind_coeff[2,,2],ind_coeff[2,,3]),HI=c(ind_coeff[3,,1],ind_coeff[3,,2],ind_coeff[3,,3]))
gr&lt;-paste(&quot;Gr&quot;,1:10)
df_ind_coeff$Group&lt;-factor(gr,levels=gr)
#we may also add the population-level median estimate
pop_lvl&lt;-data.frame(Coeff=c(&quot;(Int)&quot;,&quot;X1&quot;,&quot;X2&quot;),Median=apply(mcmc_hier$gamma,2,quantile,probs=0.5))
ggplot(df_ind_coeff,aes(x=Group,y=Median))+geom_point()+
  geom_linerange(aes(ymin=LI,ymax=HI))+coord_flip()+
  facet_grid(.~Coeff)+
  geom_hline(data=pop_lvl,aes(yintercept=Median),color=&quot;blue&quot;,linetype=&quot;dashed&quot;)+
  labs(y=&quot;Regression parameters&quot;)</pre>
<p><img sizes="(max-width: 800px) 100vw, 800px" alt="hier2" class="wp-image-1311" src="https://i2.wp.com/biologyforfun.files.wordpress.com/2016/11/hier2.png?w=456&ssl=1" data-recalc-dims="1"></p>
<p>The cool thing with using STAN is that we can extend or modify the model in many ways. This will be the topics of future posts which will include: crossed and nested design, multilevel modelling, non-normal distributions and much more, stay tuned!</p>
<p>Code for the first plot:</p>
<pre>cols&lt;-brewer.pal(10,&quot;Set3&quot;)
par(mfrow=c(1,2),mar=c(4,4,0,1),oma=c(0,0,3,5))
plot(y~X[,2],pch=16,xlab=&quot;Temperature&quot;,ylab=&quot;Response variable&quot;,col=cols[id])
lines(seq(-2,2,by=0.2),pred_x1[1,],lty=2,col=&quot;red&quot;)
lines(seq(-2,2,by=0.2),pred_x1[2,],lty=1,lwd=3,col=&quot;blue&quot;)
lines(seq(-2,2,by=0.2),pred_x1[3,],lty=2,col=&quot;red&quot;)
plot(y~X[,3],pch=16,xlab=&quot;Nitrogen concentration&quot;,ylab=&quot;Response variable&quot;,col=cols[id])
lines(seq(-2,2,by=0.2),pred_x2[1,],lty=2,col=&quot;red&quot;)
lines(seq(-2,2,by=0.2),pred_x2[2,],lty=1,lwd=3,col=&quot;blue&quot;)
lines(seq(-2,2,by=0.2),pred_x2[3,],lty=2,col=&quot;red&quot;)
mtext(text = &quot;Population-level response to the two\nexplanatory variables with 95% CrI&quot;,side = 3,line = 0,outer=TRUE)
legend(x=2.1,y=10,legend=paste(&quot;Gr&quot;,1:10),ncol = 1,col=cols,pch=16,bty=&quot;n&quot;,xpd=NA,title = &quot;Group\nID&quot;)</pre>
<p> </p>
<p>Filed under: <a target="_blank" rel="nofollow" href="https://biologyforfun.wordpress.com/category/informatic-language/">Informatic Language</a>, <a target="_blank" rel="nofollow" href="https://biologyforfun.wordpress.com/category/r-and-stat/">R and Stat</a> Tagged: <a target="_blank" rel="nofollow" href="https://biologyforfun.wordpress.com/tag/bayesian/">Bayesian</a>, <a target="_blank" rel="nofollow" href="https://biologyforfun.wordpress.com/tag/r/">R</a>, <a target="_blank" rel="nofollow" href="https://biologyforfun.wordpress.com/tag/stan/">STAN</a>, <a target="_blank" rel="nofollow" href="https://biologyforfun.wordpress.com/tag/statistics/">Statistics</a> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/biologyforfun.wordpress.com/1186/"><img alt="" src="http://feeds.wordpress.com/1.0/comments/biologyforfun.wordpress.com/1186/" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/biologyforfun.wordpress.com/1186/"><img alt="" src="http://feeds.wordpress.com/1.0/delicious/biologyforfun.wordpress.com/1186/" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/biologyforfun.wordpress.com/1186/"><img alt="" src="http://feeds.wordpress.com/1.0/facebook/biologyforfun.wordpress.com/1186/" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/biologyforfun.wordpress.com/1186/"><img alt="" src="http://feeds.wordpress.com/1.0/twitter/biologyforfun.wordpress.com/1186/" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/biologyforfun.wordpress.com/1186/"><img alt="" src="http://feeds.wordpress.com/1.0/stumble/biologyforfun.wordpress.com/1186/" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/biologyforfun.wordpress.com/1186/"><img alt="" src="http://feeds.wordpress.com/1.0/digg/biologyforfun.wordpress.com/1186/" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/biologyforfun.wordpress.com/1186/"><img alt="" src="http://feeds.wordpress.com/1.0/reddit/biologyforfun.wordpress.com/1186/" border="0"></a> <img alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" border="0" data-recalc-dims="1"></p>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/hierarchical-models-with-rstan-part-1/"></div></div><div><a data-url="https://www.r-bloggers.com/hierarchical-models-with-rstan-part-1/" data-counturl="https://www.r-bloggers.com/hierarchical-models-with-rstan-part-1/" data-count="vertical" data-text="Hierarchical models with RStan (Part 1)" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://biologyforfun.wordpress.com/2016/11/10/hierarchical-models-with-rstan-part-1/"> R – biologyforfun</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/dWPAxZyANkw"></a></div>