Last updated: 2019-03-31

Checks: 6 0

Knit directory: fiveMinuteStats/analysis/

This reproducible R Markdown analysis was created with workflowr (version 1.2.0). The Report tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.

Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(12345) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility. The version displayed above was the version of the Git repository at the time these results were generated.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
Ignored:    .Rhistory
Ignored:    .Rproj.user/
Ignored:    analysis/.Rhistory
Ignored:    analysis/bernoulli_poisson_process_cache/

Untracked files:
Untracked:  _workflowr.yml
Untracked:  analysis/CI.Rmd
Untracked:  analysis/gibbs_structure.Rmd
Untracked:  analysis/libs/
Untracked:  analysis/results.Rmd
Untracked:  analysis/shiny/tester/
Untracked:  docs/MH_intro_files/
Untracked:  docs/citations.bib
Untracked:  docs/figure/MH_intro.Rmd/
Untracked:  docs/hmm_files/
Untracked:  docs/libs/
Untracked:  docs/shiny/tester/



Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.

These are the previous versions of the R Markdown and HTML files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view them.

File Version Author Date Message
Rmd d5d3e06 Jasha 2018-05-07 Fix typo
html 34bcc51 John Blischak 2017-03-06 Build site.
Rmd 5fbc8b5 John Blischak 2017-03-06 Update workflowr project with wflow_update (version 0.4.0).
Rmd 391ba3c John Blischak 2017-03-06 Remove front and end matter of non-standard templates.
html fb0f6e3 stephens999 2017-03-03 Merge pull request #33 from mdavy86/f/review
Rmd d674141 Marcus Davy 2017-02-27 typos, refs
html c3b365a John Blischak 2017-01-02 Build site.
Rmd 67a8575 John Blischak 2017-01-02 Use external chunk to set knitr chunk options.
Rmd 5ec12c7 John Blischak 2017-01-02 Use session-info chunk.
Rmd 8466ce3 stephens999 2016-05-02 add gibbs sampling example

# Pre-requisites

Be familiar with the concept of joint distribution and a conditional distribution. Ideally also with the concept of a Markov chain and its stationary distribution.

# Overview

Gibbs sampling is a very useful way of simulating from distributions that are difficult to simulate from directly. However, in this introduction to the key concept, we will use a Gibbs sampler to simulate from a very simple distribution that could be simulated from in other ways.

# Gibbs Sampling

Suppose $$X$$ and $$Y$$ are two binary random variables with joint distribution $$\Pr(X=x,Y=y) = p_{X,Y}(x,y)$$ given by the following table:

X \ Y 0 1
0 0.6 0.1
1 0.15 0.15

That is, for example, $$p_{X,Y}(0,0)=0.6$$.

The conditional distribution of $$X$$ given any given value is easy to compute by the usual formula for conditional probability, $$\Pr(A | B) = \Pr(A \cap B)/\Pr(B)$$. For example: $\Pr(X=0 | Y=0) = \Pr(X=0 \cap Y=0)/Pr(Y=0) = 0.6/0.75 = 0.8$ and so $\Pr(X=1 | Y=0) = 1-0.8 = 0.2.$ Similarly $\Pr(X=0 | Y=1) = 0.1/0.25 = 0.4$ and so $\Pr(X=1 | Y=1) = 0.6$.

We can just as easily compute the conditional distribution of $$Y$$ for any given value of $$X$$: $\Pr(Y=0 | X=0) = 6/7$ $\Pr(Y=1 | X=0) = 1/7$ $\Pr(Y=0 | X=1) = 1/2$ $\Pr(Y=1 | X=1) = 1/2$

Now the question: what if we start at some value of $$X,Y$$ and proceed to iterate the following steps: 1. Simulate a new value of $$X$$ from $$\Pr(X | Y=y)$$ where $$y$$ is the current value of $$Y$$. 2. Simulate a new value of $$Y$$ from $$\Pr(Y | X=x)$$ where $$x$$ is the current value of $$X$$ (generated in 1.) What happens?

Let’s try it:

#returns 1 with probability p, and 0 with probability 1-p
rbernoulli=function(p){return(1*runif(1)<p)}

# sample from distribution X given Y above
sample_XgivenY = function(y){
if(y==0){
x = rbernoulli(0.2) # returns 1 with probability 0.2; otherwise 0
} else {
x = rbernoulli(0.6)
}
return(x)
}
#' sample from distribution Y given X above
sample_YgivenX = function(x){
if(x==0){
y = rbernoulli(1/7)
} else {
y = rbernoulli(0.5)
}
return(y)
}
set.seed(100)
niter = 1000
X = rep(0,niter)
Y = rep(0,niter)
X[1]=1
Y[1]=1 # start from (1,1)
for(i in 2:niter){
X[i] = sample_XgivenY(Y[i-1])
Y[i] = sample_YgivenX(X[i])
}
res = data.frame(X=X,Y=Y)

