-
Notifications
You must be signed in to change notification settings - Fork 7
/
README.Rmd
324 lines (247 loc) · 10.9 KB
/
README.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
---
output:
github_document:
html_preview: false
---
```{r include=FALSE}
knitr::opts_chunk$set(fig.path = "man/figures/", warning = FALSE)
```
# fmcmc: A friendly MCMC framework <img src="man/figures/logo.png" align="right" height="140"/>
[![DOI](http://joss.theoj.org/papers/10.21105/joss.01427/status.svg)](https://doi.org/10.21105/joss.01427)
[![R CI](https://github.com/USCbiostats/fmcmc/actions/workflows/ci.yml/badge.svg)](https://github.com/USCbiostats/fmcmc/actions/workflows/ci.yml)
[![Build
status](https://ci.appveyor.com/api/projects/status/lirawn11ssw9cq07/branch/master?svg=true)](https://ci.appveyor.com/project/gvegayon/fmcmc/branch/master)
[![Coverage
Status](https://img.shields.io/codecov/c/github/USCbiostats/fmcmc/master.svg)](https://codecov.io/github/USCbiostats/fmcmc?branch=master)
[![Lifecycle:
stable](https://img.shields.io/badge/lifecycle-stable-brightgreen.svg)](https://www.tidyverse.org/lifecycle/#stable)
[![CRAN
status](https://www.r-pkg.org/badges/version/fmcmc)](https://cran.r-project.org/package=fmcmc)
[![CRAN
downloads](http://cranlogs.r-pkg.org/badges/grand-total/fmcmc)](https://cran.r-project.org/package=fmcmc)
[![status](https://tinyverse.netlify.com/badge/fmcmc)](https://CRAN.R-project.org/package=fmcmc)
[![Integrative Methods of Analysis for Genetic Epidemiology](https://raw.githubusercontent.com/USCbiostats/badges/master/tommy-image-badge.svg)](https://image.usc.edu)
## What
The `fmcmc` R package provides a lightweight general framework for implementing
Markov Chain Monte Carlo methods based on the Metropolis-Hastings algorithm. This
implementation's primary purpose lies in the fact that the user can incorporate the
following flexibly:
1. **Automatic convergence checker**: The algorithm splits the MCMC runs according
to the frequency with which it needs to check convergence. Users can
use either one of the included functions (`convergence_gelman,`
`convergence_geweke,` etc.), or provide their own.
2. **Run multiple chains in parallel fashion**: Using either a `PSOCK` cluster
(default), or providing a personalized cluster object like the ones in
the `parallel` R package.
3. **User defined transition kernels**: Besides of canonical Gaussian Kernel,
users can specify their own or use one of the included in the package, for
example: `kernel_adapt`, `kernel_ram`, `kernel_normal_reflective`, `kernel_unif`,
`kernel_mirror`, or `kernel_unif_reflective`.
All the above without requiring compiled code. For the latest about `fmcmc,` checkout
the [NEWS.md](NEWS.md) section.
## Who is this for?
While a lot of users rely on MCMC tools such as Stan (via the [rstan](https://cran.r-project.org/package=rstan) package) or
WinBUGS (via [rstan](https://cran.r-project.org/package=R2WinBUGS)), in several settings either these tools are not enough
or provide too much for things that do not need that much. So, this tool is for
you if:
* You have a simple model to estimate with Metropolis-Hastings.
* You want to run multiple chains of your model using out-of-the-box parallel
computing.
* You don't want (or cannot) rely on external tools (so you need good-old
base R only for your models).
* You want to implement a model in which your model parameters are either bounded
(like a standard error, for example), or are not, say, continuous (e.g., a
size variable in a Binomial distribution), so you need a personalized transition
kernel.
In any other case, you may want to take a look at the previously mentioned R
packages, or check out the [mcmc](https://cran.r-project.org/package=mcmc) R
package, which also implements the Metropolis-Hastings algorithm (although with
not all the features that this R package has), the [adaptMCMC](https://cran.r-project.org/package=adaptMCMC)
R package, or the [MCMCpack](https://cran.r-project.org/package=MCMCpack) R package.
# Installing
If you want to get the latest bleeding-edge version from Github, you can use [devtools](https://cran.r-project.org/package=devtools):
```r
devtools::install_github("USCbiostats/fmcmc")
```
The latest (stable) release is also available on CRAN:
```r
install.packages("fmcmc")
```
# Citation
```{r citation, echo=FALSE, comment=""}
citation("fmcmc")
```
# Example: Linear regression model
## First run
In the following we show how to use the package for estimating parameters in
a linear regression model. First, let's simulate some data to use:
```{r random-data1}
set.seed(78845)
n <- 1000
X <- rnorm(n)
y <- 3.0 + 2.0*X + rnorm(n, sd = 4)
```
In this case, we have three parameters to estimate, the constant
(2.0), the $\beta$ coefficient (2.0), and the standard deviation parameter of the
error (1.5).
To estimate this model, we can either maximize the log-likelihood function--which
is what is usually done--or we could do it using MCMC. In either case, we need
to specify the log(unnormalized some times)-likelihood function:
```{r ll1}
ll <- function(p, X., y.) {
joint_ll <- dnorm(y. - (p[1] + X.*p[2]), sd = p[3], log = TRUE)
joint_ll <- sum(joint_ll)
# If is undefined, then we explicitly return infinte (instead of NaN, for
# example)
if (!is.finite(joint_ll))
return(-Inf)
joint_ll
}
```
Notice that the function has more than one argument, in this case, `p,`
the vector of parameters, `X.` and `y.,` the data of our model.
Let's do a first run of the MCMC algorithm using the function of the same name
(first, load the package, of course):
```{r mcmc1}
library(fmcmc)
# Running the MCMC (we set the seed first)
set.seed(1215)
ans <- MCMC(
ll,
initial = c(0, 0, sd(y)),
nsteps = 5000,
X. = X,
y. = y
)
```
As the output object is an object of class `mcmc` from the `coda` R package, we
can use all the functions from it on our output:
```{r first-diagnostics}
library(coda)
plot(ans)
summary(ans)
```
While the summary statistics look very good (we got very close to the original
parameters), the trace of the parameters looks very bad (poor mixing). We can
re-run the algorithm changing the scale parameter in the `kernel_normal` function.
To do so, we can pass `ans` as the `initial` argument so that
the function starts from the last point of that chain:
```{r summary-and-plot1}
ans <- MCMC(
ll,
initial = ans,
nsteps = 5000,
X. = X,
y. = y,
kernel = kernel_normal(scale = .05) # We can set the scale parameter like this
)
plot(ans)
```
Much better! Now, what if we use Vihola (2012) Robust Adaptive Metropolis (which
is also implemented in the R package [adaptMCMC](https://cran.r-project.org/package=adaptMCMC))
```{r summary-and-plot-ram}
ans_RAM <- MCMC(
ll,
initial = ans,
nsteps = 5000,
X. = X,
y. = y,
kernel = kernel_ram()
)
plot(ans_RAM)
1 - rejectionRate(ans_RAM)
```
We can also try using Haario et al. (2001) Adaptive Metropolis
```{r summary-and-plot-adapt}
ans_AM <- MCMC(
ll,
initial = ans,
nsteps = 5000,
X. = X,
y. = y,
kernel = kernel_adapt()
)
plot(ans_AM)
1 - rejectionRate(ans_AM)
```
Finally, if needed, we can also access information about the last run using `MCMC_OUTPUT`.
For example, if we wanted to look at the trace of the logposterior function, we could
use the `get_logpost()` function:
```{r get_}
plot(get_logpost(), type = "l")
```
The set of proposed values is also available using the `get_draws()` function:
```{r get_draws}
boxplot(get_draws(), type = "l")
```
If the previous run featured multiple chains, then `get_logpost()` would return a list
instead of length `get_nchains()`.
## Automatic stop
Now, suppose that the algorithm actually takes a lot of time to actually reach
stationary state, then it would be nice to actually sample from the posterior
distribution once convergence has been reached. In the following example we
use multiple chains and the Gelman-Rubin diagnostic to check for convergence of the
chain:
```{r mcmc2}
set.seed(1215) # Same seed as before
ans <- MCMC(
ll,
initial = c(0, 0, sd(y)),
nsteps = 5000,
X. = X,
y. = y,
kernel = kernel_normal(scale = .05),
nchains = 2, # Multiple chains
conv_checker = convergence_gelman(200) # Checking for conv. every 200 steps
)
```
As a difference from the previous case, now we didn't have to wait until the 5,000
completed, but the algorithm stopped for us, allowing us to start generating
the desired sample much quicker.
## Kernels: Making sure that we get positive values
For this final example, we will use the `kernel` argument and provide what
corresponds to a transition kernel which makes proposals within certain boundaries,
in particular, we want the algorithm to propose only positive values for the `sd`
parameter, which we now must be positive.
Moreover, since we know that we will only get positive values, we
can go further and modify `ll` skipping the check for finite values:
```{r ll2}
ll <- function(p, X., y.) {
sum(dnorm(y. - (p[1] + X.*p[2]), sd = p[3], log = TRUE))
}
```
Much simpler function! Let's do the call of the MCMC function specifying the
right transition kernel to increase the acceptance rate. In this example, we will
set the max of all parameters to be 5.0, and the min to be -5.0 for the constant
and 0 for the beta coefficient and the variance parameter, all this using the
`kernel_normal_reflective` (which implements a normal kernel with boundaries) function:
```{r mcmc3}
set.seed(1215) # Same seed as before
ans <- MCMC(
ll,
initial = c(0, 0, sd(y)),
nsteps = 5000,
X. = X,
y. = y,
kernel = kernel_normal_reflective(
ub = 5.0, # All parameters have the same upper bound
lb = c(-5.0, 0.0, 0.0), # But lower bound is specified per parameter
scale = 0.05 # This is the same scale as before
),
nchains = 2,
conv_checker = convergence_gelman(200)
)
```
Again, as the proposal kernel has lower and upper bounds, then we are guaranteed
that all proposed states are within the support of the parameter space.
# Other tools
`fmcmc` is just one way to work with Markov Chain Monte Carlo. Besides `stan` and
`WinBUGS`, there are other ways to do MCMC in R: [mcmc](https://cran.r-project.org/package=mcmc),
[HybridMC](https://cran.r-project.org/package=HybridMC), [adaptMCMC](https://cran.r-project.org/package=adaptMCMC), and
[elhmc](https://cran.r-project.org/package=elhmc) among others (take a look at
the [CRAN Task View on Bayesian Inference](https://CRAN.R-project.org/view=Bayesian).)
# Contributing to `fmcmc`
We welcome contributions to `fmcmc`. Whether reporting a bug, starting a discussion by asking a question, or proposing/requesting a new feature, please go by creating a new issue [here](https://github.com/USCbiostats/fmcmc/issues) so that we can talk about it.
Please note that the 'fmcmc' project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By contributing to this project, you agree to abide by its terms.
# Funding
Supported by National Cancer Institute Grant #1P01CA196596.