-
Notifications
You must be signed in to change notification settings - Fork 14
/
Bayes_intro.Rmd
1605 lines (992 loc) · 32.1 KB
/
Bayes_intro.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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: |
| An introduction to Bayesian modelling
| with R, JAGS and STAN
author: "Francisco Rodriguez-Sanchez (@frod_san)"
date: "November 2016"
fontsize: 9pt
output:
beamer_presentation:
df_print: kable
fig_caption: no
fig_height: 6
fig_width: 7
includes:
in_header: header.tex
latex_engine: pdflatex
slide_level: 2
theme: metropolis
---
```{r knitr_setup, include=FALSE, cache=FALSE}
library(knitr)
### Chunk options ###
## Text results
opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, eval = TRUE, size = 'footnotesize')
## Code decoration
opts_chunk$set(tidy = FALSE, comment = NA, highlight = TRUE, prompt = FALSE, crop = TRUE)
# ## Cache
opts_chunk$set(cache = TRUE, cache.path = "knitr_output/cache/")
# ## Plots
opts_chunk$set(fig.path = "knitr_output/figures/")
opts_chunk$set(fig.align = 'center')
### Hooks ###
## Crop plot margins
knit_hooks$set(crop = hook_pdfcrop)
## Reduce font size
# see http://stackoverflow.com/a/39961605
knit_hooks$set(smallfont = function(before, options, envir) {
if (before) return(paste0("\n \\", options$size, "\n\n"))
else return("\n\n \\normalsize \n")
})
```
## Bayesian modelling is growing fast
```{r out.width='4in', out.height='2in'}
include_graphics("images/Clark2005_title.png")
```
- Powerful
- Flexible
- Knowledge synthesis
- Uncertainty
----
Even if you don't become Bayesian today,
this workshop will help you to understand
regression and 'mixed-effects' models better.
----
*The purpose of models is not to fit data,*
*but to sharpen the questions*
Samuel Karlin
## Practical workshop: we'll see main concepts, but do read the literature!
**General**
- [Data analysis using regression and multilevel/hierarchical models](http://www.stat.columbia.edu/~gelman/arm/)
- [Statistical Rethinking: A Bayesian Course with Examples in R and Stan](http://xcelab.net/rm/statistical-rethinking/)
- [Bayesian data analysis](http://www.stat.columbia.edu/~gelman/book/)
- [The BUGS book](http://www.crcpress.com/product/isbn/9781584888499)
- [Doing Bayesian data analysis: a tutorial with R, JAGS, and STAN](https://sites.google.com/site/doingbayesiandataanalysis/)
- [Bayesian linear mixed models using Stan: a tutorial](http://www.tqmp.org/RegularArticles/vol12-3/p175/p175.pdf)
- [Bayesian basics](http://m-clark.github.io/docs/IntroBayes.html)
- [Philosophy and the practice of Bayesian statistics](http://www.stat.columbia.edu/~gelman/research/published/philosophy.pdf)
## Practical workshop: we'll see main concepts, but do read the literature!
**Ecology-oriented**
- [The ecological detective: confronting models with data](http://press.princeton.edu/titles/5987.html)
- [Bayesian methods for ecology](http://www.cambridge.org/us/academic/subjects/life-sciences/ecology-and-conservation/bayesian-methods-ecology)
- [Models for ecological data](http://press.princeton.edu/titles/8348.html)
- [Introduction to WinBUGS for ecologists](http://www.mbr-pwrc.usgs.gov/software/kerybook/)
- [Applied hierarchical modeling in ecology](http://www.mbr-pwrc.usgs.gov/pubanalysis/keryroylebook/)
- [Bayesian Models: A Statistical Primer for Ecologists](http://press.princeton.edu/titles/10523.html)
- and more...
## Bayesian modelling software
- WinBUGS/OpenBUGS
- JAGS
- STAN
- Filzbach
- Nimble
- Many R packages: MCMCpack, MCMCglmm, LaplacesDemon, r-inla, etc (see [Bayesian task view](http://cran.r-project.org/web/views/Bayesian.html))
## We'll focus on JAGS and STAN
- Fast, powerful, and most popular
- Similar to BUGS
- Easy to start
- Open-ended modelling: deal with complex models too
- But look for specific implementations of your analysis (e.g. hSDM, rstanarm)
- Once concepts understood, switching software not difficult
## JAGS has to be installed independently
http://mcmc-jags.sourceforge.net/
Use latest version (4.2.0)
## Calling JAGS from R
- [rjags](https://cran.r-project.org/package=rjags)
- [R2jags](https://cran.r-project.org/package=R2jags)
- [runjags](https://cran.r-project.org/web/packages/runjags/)
- [jagsUI](https://cran.r-project.org/package=jagsUI)
- [dclone](https://cran.r-project.org/package=dclone)
- [rube](http://stat.cmu.edu/~hseltman/rube/)
## Calling STAN from R
- [rstan](https://cran.r-project.org/package=rstan)
- [rstanarm](https://cran.r-project.org/package=rstanarm)
- [rethinking](https://github.com/rmcelreath/rethinking)
- [brms](https://cran.r-project.org/package=brms)
## We will also need these R packages:
```{r echo=TRUE, eval=FALSE, cache=FALSE}
library(arm)
library(R2jags)
library(ggmcmc)
library(shinystan)
library(rube)
library(lme4)
library(rstan)
library(rstanarm)
```
and their dependencies
# The very basics: linear regression
## The very basics: linear regression
\begincols
\begincol
```{r reg1, echo=FALSE, fig.align='left', fig.height=5, fig.width=4}
data(iris)
setosa <- iris[iris$Species == "setosa", ]
plot(setosa[,3], setosa[,4], xlab = "x", ylab = "y", ylim = c(0,0.65),
pch=19, las = 1, cex.lab = 1.5)
abline(lm(setosa[,4] ~ setosa[,3]), lwd = 3)
```
\endcol
\begincol
$$
y_{i} = a + bx_{i} + \epsilon_{i}
$$
**How many parameters?**
\endcol
\endcols
## The very basics: linear regression
\begincols
\begincol
```{r out.width='2in', out.height='2in'}
include_graphics("images/normal_distr.png")
```
\endcol
\begincol
$$
\begin{aligned}
y_{i} = a + bx_{i} + \epsilon_{i} \\
\epsilon_{i} \sim N(0, \sigma^2)
\end{aligned}
$$
Or also
$$
\begin{aligned}
y_{i} \sim N(\mu_{i}, \sigma^2) \\
\mu_{i} = a + bx_{i}
\end{aligned}
$$
\endcol
\endcols
## Our dataset: tree heights and DBH
http://tinyurl.com/treesdata
- One species
- 10 plots
- 1000 trees
- Number of trees per plot ranging from 4 to 392
```{r echo=TRUE}
trees <- read.csv("trees.csv")
summary(trees[, 1:3])
```
## What's the relationship between DBH and height?
```{r echo=FALSE}
plot(trees$dbh, trees$height, pch=20, las=1, cex.lab=1.4, xlab="DBH (cm)", ylab="Height (m)")
```
## First step: linear regression (lm)
```{r lm, echo=TRUE, message=FALSE}
simple.lm <- lm(height ~ dbh, data = trees)
arm::display(simple.lm) # summary of key model elements
```
**Interpretation?**
## Always centre continuous variables
```{r echo=TRUE}
summary(trees$dbh)
trees$dbh.c <- trees$dbh - 25
```
So, all parameters will be referred to a 25 cm DBH tree.
## Linear regression with centred DBH
\begincols
\begincol
```{r echo=FALSE, fig.align='left', fig.width=4, fig.height=4}
plot(trees$dbh.c, trees$height, pch=20, las=1, cex.lab=1.4, xlab="DBH (cm)", ylab="Height (m)")
abline(lm(height ~ dbh.c, data=trees), col="red", lwd=3)
```
\endcol
\begincol
```{r echo=FALSE, smallfont=TRUE, cache=FALSE}
library(arm)
simple.lm <- lm(height ~ dbh.c, data = trees)
display(simple.lm)
```
\endcol
\endcols
## Let's make it Bayesian
**Things we'll need**
- A function describing the model (including **priors**)
- Data
- Choose parameters to save
- Define initial values for MCMC chains
- Decide number of iterations (and burnin)
## Remember our model structure
$$
\begin{aligned}
y_{i} \sim N(\mu_{i}, \sigma^2) \\
\mu_{i} = \alpha + \beta x_{i}
\end{aligned}
$$
In this case:
$$
\begin{aligned}
Height_{i} \sim N(\mu_{i}, \sigma^2) \\
\mu_{i} = \alpha + \beta DBH_{i}
\end{aligned}
$$
$\alpha$: expected height when DBH = 0
$\beta$: how much height increases with every unit increase of DBH
## JAGS uses precision instead of variance
$$
\tau = \frac{1}{\sigma^2}
$$
So, residual variance $\sigma^2 = 100$ expressed as $\tau = 0.01$.
## Specify the model as an R function
$$
\begin{aligned}
Height_{i} \sim N(\mu_{i}, \sigma^2) \\
\mu_{i} = \alpha + \beta DBH_{i}
\end{aligned}
$$
```{r echo=TRUE}
bayes.lm <- function(){
# LIKELIHOOD
for (i in 1:length(height)){
height[i] ~ dnorm(mu[i], tau) # tau=precision (inverse var)
mu[i] <- alpha + beta*dbhc[i] # expected height ~ dbhc
}
}
```
## We need priors for every parameter!
```{r echo=TRUE, smallfont=TRUE}
bayes.lm <- function(){
# LIKELIHOOD
for (i in 1:length(height)){
height[i] ~ dnorm(mu[i], tau) # tau = precision (inverse var)
mu[i] <- alpha + beta*dbhc[i] # expected height ~ dbhc
}
# PRIORS (vague or weakly informative)
alpha ~ dunif(1, 100) # prior avg height of 25-cm-DBH tree
beta ~ dunif(0, 10) # how much do we expect height to scale with DBH?
tau <- 1/(sigma*sigma) # tau = 1/sigma^2
sigma ~ dunif(0, 50) # residual standard deviation
}
```
## A note on priors
Avoid 'non-informative' priors (see [this](http://andrewgelman.com/2013/11/21/hidden-dangers-noninformative-priors/) and [this](https://normaldeviate.wordpress.com/2013/07/13/lost-causes-in-statistics-ii-noninformative-priors/))
Use *weakly informative* (e.g. bounded Uniform, Normal with reasonable parameters, Cauchy...)
or *strongly informative* priors based on previous knowledge and common sense.
Some tips for setting priors:
- https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations
- http://www.mrc-bsu.cam.ac.uk/wp-content/uploads/bugsbook_chapter5.pdf
Usually good idea to try different priors and evaluate posterior sensitivity
Or run model without likelihood (priors only).
## Example: estimating people height across countries
\begincols
\begincol
Unreasonable prior
```{r echo=1, fig.height=3, fig.width=3, fig.align='left'}
plot(density(rnorm(1000, 0, 1000)),
main="", xlab="Height (m)")
```
\endcol
\begincol
Reasonable prior
```{r echo=1, fig.height=3, fig.width=3, fig.align='left'}
plot(density(rnorm(1000, 2, 0.5)),
main="", xlab="Height (m)")
```
\endcol
\endcols
(*from STAN manual*)
## We already have our model definition
```{r echo=TRUE}
bayes.lm <- function(){
# LIKELIHOOD
for (i in 1:length(height)){
height[i] ~ dnorm(mu[i], tau) # tau = precision (inverse of variance)
mu[i] <- alpha + beta*dbhc[i] # centred diameter
}
# PRIORS (vague or weakly informative)
alpha ~ dunif(1, 100) # prior for average height of a 25-cm-DBH tree
beta ~ dunif(0, 10) # how much do we expect height to scale with DBH?
tau <- 1/(sigma*sigma) # tau = 1/sigma^2
sigma ~ dunif(0, 50) # residual standard deviation
}
```
## Next step: create list with data
Data = known values
```{r echo=TRUE}
data <- list(height = trees$height, # response
dbhc = trees$dbh.c) # predictor
```
## Next step: choose parameters to save
```{r echo=TRUE}
params <- c("alpha", "beta", "sigma")
```
## Now call JAGS to run the model
```{r echo=TRUE, cache=FALSE}
library(R2jags)
```
```{r echo=TRUE, results='hide'}
m1 <- jags(data,
model.file = bayes.lm,
parameters.to.save = params,
n.chains = 3,
inits = NULL, # JAGS will create inits for each chain
n.iter = 10, # number of iterations
n.burnin = 5) # iterations to discard (before convergence)
```
## Traceplots: viewing MCMC in action
```{r echo=1, fig.height=5, fig.width=6}
traceplot(m1, ask = FALSE, mfrow = c(2, 2))
par(mfrow=c(1,1))
```
Obviously we haven't achieved convergence yet...
## Viewing MCMC in action (II)
[![](images/metrop.gif)](http://mbjoseph.github.io/images/metrop.gif)
Source: http://mbjoseph.github.io/2013/09/08/metropolis.html
## Let's run JAGS for longer
```{r echo=TRUE, results='hide'}
m1 <- jags(data,
model.file = bayes.lm,
parameters.to.save = params,
n.chains = 3,
inits = NULL,
n.iter = 10000, # 10000 MCMC iterations
n.burnin = 5000) # discard first half (5000 iterations)
```
## Use traceplots to asess convergence
```{r echo=1}
traceplot(m1, ask = FALSE, mfrow = c(2, 2))
par(mfrow=c(1,1))
```
## Results: parameter estimates
```{r echo=FALSE}
print(m1, intervals=c(0.025, 0.975))
```
## Compare with `simple.lm`
```{r}
display(simple.lm)
```
Results pretty similar, because of vague priors
## A plot of the whole model
```{r fig.height=7, fig.width=9}
plot(m1)
```
# Model checking
## Using ggmcmc to produce diagnostic plots
```{r echo=TRUE}
suppressPackageStartupMessages(library(ggmcmc))
m1.mcmc <- as.mcmc(m1) # Get list of MCMC values
m1.tidy = ggs(m1.mcmc) # Produce tidy data frame
ggmcmc(m1.tidy)
```
This generates a PDF file with diagnostic plots for all parameters! (`ggmcmc-output.pdf`)
## ggmcmc output sample
\begincols
\begincol
```{r}
include_graphics("images/ggmcmc_out1.png")
```
\endcol
\begincol
```{r}
include_graphics("images/ggmcmc_out2.png")
```
\endcol
\endcols
## shinystan: assess model interactively
```{r eval=FALSE, echo=TRUE}
library(shinystan)
launch_shinystan(as.shinystan(m1.mcmc))
```
## Comparing prior and posterior
```{r echo=FALSE, eval=FALSE}
curve(dunif(x, 1, 100), from = 1, to = 100,
lwd = 2, col = "red", main="Height of average 25-cm DBH tree (alpha)", xlab="Height (m)", ylab = "",
las = 1, ylim = c(0, 0.1))
lines(density(m1$BUGSoutput$sims.list$alpha), lwd=2, col="blue")
legend("topright", c("prior", "posterior"), col = c("red", "blue"), lty = 1, bty = "n")
```
## Comparing prior and posterior
```{r echo=TRUE, cache=FALSE}
library(rube)
priPost(post = m1$BUGSoutput$sims.list$alpha[, 1],
dist = "Uniform", pripar = c(1, 100))
```
## Comparing prior and posterior (sigma)
```{r echo=TRUE}
priPost(post = m1$BUGSoutput$sims.list$sigma[, 1],
dist = "Uniform", pripar = c(0, 50))
```
## Observed vs Predicted values
```{r echo=FALSE}
alpha.avg <- mean(m1$BUGSoutput$sims.list$alpha)
beta.avg <- mean(m1$BUGSoutput$sims.list$beta)
mu <- alpha.avg + beta.avg*trees$dbh.c
plot(trees$height, mu,
xlim = c(0, 60), ylim = c(0, 60),
xlab = "Observed height (m)", ylab = "Predicted height (m)")
abline(a = 0, b = 1)
```
How would you do this?
## Observed vs Predicted values
```{r echo=TRUE, fig.height=3, fig.width=4}
alpha.avg <- mean(m1$BUGSoutput$sims.list$alpha)
beta.avg <- mean(m1$BUGSoutput$sims.list$beta)
mu <- alpha.avg + beta.avg*trees$dbh.c
plot(trees$height, mu,
xlim = c(0, 60), ylim = c(0, 60),
xlab = "Observed height (m)", ylab = "Predicted height (m)")
abline(a = 0, b = 1)
```
## Residuals
```{r echo=FALSE}
residuals <- trees$height - mu
hist(residuals)
```
## posterior predictive distribution
# Now using Normal vague priors
## Model with Normal priors
```{r echo=TRUE}
bayes.lm.N <- function(){
# LIKELIHOOD
for (i in 1:length(height)){
height[i] ~ dnorm(mu[i], tau) # tau = precision (inverse of variance)
mu[i] <- alpha + beta*dbhc[i] # centred diameter
}
# PRIORS
alpha ~ dnorm(0, 0.01) # prior for intercept
beta ~ dnorm(0, 0.01) # prior for beta (slope)
tau <- 1/(sigma*sigma) # tau = 1/sigma^2
sigma ~ dunif(0, 50) # residual standard deviation
}
```
## Calling JAGS
```{r echo=TRUE, results='hide'}
m1b <- jags(data,
model.file = bayes.lm.N,
parameters.to.save = params,
n.chains = 3,
inits = NULL,
n.iter = 4000,
n.burnin = 2000)
```
## Results with Normal priors on intercept and slope
```{r echo=FALSE}
print(m1b, intervals=c(0.025, 0.975))
```
Very similar
## Let's try strongly informative prior on alpha
```{r echo=TRUE}
bayes.lm.N2 <- function(){
# LIKELIHOOD
for (i in 1:length(height)){
height[i] ~ dnorm(mu[i], tau) # tau = precision (inverse of variance)
mu[i] <- alpha + beta*dbhc[i] # centred diameter
}
# PRIORS
alpha ~ dnorm(10, 10) # prior for intercept
beta ~ dnorm(0, 0.01) # prior for beta (slope)
tau <- 1/(sigma*sigma) # tau = 1/sigma^2
sigma ~ dunif(0, 50) # residual standard deviation
}
```
## Calling JAGS
```{r echo=TRUE, results='hide'}
m1c <- jags(data,
model.file = bayes.lm.N2,
parameters.to.save = params,
n.chains = 3,
inits = NULL,
n.iter = 4000,
n.burnin = 2000)
```
## Posteriors: between prior and likelihood
```{r echo=FALSE}
print(m1c, intervals=c(0.025, 0.975))
```
## Prior vs Posterior
```{r echo=TRUE}
priPost(post = m1c$BUGSoutput$sims.list$alpha[,1],
dist = "Normal", pripar = c(10, 0.1))
```
# Bayesian inference
## Bayes theorem: prior, likelihood, posterior
$$
P(Hypothesis | Data) = \frac{P(Data | Hypothesis) P(Hypothesis)}{P(Data)}
$$
$$
P(Hypothesis | Data) \propto P(Data | Hypothesis) \times P(Hypothesis)
$$
$$
Posterior \propto Likelihood \times Prior
$$
Hence, prior influence decreases with size of data set.
# Varying-intercept models
## Accounting for plot effects
```{r echo=FALSE}
#plot <- as.numeric(levels(trees$plot))[trees$plot]
plot.id <- factor(trees$plot)
plot(trees$dbh[plot.id==1], trees$height[plot.id==1],
pch=20, las=1, cex.lab=1.4, xlab="DBH (cm)", ylab="Height (m)", col=1,
ylim=c(0,60))
for(i in 2:10){
points(trees$dbh[plot.id==i], trees$height[plot.id==i], pch=20, col=i)
}
```
**Do it yourself using lm**
## lm results
```{r echo = 1}
lm.plot <- lm(height ~ factor(plot) + dbh.c, data = trees)
display(lm.plot)
```
**Interpretation?**
## Single vs varying intercept
\begincols
\begincol
```{r single_interc, echo=FALSE, fig.height=5, fig.width=4}
plot(height ~ dbh, data=trees, las=1, xlab="DBH (cm)", ylab="Height (m)", ylim = c(0, 60),
main = "Pooling all plots")
abline(lm(height ~ dbh, data=trees), lwd=4, col="red")
```
\endcol
\begincol
```{r varying_interc, echo=FALSE, fig.height=5, fig.width=4}
lm2 <- lm(height ~ factor(plot) + dbh, data = trees)
plot(trees$dbh[plot.id==1], trees$height[plot.id==1],
pch=20, las=1, xlab="DBH (cm)", ylab="Height (m)", col=1,
ylim=c(0,60), main = "Different intercept for each plot")
abline(a=coef(lm2)[1], b=coef(lm2)[11], col=1, lwd=2)
for(i in 2:10){
points(trees$dbh[plot.id==i], trees$height[plot.id==i], pch=20, col=i)
abline(a=coef(lm2)[1] + coef(lm2)[i], b=coef(lm2)[11], col=i, lwd=2)
}
```
\endcol
\endcols
## Let's make it Bayesian
**Things we'll need**
- A function describing the model (including **priors**)
- Data
- Choose parameters to save
- Define initial values for MCMC chains
- Decide number of iterations (and burnin)
## Bayesian varying-intercept model with no pooling
```{r echo=TRUE}
varint.nopool <- function(){
# LIKELIHOOD
for (i in 1:length(height)){
height[i] ~ dnorm(mu[i], tau) # tau = precision (inverse of variance)
mu[i] <- alpha[plot[i]] + beta*dbhc[i] # centred diameter
}
# PRIORS
#alpha ~ dnorm(0, .001) # previous model
for (j in 1:10){
alpha[j] ~ dnorm(0, .001) # Plot effects drawn from Normal distribution
# with large **fixed** variance
}
beta ~ dnorm(0, .001)
tau <- 1/(sigma*sigma) # tau = 1/sigma^2
sigma ~ dunif(0, 50)
}
```
**This fits same model as `lm.plot`**
## Call JAGS
```{r echo=TRUE, results='hide'}
data <- list(height = trees$height,
dbhc = trees$dbh.c,
plot = trees$plot)
m2 <- jags(data,
model.file = varint.nopool,
parameters.to.save = params,
n.chains = 3,
inits = NULL,
n.iter = 4000,
n.burnin = 2000)
```
## Running JAGS in parallel (multiple cores)
```{r echo=TRUE}
m2 <- jags.parallel(data,
model.file = varint.nopool,
parameters.to.save = params,
n.chains = 3,
inits = NULL,
n.iter = 4000,
n.burnin = 2000)
```
## Results of Bayesian varying intercept model without pooling
```{r echo=FALSE}
print(m2, intervals=c(0.025, 0.975))
```
## Same results as `lm.plot`
```{r}
display(lm.plot)
```
## Plot whole model
```{r fig.height=7, fig.width=9, echo=FALSE}
plot(m2)