<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/mcmc-using-stan-diagnostics-with-the-bayesplot-package-exercises/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.r-exercises.com/2018/04/08/mcmc-using-stan-diagnostics-with-bayesplot-package-exercises/"> R-exercises</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><a rel="nofollow" href="https://i1.wp.com/www.r-exercises.com/wp-content/uploads/2018/04/plt-exercises-12.png?ssl=1" target="_blank"><img sizes="(max-width: 300px) 100vw, 300px" src="https://i0.wp.com/www.r-exercises.com/wp-content/uploads/2018/04/plt-exercises-12-300x171.png?resize=300%2C171&ssl=1" alt="" width="300" class="wp-image-10326" data-recalc-dims="1" height="171"></a>This exercise set will continue to present the <a rel="nofollow" href="http://mc-stan.org/" target="_blank">STAN</a> platform, but with another useful tool: the <code>bayesplot</code> package. This package is very useful to construct diagnostics that can be used to have insights on the convergence of the MCMC sampling since the convergence of the generated chains is the main issue in most STAN models.<br>
You can find the first bit of information on <code>bayesplot </code>package in this <a rel="nofollow" href="https://cran.r-project.org/web/packages/bayesplot/vignettes/plotting-mcmc-draws.html" target="_blank">introductory vignette </a>or in this <a rel="nofollow" href="https://cran.r-project.org/web/packages/bayesplot/vignettes/visual-mcmc-diagnostics.html" target="_blank">vignette</a>.</p>
<p>We will make use of a survey of residents from a small area in Bangladesh that was affected by arsenic in drinking water. Respondents with elevated arsenic levels in their wells were asked if they were interested in getting water from a neighbor’s well. A series of <a rel="nofollow" href="https://www.wikiwand.com/en/Logistic_regression" target="_blank">logistic regressions</a> could be fit to predict this binary response given various information about the households. Here we fit a model for the well-switching response, given two predictors: the arsenic level of the water in the resident’s home and the distance of the house from the nearest safe well.<br>
More information on this data can be found in <a rel="nofollow" href="https://link.springer.com/article/10.1007%2Fs11222-016-9696-4" target="_blank">this interesting paper</a>.</p>
<p>Solutions for this set of exercises can be found <a rel="nofollow" href="https://www.r-exercises.com/2018/04/08/mcmc-using-stan-diagnostics-with-bayesplot-package-solutions/" target="_blank">here</a>. The first chunk defines, installs (if needed) and loads the packages needed in this set.</p>
<p><strong>Exercise 1</strong><br>
After having installed and loaded the <code>rstan </code>and <code>bayesplot </code>packages, set the global options that allows you to automatically save a bare version of a compiled Stan program. This way, it does not need to be recompiled to execute multiple chains, in parallel, by taking all the available cores of your machine (use the <code>parallel</code> package).<br>
Set the color “bright blue” so that it applies to all subsequent plots.<br>
Finally, import the data of interest; the wells.dat data-set, you can import from the <a rel="nofollow" href="http://stat.columbia.edu/~gelman/arm/examples/arsenic/" target="_blank">Gelman repository</a> by simply making use of the <code>read.table()</code> function from the R utils package. Create the variable “<em>dist100″</em> which is equal to <code>dist/100 </code>.</p>
<p><strong>Exercise 2</strong><br>
Create a plot to visualize the relationship between the two variables of interest with the dependent binary variable “<em>switch</em>“.<br>
What can you say about this relationship?<br>
Then, fit the model with the frequentist <code>glm()</code> function and inspect the summary of the estimation results.</p>
<p><strong>Exercise 3</strong><br>
Write the STAN model of interest in your R script by following the pertaining blocks of a <a rel="nofollow" href="http://mlss2014.hiit.fi/mlss_files/2-stan.pdf" target="_blank">STAN code</a> by using weak priors for the parameters (ex. take multivariate normal prior with a standard deviation of 10).</p>
<p><strong>–</strong> The <strong>data</strong> block that will gather all the data is used in the STAN model: N (the number of data points; it cannot be negative), P (the number of different predictors; it cannot be negative), X (the matrix of covariates, including the intercept) and y (the binary outcome).<br>
<strong>–</strong> The <strong>parameters</strong> block: beta that is represented as a parameter vector for the parameters of the logistic regression model.<br>
<strong>–</strong> The <strong>model</strong> block: it defines the prior distribution for the parameters beta and creates the response vector of interest by multiplying the matrix of covariates with the parameters.</p>
<p>Do not forget to constraint the upper and lower bounds in the data and parameter block declarations.</p>
<p>Note that it is recommended to write the STAN code in a separate file (“.stan” extension) and then call it directly through the <code>stan()</code> function instead of writing it in a character, like what is done here. That would be easier to debug, read, etc.</p>
<p><strong>Exercise 4</strong><br>
Define the named data list that will be used inside the STAN data block written above.</p>
<p><strong>Exercise 5</strong><br>
Run the STAN model using the <code>stan()</code> function and using the following input parameters:<br>
– The STAN code defined in Exercise 3<br>
– The data list defined in Exercise 4<br>
– Four different chains<br>
– 1000 iterations per chain<br>
– A warm-up phase of 200. This phase defines the number of iterations that are used by the sampler for the adaptation phase before sampling begins (and is thus different of the burn-in phase we have seen in the Metropolis or Gibbs samplers).<br>
Use all the available cores of your machine and make it reproducible (take the <code>seed</code> 1234). Then, print the estimation outputs of the parameters.</p>
<p><strong>Exercise 6</strong><br>
Plot the central posterior uncertainty intervals of each parameter in the form of horizontal lines with the median as a central point.</p>
<p><strong>Exercise 7</strong><br>
Do the same as Exercise 6, but with the posterior estimates represented by density areas. Take the mean as a central point and 80%/99% as inner/outer credible intervals.</p>
<p><strong>Exercise 8</strong><br>
– Plot the histograms of the three parameters. Take the binwidth of 1/50 for each parameter. Then, do the same, but displaying each of the 4 chains and take a binwidth of 1/100.<br>
– Do the same but with density plots. Overlay chains in the density plots instead of plotting them separately, like the histograms.<br>
– Draw <a rel="nofollow" href="https://www.wikiwand.com/en/Violin_plot" target="_blank">violin-plots</a> of the 4 chains separately for each parameter except the intercept. Highlight the quantiles 5%, 20%, 50%, 70%, and 95%.</p>
<p><strong>Exercise 9</strong><br>
Compute the traceplots for each parameter separately and overlay the 4 pertaining chains in each plot.</p>
<p><strong>Exercise 10</strong><br>
Since we are interested only in the two covariates (<em>dist100</em> and <em>arsenic</em>), represent a bivariate scatter-plot of the posterior draws. Then, try to avoid over-plotting with hexagonal binning.<br>
Finally, represent a scatter-plot table of all the parameters with the density plots lying in the diagonal and the posterior draws in the off-diagonal.</p>
<div>
<h3>Related exercise sets:</h3>
<ol>
<li><a rel="nofollow" href="https://www.r-exercises.com/2017/11/29/spatial-data-analysis-introduction-to-raster-processing-part-1/" title="Spatial Data Analysis: Introduction to Raster Processing (Part 1)" target="_blank">Spatial Data Analysis: Introduction to Raster Processing (Part 1) </a></li>
<li><a rel="nofollow" href="https://www.r-exercises.com/2017/07/13/parallel-computing-exercises-foreach-and-doparallel-part-2/" title="Parallel Computing Exercises: Foreach and DoParallel (Part-2)" target="_blank">Parallel Computing Exercises: Foreach and DoParallel (Part-2) </a></li>
<li><a rel="nofollow" href="https://www.r-exercises.com/2017/08/03/parallel-computing-exercises-snow-and-rmpi-part-3/" title="Parallel Computing Exercises: Snow and Rmpi (Part-3)" target="_blank">Parallel Computing Exercises: Snow and Rmpi (Part-3) </a></li>
<li><a rel="nofollow" href="http://www.r-exercises.com/start-here-to-learn-r/" target="_blank">Explore all our (>1000) R exercises</a></li>
<li><a rel="nofollow" href="http://www.r-exercises.com/r-courses/" target="_blank">Find an R course using our R Course Finder</a> directory</li>
</ol>
</div>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.r-exercises.com/2018/04/08/mcmc-using-stan-diagnostics-with-bayesplot-package-exercises/"> R-exercises</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 rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/EEaCOEH0SCs" height="1"></a></div>