/
p6.Rmd
464 lines (352 loc) · 15.5 KB
/
p6.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
---
title: 'Practical 6: Software and GLMs'
author: "VIBASS"
output:
html_vignette:
fig_caption: yes
number_sections: yes
toc: yes
fig_width: 6
fig_height: 4
vignette: >
%\VignetteIndexEntry{Practical 6: Software and GLMs}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
collapse = TRUE,
comment = "#>"
)
```
# Software for Bayesian Statistical Analysis
So far, simple Bayesian models with conjugate priors have been
considered. As explained in previous practicals, when the posterior
distribution is not available in closed form, MCMC algorithms such as the
Metropolis-Hastings or
Gibbs Sampling can be used to obtain samples from it.
In general, posterior distributions are seldom available in closed form and
implementing MCMC algorithms for complex models can be technically difficult
and very time-consuming.
For this reason, in this Practical we start by looking at a number of `R`
packages to fit Bayesian statistical models. These packages will equip us
with tools which can be used to deal with more complex models efficiently,
without us having to do a lot of extra coding ourselves. Fitting Bayesian
models in `R` will then be much like fitting non-Bayesian models, using
model-fitting functions at the command line, and using standard syntax for
model specification.
## BayesX and INLA
In particular, the following two software packages will be considered:
* `BayesX`
* `INLA`
`BayesX` (http://www.bayesx.org/) implements MCMC methods to obtain samples
from the joint posterior and is conveniently accessed from R via the package
`R2BayesX`.
`INLA` (https://www.r-inla.org/) is based on producing (accurate)
approximations to the marginal posterior distributions of the model parameters.
Although this can be enough most of the time, making multivariate inference
with `INLA` can be difficult or impossible. However, in many cases this is
not needed and `INLA` can fit some classes of models in a fraction of the
time it takes with MCMC.
Both `R2BayesX` and `INLA` have a very simple interface to define models
using a `formula` (in the same way as with `glm()` and `gam()` functions).
While `R2BayesX` can be installed from CRAN, `INLA` is not on CRAN and
needs to be installed from a specific repository.
## Other Bayesian Software
* Package `MCMCpack` in R contains functions such as `MCMClogit()`, `MCMCPoisson()` and
`MCMCprobit()` for fitting specific kinds of models.
* A classic MCMC program is `BUGS`, (Bayesian Analysis using Gibbs Sampling)
described in Lunn et al. (2000):
[http://www.mrc-bsu.cam.ac.uk/bugs/winbugs/contents.shtml](http://www.mrc-bsu.cam.ac.uk/bugs/winbugs/contents.shtml).
BUGS can be used through graphical interfaces `WinBUGS` and `OpenBUGS`. Both of
these packages can be called from within R using packages `R2WinBUGS` and
`R2OpenBUGS`.
* `JAGS`, which stands for “just another Gibbs sampler”. Can also be called from
R using package `r2jags`.
* The `NIMBLE` package extends `BUGS` and implements MCMC and other methods
for Bayesian inference. You can get it from https://r-nimble.org, and is best
run directly from R.
* The `Stan` software implements Hamiltonian Monte Carlo and other methods for
fit hierarchical Bayesian models. It is available from https://mc-stan.org.
# Bayesian Logistic Regression
## Model Formulation
To summarise the model formulation presented in the lecture, given a response
variable $Y_i$ representing the count of a number of successes from a given
number of trials $n_i$ with success probability $\theta_i$, we have
* $(Y_i \mid \boldsymbol \theta_i) \sim\mbox{Bi}(n_i, \theta_i),\,\, i.i.d.\,\,, i=1, \ldots, m$
\begin{align*}
\mbox{logit}(\theta_i) & =\eta_i \nonumber\\
\eta_{i} & =\beta_0+\beta_1 x_{i1}+\ldots+\beta_p x_{ip}=\boldsymbol x_i\boldsymbol \beta\nonumber
\end{align*}
assuming the logit link function and with linear predictor $\eta_{i}$.
## Example: Fake News
The `fake_news` data set in the `bayesrules` package in `R` contains
information about 150 news articles, some real news and some fake news.
In this example, we will look at trying to predict whether an article of news
is fake or not given three explanatory variables.
We can use the following code to extract the variables we want from the
data set:
```{r}
library(bayesrules)
fakenews <- fake_news[,c("type","title_has_excl","title_words","negative")]
```
The response variable `type` takes values `fake` or `real`, which should be
self-explanatory. The three explanatory variables are:
* `title_has_excl`, whether or not the article contains an excalamation mark (values `TRUE` or `FALSE`);
* `title_words`, the number of words in the title (a positive integer); and
* `negative`, a sentiment rating, recorded on a continuous scale.
In the exercise to follow, we will examine whether the chance of an article
being fake news is related to the three covariates here.
## Fitting Bayesian Logistic Regression Models
`BayesX` makes inference via MCMC, via the `R2BayesX` package which as noted
makes the syntax for model fitting very similar to that for fitting
non-Bayesian models using `glm()` in R. If you do not yet have it installed,
you can install it in the usual way from CRAN.
The package must be loaded into R:
```{r}
library(R2BayesX)
```
The syntax for fitting a Bayesian Logistic Regression Model with one response
variable and three explanatory variables will be like so:
```{r eval=FALSE}
model1 <- bayesx(formula = y ~ x1 + x2 + x3,
data = data.set,
family = "binomial")
```
Alternatively, we can obtain a Bayesian model fit without using MCMC with the
INLA software, implemented in R via the `INLA` package. If you do not have this
package installed already, as it is not on CRAN you will need to install it via
```{r eval=FALSE}
install.packages("INLA",repos=c(getOption("repos"),INLA="https://inla.r-inla-download.org/R/stable"), dep=TRUE)
```
After this, the package can be loaded into R:
```{r}
library(INLA)
```
## Model Fitting
Note that the variable `title_has_excl` will need to be either replaced by or
converted to a factor, for example
```{r}
fakenews$titlehasexcl <- as.factor(fakenews$title_has_excl)
```
Functions `summary` and `confint` produce a summary (including parameter
estimates etc) and confidence intervals for the parameters, respectively.
In order to be able to obtain output plots from BayesX, it seems that we need
to create a new version of the response variable of type logical:
```{r}
fakenews$typeFAKE <- fakenews$type == "fake"
```
## Exercises
* Perform an exploratory assessment of the fake news data set, in particular
looking at the possible relationships between the explanatory variables
and the fake/real response variable `typeFAKE`. You may wish to use the R
function `boxplot()` here.
<details><summary>Solution</summary>
```{r fig = TRUE}
# Is there a link between the fakeness and whether the title has an exclamation mark?
table(fakenews$title_has_excl, fakenews$typeFAKE)
# For the quantitative variables, look at boxplots on fake vs real
boxplot(fakenews$title_words ~ fakenews$typeFAKE)
boxplot(fakenews$negative ~ fakenews$typeFAKE)
```
</details>
* Fit a Bayesian model in BayesX using the fake news `typeFAKE` variable as
response and the others as covariates. Examine the output; does the model fit
well, and is there any evidence that any of the explanatory variables are
associated with changes in probability of an article being fake or not?
<details><summary>Solution</summary>
```{r fig = TRUE}
# Produce the BayesX output
bayesx.output <- bayesx(formula = typeFAKE ~ titlehasexcl + title_words + negative,
data = fakenews,
family = "binomial",
method = "MCMC",
iter = 15000,
burnin = 5000)
summary(bayesx.output)
confint(bayesx.output)
```
</details>
* Produce plots of the MCMC sample traces and the estimated posterior
distributions for the model parameters. Does it seem like convergence has been
achieved?
<details><summary>Solution</summary>
```{r fig = TRUE, fig.width = 5, fig.height = 10}
# Traces can be obtained separately
plot(bayesx.output,which = "coef-samples")
```
```{r fig = TRUE}
# And the density plots one-by-one
par(mfrow=c(2,2))
plot(density(samples(bayesx.output)[,"titlehasexclTRUE"]),main="Title Has Excl")
plot(density(samples(bayesx.output)[,"title_words"]),main="Title Words")
plot(density(samples(bayesx.output)[,"negative"]),main="Negative")
```
</details>
* Fit the Bayesian model without MCMC using `INLA`; note that the summary output
provides credible intervals for each parameter to help us make inference.
Also, in INLA a Binomial response needs to be entered as type integer, so we
need another conversion:
```{r}
fakenews$typeFAKE.int <- as.integer(fakenews$typeFAKE)
```
<details><summary>Solution</summary>
```{r fig = TRUE}
# Fit model - note similarity with bayesx syntax
inla.output <- inla(formula = typeFAKE.int ~ titlehasexcl + title_words + negative,
data = fakenews,
family = "binomial")
# Summarise output
summary(inla.output)
```
</details>
* Fit a non-Bayesian model using `glm()` for comparison. How do the model fits
compare?
<details><summary>Solution</summary>
```{r fig = TRUE}
# Fit model - note similarity with bayesx syntax
glm.output <- glm(formula = typeFAKE ~ titlehasexcl + title_words + negative,
data = fakenews,
family = "binomial")
# Summarise output
summary(glm.output)
# Perform ANOVA on each variable in turn
drop1(glm.output,test="Chisq")
```
</details>
# Bayesian Poisson Regression
## Model Formulation
To summarise the model formulation presented in the lecture, given a response
variable $Y_i$ representing the counts occurring from a process with mean
parameter $\lambda_i$:
* $(Y_i \mid \boldsymbol \lambda_i) \sim\mbox{Po}(\lambda_i),\,\, i.i.d.\,\,, i=1, \ldots, n$
\begin{align*}
\mbox{log}(\lambda_i) & =\eta_i \nonumber\\
\eta_{i} & =\beta_0+\beta_1 x_{i1}+\ldots+\beta_p x_{ip}=\boldsymbol x_i\boldsymbol \beta\nonumber
\end{align*}
assuming the log link function and with linear predictor $\eta_{i}$.
## Example: Emergency Room Complaints
For this example we will use the `esdcomp` data set, which is available in the
`faraway` package. This data set records complaints about emergency room
doctors. In particular, data was recorded on 44 doctors working in an
emergency service at a hospital to study the factors affecting the number of
complaints received.
The response variable that we will use is `complaints`, an integer count of the
number of complaints received. It is expected that the number of complaints will
scale by the number of visits (contained in the `visits` column), so we are
modelling the rate of complaints per visit - thus we will need to include a new
variable `log.visits` as an offset.
The three explanatory variables we will use in the analysis are:
* `residency`, whether or not the doctor is still in residency training (values
`N` or `Y`);
* `gender`, the gender of the doctor (values `F` or `M`); and
* `revenue`, dollars per hour earned by the doctor, recorded as an integer.
Our simple aim here is to assess whether the seniority, gender or income of the
doctor is linked with the rate of complaints against that doctor.
We can use the following code to extract the data we want without having to load
the whole package:
```{r}
esdcomp <- faraway::esdcomp
```
## Fitting Bayesian Poisson Regression Models
Again we can use `BayesX` and `INLA` to fit this form of Bayesian generalised
linear model.
If not loaded already, the packages must be loaded into R:
```{r echo=FALSE}
library(R2BayesX)
library(INLA)
```
In BayesX, the syntax for fitting a Bayesian Poisson Regression Model with one
response variable, three explanatory variables and an offset will be like so:
```{r eval=FALSE}
model1 <- bayesx(formula = y~x1+x2+x3+offset(w),
data = data.set,
family="poisson")
```
As noted above we need to include an offset in this analysis; since
for a Poisson GLM we will be using a log() link function by default, we must
compute the log of the number of visits and include that in the data set
`esdcomp`:
```{r}
esdcomp$log.visits <- log(esdcomp$visits)
```
The offset term in the model is then written
`offset(log.visits)`
in the call to `bayesx`.
## Exercises
* Perform an exploratory assessment of the emergency room complaints data set,
particularly how the response variable `complaints` varies with the proposed
explanatory variables relative to the number of visits. To do this, create
another variable which is the ratio of `complaints` to `visits`.
<details><summary>Solution</summary>
```{r fig = TRUE}
# Compute the ratio
esdcomp$ratio <- esdcomp$complaints / esdcomp$visits
# Plot the link with revenue
plot(esdcomp$revenue,esdcomp$ratio)
# Use boxplots against residency and gender
boxplot(esdcomp$ratio ~ esdcomp$residency)
boxplot(esdcomp$ratio ~ esdcomp$gender)
```
</details>
* Fit a Bayesian model in BayesX using the `complaints` variable as Poisson
response and the others as covariates. Examine the output; does the model fit
well, and is there any evidence that any of the explanatory variables are
associated with the rate of complaints?
<details><summary>Solution</summary>
```{r fig = TRUE}
# Fit model - note similarity with bayesx syntax
esdcomp$log.visits <- log(esdcomp$visits)
bayesx.output <- bayesx(formula = complaints ~ offset(log.visits) + residency + gender + revenue,
data = esdcomp,
family = "poisson")
# Summarise output
summary(bayesx.output)
```
</details>
* Produce plots of the MCMC sample traces and the estimated posterior
distributions for the model parameters. Does it seem like convergence has been
achieved?
<details><summary>Solution</summary>
```{r fig = TRUE, fig.width = 5, fig.height = 10}
# An overall plot of sample traces and density estimates
# plot(samples(bayesx.output))
# Traces can be obtained separately
plot(bayesx.output,which = "coef-samples")
```
```{r fig = TRUE}
# And the density plots one-by-one
par(mfrow =c(2, 2))
plot(density(samples(bayesx.output)[, "residencyY"]), main = "Residency")
plot(density(samples(bayesx.output)[, "genderM"]), main = "Gender")
plot(density(samples(bayesx.output)[, "revenue"]), main = "Revenue")
```
</details>
* Fit the Bayesian model without MCMC using `INLA`; note that the summary output
provides credible intervals for each parameter to help us make inference.
<details><summary>Solution</summary>
```{r}
# Fit model - note similarity with bayesx syntax
inla.output <- inla(formula = complaints ~ offset(log.visits) + residency + gender + revenue,
data = esdcomp,
family = "poisson")
# Summarise output
summary(inla.output)
```
</details>
* Fit a non-Bayesian model using `glm()` for comparison. How do the model fits
compare?
<details><summary>Solution</summary>
```{r fig = TRUE}
# Fit model - note similarity with bayesx syntax
esdcomp$log.visits <- log(esdcomp$visits)
glm.output <- glm(formula = complaints ~ offset(log.visits) + residency + gender + revenue,
data = esdcomp,
family = "poisson")
# Summarise output
summary(glm.output)
# Perform ANOVA on each variable in turn
drop1(glm.output, test = "Chisq")
```
</details>