Here is what happens for the first 20 iterations:

head(res,20)
   X Y
1  1 1
2  1 1
3  1 1
4  1 1
5  0 0
6  0 0
7  0 0
8  0 0
9  0 0
10 0 0
11 0 0
12 0 0
13 0 0
14 0 0
15 0 0
16 0 0
17 0 0
18 0 0
19 0 0
20 1 0

And here is a summary of what proportion of the rows are of each type:

table(data.frame(X=X,Y=Y))/niter
   Y
X       0     1
0 0.617 0.092
1 0.154 0.137

As you can see, the proportion of iterations in which $$X=x$$ and $$Y=y$$ is very close to $$\Pr(X=x,Y=y)=p_{X,Y}(x,y)$$. This is not a coincidence!

# Explanation

What we have done here is simulate a Markov chain $(X_1,Y_1), (X_2,Y_2), (X_3,Y_3), \dots$, whose stationary distribution is $$\Pr(X=x,Y=y)=p_{X,Y}(x,y)$$.

To see that the pairs $$(X,Y)$$ form a Markov chain, note that the simulation of $$X_i$$ is done using only the previous value $$Y_{i-1}$$, and the simulation of $$Y_i$$ is done using only $$X_i$$. So simulation of $$(X_i,Y_i)$$ depends on the previous states only through the immediate previous state $$(X_{i-1},Y_{i-1})$$, which means it is a Markov chain. (And in fact it only depends on $$Y_{i-1}$$, but that is not so important.)

To see why it has stationary distribution $$p_{X,Y}(x,y)$$ imagine simulating $$X_1,Y_1$$ from this distribution, so $$\Pr(X_1=x,Y_1=y)= p_{X,Y}(x,y)$$, and in particular $$\Pr(Y_1=y)= \sum_x p_{X,Y}(x,y) = p_Y(y)$$.

Now, what is $$\Pr(X_2=x,Y_1=y)$$? Well we know $\Pr(X_2=x,Y_1=y) = \Pr(Y_1=y) \Pr(X_2=x| Y_1=y).$ And we know from above that $\Pr(Y_1=y) = p_{Y}(y).$ And we know that given $$Y_1=y$$, $$X_2$$ was simulated from the conditional distribution $$p_{X|Y}(x|y)$$, so $\Pr(X_2=x | Y_1=y) = p_{X|Y}(x|y).$ Putting these together we have $\Pr(X_2=x,Y_1=y) = p_{Y}(y)p_{X|Y}(x|y) = p_{X,Y}(x,y).$

Now, essentially the same argument shows that $$\Pr(X_2=x, Y_2=y) = p_{X,Y}(x,y)$$. [Exercise]

Thus, we have shown that if $$\Pr(X_1=x, Y_1=y) = p_{X,Y}(x,y)$$ then also $$\Pr(X_2=x, Y_2=y) = p_{X,Y}(x,y)$$. That is exactly what it means for $$p_{X,Y}(x,y)$$ to be the stationary distribution: if we start the chain by simulating from that distribution then it remains in that distribution after one step, and so it remains in that distribution for ever.

Of course, we did not start the chain at that distribution. But the above argument shows that this is indeed the stationary distribution. There is a general result that discrete Markov chains converge to their stationary distribution, provided that they are what is called “irreducible and aperiodic” (which this Markov chain is). That is, for large enough $$n$$, we should see $$\Pr(X_n=x, Y_n=y) \approx p_{X,Y}(x,y)$$ no matter where we start. Furthermore, in the long-run, the proportion of iterations spent in each state will also converge to this distribution.

This explains the simulation result.

sessionInfo()
R version 3.5.2 (2018-12-20)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.1

Matrix products: default
BLAS: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] workflowr_1.2.0 Rcpp_1.0.0      digest_0.6.18   rprojroot_1.3-2
[5] backports_1.1.3 git2r_0.24.0    magrittr_1.5    evaluate_0.12
[9] stringi_1.2.4   fs_1.2.6        whisker_0.3-2   rmarkdown_1.11
[13] tools_3.5.2     stringr_1.3.1   glue_1.3.0      xfun_0.4
[17] yaml_2.2.0      compiler_3.5.2  htmltools_0.3.6 knitr_1.21     

This site was created with R Markdown