-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathBayesianStatistics_OGimenez.Rmd
executable file
·2860 lines (1996 loc) · 83.2 KB
/
BayesianStatistics_OGimenez.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: "Bayesian statistics"
author: "Olivier Gimenez"
date: "July 2020"
output:
beamer_presentation:
fig_caption: no
includes:
in_header: header.tex
latex_engine: pdflatex
slide_level: 2
theme: metropolis
ioslides_presentation: default
classoption: aspectratio=169
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(cache = TRUE,
echo = TRUE,
message = FALSE,
warning = FALSE,
fig.height=6,
fig.width = 1.777777*6,
tidy = FALSE,
comment = NA,
highlight = TRUE,
prompt = FALSE,
crop = TRUE,
comment = "#>",
collapse = TRUE)
knitr::opts_knit$set(width = 60)
library(tidyverse)
library(reshape2)
theme_set(theme_light(base_size = 16))
make_latex_decorator <- function(output, otherwise) {
function() {
if (knitr:::is_latex_output()) output else otherwise
}
}
insert_pause <- make_latex_decorator(". . .", "\n")
insert_slide_break <- make_latex_decorator("----", "\n")
insert_inc_bullet <- make_latex_decorator("> *", "*")
insert_html_math <- make_latex_decorator("", "$$")
```
## Credit where credit's due
* Ruth King, Byron Morgan, Steve Brooks (our workshops and [\alert{Bayesian analysis for population ecology} book](https://www.maths.ed.ac.uk/~rking33/Book-website/index.html)).
* Richard McElreath ([\alert{Statistical rethinking} book and lecture videos](https://github.com/rmcelreath/statrethinking_winter2019)).
* Jim Albert and Jingchen Hu ([\alert{Probability and Bayesian modelling} book](https://bayesball.github.io/BOOK/probability-a-measurement-of-uncertainty.html)).
* Materials shared by [\alert{Tristan Marh}](https://www.tjmahr.com/), [\alert{Jason Matthiopoulos}](https://www.gla.ac.uk/researchinstitutes/bahcm/staff/jasonmatthiopoulos/), [\alert{Francisco Rodriguez Sanchez}](https://frodriguezsanchez.net/), [\alert{Kerrie Mengersen}](https://staff.qut.edu.au/staff/k.mengersen) and [\alert{Mark Lai}](https://quantscience.rbind.io/).
## Slides codes and data
* All material prepared with `R`.
* `R Markdown` used to write reproducible material.
* Slides available on FigShare [\alert{here}](https://doi.org/10.6084/m9.figshare.12656894.v1).
* Material available on Github [\alert{there}](https://github.com/oliviergimenez/Bayesian_Workshop).
## Objectives
* Try and demystify Bayesian statistics, and what we call MCMC.
* Make the difference between Bayesian and Frequentist analyses.
* Understand the Methods section of ecological papers doing Bayesian stuff.
* Run Bayesian analyses, safely hopefully.
`r insert_slide_break()`
```{r, out.width = '13cm',out.height='7cm',fig.align='center',echo=FALSE}
knitr::include_graphics('img/brace_yourself.jpeg')
```
## What is on our plate?
1. Bayesian inference: Motivation and examples.
2. The likelihood.
3. A detour to explore priors.
4. Markov chains Monte Carlo methods (MCMC).
5. Bayesian analyses in R with the Jags software.
6. Contrast ecological hypotheses with model selection.
7. Heterogeneity and multilevel models (aka mixed models).
# I want moooooore
`r insert_slide_break()`
```{r, out.width = '13cm',out.height='7cm',fig.align='center',echo=FALSE}
knitr::include_graphics('img/books.jpeg')
```
`r insert_slide_break()`
```{r, fig.align = 'center', echo = FALSE}
knitr::include_graphics('img/mccarthy.png')
```
`r insert_slide_break()`
```{r, fig.align = 'center', echo = FALSE}
knitr::include_graphics('img/kery.png')
```
`r insert_slide_break()`
```{r, fig.align = 'center', echo = FALSE}
knitr::include_graphics('img/kruschke.png')
```
`r insert_slide_break()`
```{r, fig.align = 'center', echo = FALSE}
knitr::include_graphics('img/mcelreath.png')
```
`r insert_slide_break()`
```{r, fig.align = 'center', echo = FALSE}
knitr::include_graphics('img/gelmanhill.png')
```
# What is Bayesian inference?
`r insert_slide_break()`

## A reminder on conditional probabilities
`r insert_inc_bullet()` $\Pr(A \mid B)$: Probability of A given B
`r insert_inc_bullet()` The ordering matters: $\Pr(A \mid B)$ is not the same as $\Pr(B \mid A)$.
`r insert_inc_bullet()` $\Pr(A \mid B) = \displaystyle{\frac{\Pr(A \text{ and } B)}{\Pr(B)}}$
`r insert_slide_break()`

## Screening for vampirism
`r insert_inc_bullet()` The chance of the test being positive given you are a vampire is $\Pr(+|\text{vampire}) = 0.90$ (**sensitivity**).
`r insert_inc_bullet()` The chance of a negative test given you are mortal is $\Pr(-|\text{mortal}) = 0.95$ (**specificity**).
## What is the question?
`r insert_inc_bullet()` From the perspective of the test: Given a person is a vampire, what is the probability that the test is positive? $\Pr(+|\text{vampire}) = 0.90$.
`r insert_inc_bullet()` From the perspective of a person: Given that the test is positive, what is the probability that this person is a vampire? $\Pr(\text{vampire}|+) = \; ?$
`r insert_inc_bullet()` Assume that vampires are rare, and represent only $0.1\%$ of the population. This means that $\Pr(\text{vampire}) = 0.001$.
## What is the answer? Bayes' theorem to the rescue!
\begincols
\begincol

\endcol
\begincol
- $\Pr(\text{vampire}|+) = \displaystyle{\frac{\Pr(\text{vampire and } +)}{\Pr(+)}}$
`r insert_pause()`
- $\Pr(\text{vampire and } +) = \Pr(\text{vampire}) \; \Pr(+ | \text{vampire}) = 0.0009$
`r insert_pause()`
- $\Pr(+) = 0.0009 + 0.04995 = 0.05085$
`r insert_pause()`
- $\Pr(\text{vampire}|+) = 0.0009/0.05085 = 0.02$
\endcol
\endcols
`r insert_pause()`
$$\Pr(\text{vampire}|+)= \displaystyle{\frac{ \Pr(+|\text{vampire}) \; \Pr(\text{vampire})}{\Pr(+)}}$$
# Your turn
## Screening for vampirism
* Suppose the diagnostic test has the same sensitivity and specificity but vampirism is more common: $10\%$ of the population is vampire.
* What is the probability that a person is a vampire, given that the test is positive?
# Solution
## The probability that a person is a vampire, given that the test is positive
- $\Pr(+ | \text{vampire}) = 0.9$
- $\Pr(- | \text{mortal}) = 0.95$
- $\Pr(\text{vampire}) = 0.1$
$$\begin{aligned}
\Pr(+) &= \Pr(+ | \text{vampire}) \Pr(\text{vampire}) + \Pr(+ | \text{mortal}) \Pr(\text{mortal}) \\
&= 0.9*0.1 + 0.05*0.9 \\
&=0.135
\end{aligned}
$$
$$\begin{aligned}
\Pr(\text{vampire} | +) &= \Pr(+ | \text{vampire}) \Pr(\text{vampire}) / \Pr(+) \\
&= 0.9*0.1 / 0.135
\end{aligned}
$$
## Bayes' theorem
\begincols
\begincol
* A theorem about conditional probabilities.
* $\Pr(B \mid A) = \displaystyle{\frac{ \Pr(A \mid B) \; \Pr(B)}{\Pr(A)}}$
\endcol
\begincol

\endcol
\endcols
## Bayes' theorem
`r insert_inc_bullet()` Easy to mess up with letters. Might be easier to remember when written like this:
$$ \Pr(\text{hypothesis} \mid \text{data}) = \frac{ \Pr(\text{data} \mid \text{hypothesis}) \; \Pr(\text{hypothesis})}{\Pr(\text{data})} $$
`r insert_inc_bullet()` The "hypothesis" is typically something unobserved or unknown. It's what you want to learn about using the data.
`r insert_inc_bullet()` For regression models, the "hypothesis" is a parameter (intercept, slopes or error terms).
`r insert_inc_bullet()` Bayes theorem tells you the probability of the hypothesis given the data.
## What is doing science after all?
How plausible is some hypothesis given the data?
$$ \Pr(\text{hypothesis} \mid \text{data}) = \frac{ \Pr(\text{data} \mid \text{hypothesis}) \; \Pr(\text{hypothesis})}{\Pr(\text{data})} $$
## Why is Bayesian statistics not the default?
`r insert_inc_bullet()` Due to practical problems of implementing the Bayesian approach, and some wars of male statisticians's egos, little advance was made for over two centuries.
`r insert_inc_bullet()` Recent advances in computational power coupled with the development of new methodology have led to a great increase in the application of Bayesian methods within the last two decades.
## Frequentist versus Bayesian
`r insert_inc_bullet()` Typical stats problems involve estimating parameter $\theta$ with available data.
`r insert_inc_bullet()` The frequentist approach (**maximum likelihood estimation** – MLE) assumes that the parameters are fixed, but have unknown values to be estimated.
`r insert_inc_bullet()` Classical estimates generally provide a point estimate of the parameter of interest.
`r insert_inc_bullet()` The Bayesian approach assumes that the parameters are not fixed but have some fixed unknown distribution - a distribution for the parameter.
## What is the Bayesian approach?
* The approach is based upon the idea that the experimenter begins with some prior beliefs about the system.
`r insert_pause()`
* And then updates these beliefs on the basis of observed data.
`r insert_pause()`
* This updating procedure is based upon the Bayes’ Theorem:
$$\Pr(A \mid B) = \frac{\Pr(B \mid A) \; \Pr(A)}{\Pr(B)}$$
## What is the Bayesian approach?
* Schematically if $A = \theta$ and $B = \text{data}$, then
`r insert_pause()`
* The Bayes' theorem
$$\Pr(A \mid B) = \frac{\Pr(B \mid A) \; \Pr(A)}{\Pr(B)}$$
`r insert_pause()`
* Translates into:
$$\Pr(\theta \mid \text{data}) = \frac{\Pr(\text{data} \mid \theta) \; \Pr(\theta)}{\Pr(\text{data})}$$
## Bayes' theorem
$${\color{red}{\Pr(\theta \mid \text{data})}} = \frac{\color{blue}{\Pr(\text{data} \mid \theta)} \; \color{green}{\Pr(\theta)}}{\color{orange}{\Pr(\text{data})}}$$
`r insert_pause()`
* \textcolor{red}{Posterior distribution}: Represents what you know after having seen the data. The basis for inference, a distribution, possibly multivariate if more than one parameter ($\theta$).
`r insert_pause()`
* \textcolor{blue}{Likelihood}: We know that guy from before, same as in the MLE approach.
`r insert_pause()`
* \textcolor{green}{Prior distribution}: Represents what you know before seeing the data. The source of much discussion about the Bayesian approach.
`r insert_pause()`
* $\color{orange}{\Pr(\text{data}) = \int L(\text{data} \mid \theta) \;\Pr(\theta) d\theta }$: Possibly high-dimensional integral, difficult if not impossible to calculate. This is one of the reasons why we need simulation (MCMC) methods - more soon.
`r insert_slide_break()`
```{r, echo=FALSE, fig.align='center'}
knitr::include_graphics('img/frequentists_vs_bayesians_2x.png')
```
# Likelihood
## Context
`r insert_inc_bullet()` Usually, when talking about probability distributions, we assume that we know the parameter values.
`r insert_inc_bullet()` In the real world, it is usually the other way around.
## A question of interest might be for example:
> We have observed 3 births by a female during her 10 breeding
attempts. What does this tell us about the true probability of
getting a successful breeding attempt from this female? For the population?
`r insert_slide_break()`
* We don’t know what the probability of a birth is.
* But we can calculate the probability of getting our data for different values:
```{r,collapse=TRUE}
dbinom(x=3,size=10,prob=0.1)
```
`r insert_slide_break()`
* We don’t know what the probability of a birth is.
* But we can see what the probability of getting our data would be for different values:
```{r,collapse=TRUE}
dbinom(x=3,size=10,prob=0.9)
```
`r insert_slide_break()`
* We don’t know what the probability of a birth is.
* But we can see what the probability of getting our data would be for different values:
```{r,collapse=TRUE}
dbinom(x=3,size=10,prob=0.25)
```
`r insert_slide_break()`
```{r,collapse=TRUE}
dbinom(x=3,size=10,prob=0.1)
dbinom(x=3,size=10,prob=0.9)
dbinom(x=3,size=10,prob=0.25)
```
So we would be more likely to observe 3 births if the probability is 0.25 than 0.1 or 0.9.
## The likelihood
* This reasoning is so common in statistics that it has a special name:
`r insert_pause()`
* **The likelihood** is the probability of observing the data under a certain model.
`r insert_pause()`
* The data are known, we usually consider the likelihood as a function of the model parameters $\theta_1,\theta_2, \ldots, \theta_p$
$$L = P(\theta_1,\theta_2, \ldots, \theta_p \mid \text{data})$$
## Likelihood functions
We may create a function to calculate a likelihood:
```{r,collapse=TRUE}
lik.fun <- function(parameter){
ll <- dbinom(x=3, size=10, prob=parameter)
return(ll)
}
lik.fun(0.3)
lik.fun(0.6)
```
## Maximize the likelihood (3 successes ot of 10 attempts)
```{r, echo=FALSE}
lik.fun <- function(parameter){
ll <- dbinom(x=3, size=10, prob=parameter)
return(ll)
}
p.grid = seq(0,1,by=0.01)
lik = rep(NA,length(p.grid))
for (i in 1:length(p.grid)){
lik[i] <- lik.fun(p.grid[i])
}
plot(p.grid,lik,xlab='Probability of getting a successful breeding',ylab='Likelihood',type='l',lwd=3,cex.lab=1.5)
abline(v=0.3,lty=2,lwd=2,col='blue')
```
The *maximum* of the likelihood is at value $0.3$
## Maximum likelihood estimation
* There is always a set of parameters that gives you the highest likelihood of observing the data, and this is the MLE.
`r insert_pause()`
* These can be calculated using:
+ Trial and error (not efficient!).
+ Compute the maximum of a function by hand (rarely doable in practice).
+ An iterative optimization algorithm: `?optim` in `R`.
## By hand: compute MLE of $p$ from $Y \sim \text{Bin}(N=10,p)$ with $k=3$ successes
`r insert_inc_bullet()` $P(Y=k) = {{k}\choose{N}} p^k (1-p)^{N-k} = L(p)$.
`r insert_inc_bullet()` $\log(L(p)) = \text{cte} + k \log(p) + (N-k) \log(1-p)$.
`r insert_inc_bullet()` We are searching for the maximum of $L$, or equivalently that of $\log(L)$.
`r insert_inc_bullet()` Compute derivate w.r.t. $p$: $\displaystyle{{{d\log(L)}\over{dp}} = {{k}\over{p}} - {{(N-k)}\over{(1-p)}}}$.
`r insert_inc_bullet()` Then solve $\displaystyle{{{d\log(L)}\over{dp}}=0}$; the MLE is $\displaystyle{\hat{p} = {{k}\over{N}}={{3}\over{10}}=0.3}$.
`r insert_inc_bullet()` Here, the MLE is the proportion of observed successes.
## Using a computer: MLE of $p$ from $Y \sim \text{Bin}(N=10,p)$ with $k=3$ successes
```{r,collapse=TRUE}
lik.fun <- function(parameter) dbinom(x=3, size=10, prob=parameter)
# ?optimize
optimize(lik.fun,c(0,1),maximum=TRUE)
```
Use `optim` when the number of parameters is $> 1$.
## Using a computer: MLE of $p$ from $Y \sim \text{Bin}(N=10,p)$ with $k=3$ successes
```{r, echo=FALSE}
lik.fun <- function(parameter) dbinom(x=3, size=10, prob=parameter)
plot(lik.fun,0,1,xlab="probability of success (p)",ylab="log-likelihood(p)",main="Binomial likelihood with 3 successes ot of 10 attempts",lwd=3,cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5)
abline(v=0.3,h=0.26682,col='blue',lty=2,lwd=2)
```
# Your turn
## MLE of the parameters of a Normal distribution
* Assume we have collected data on the height of 100 people:
```{r}
# set seed for random numbers
set.seed(2020)
# simulate data from Normal distribution
n <- 100
height <- rnorm(n, mean=170, sd=10)
```
`r insert_slide_break()`
```{r echo=FALSE}
data.frame(height=height) %>%
ggplot(aes(x=height))+
geom_histogram(color="blue",fill="dodgerblue") +
labs(x = "Height", y = 'Density')
```
`r insert_slide_break()`
* We consider a Normal distribution for the model.
* Compute the MLE of the parameters of the Normal distribution.
* Hint: Use functions `optim()` and `dnorm()`
# Solution
## `R` code
* Write a function for the likelihood of a Normal distribution with parameters mean $\mu$ and standard deviation $\sigma$:
```{r}
negloglik <- function(theta, data) {
mu <- theta[1]
sigma <- theta[2]
x <- data
-sum(dnorm(x, mean = mu, sd = sigma, log = TRUE))
}
negloglik(theta = c(150,1), height)
```
`r insert_slide_break()`
* Minimiiiiiize
```{r}
fit <- optim(par = c(1,1), fn = negloglik, data = height)
fit
```
`r insert_slide_break()`
```{r, echo = FALSE}
binwidth <- 1
df <- data.frame(x = height) %>%
ggplot(aes(x = height, mean = fit$par[1], sd = fit$par[2], binwidth = binwidth, n = n)) +
geom_histogram(binwidth = binwidth,
colour = "white",
fill = "cornflowerblue",
size = 0.1) +
stat_function(fun = function(x) dnorm(x, mean = fit$par[1], sd = fit$par[2]) * n * binwidth,
color = "darkred", size = 1)
df
```
# Back to Bayes
## A simple example
* Let us take a simple example to fix ideas.
* 120 deer were radio-tracked over winter.
* 61 close to a plant, 59 far from any human activity.
* Question: is there a treatment effect on survival?
| | Released | Alive | Dead | Other |
|------------+----------+-------+------+-------|
| treatment | 61 | 19 | 38 | 4 |
| control | 59 | 21 | 38 | 0 |
`r insert_slide_break()`
`r insert_inc_bullet()` So, $n = 57$ deer were assigned to the treatment group of which $k=19$ survived the winter.
`r insert_inc_bullet()` Of interest is the probability of over-winter survival, call it $\theta$, for the general population within the treatment area.
`r insert_inc_bullet()` The obvious estimate is simply to take the ratio $k/n=19/57$.
`r insert_inc_bullet()` How would the classical statistician justify this estimate?
`r insert_slide_break()`
* Our model is that we have a Binomial experiment (assuming independent and identically distributed draws from the population).
`r insert_pause()`
* $K$ the number of alive individuals at the end of the winter, so that $P(K=k) = \binom{n}{k}\theta^k(1-\theta)^{n-k}$.
`r insert_pause()`
* The classical approach is to maximise the corresponding likelihood with respect to $\theta$ to obtain the entirely plausible MLE:
$$ \hat{\theta} = k/n = 19/57$$.
## The Bayesian approach
`r insert_inc_bullet()` The Bayesian starts off with a prior.
`r insert_inc_bullet()` Now, the one thing we know about $\theta$ is that is a continuous random variable and that it lies between zero and one.
`r insert_inc_bullet()` Thus, a suitable prior distribution might be the Beta defined on $[0,1]$.
`r insert_inc_bullet()` What is the Beta distribution?
## What is the Beta distribution?
$$
q(\theta \mid \alpha, \beta) = \frac{1}{\text{Beta}(\alpha, \beta)}{\theta^{\alpha-1}} {(1-\theta)^{\theta-1}}
$$
with $\text{Beta}(\alpha, \beta) = \displaystyle{\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}}$ and $\Gamma(n) = (n-1)!$
`r insert_slide_break()`
```{r, echo=FALSE}
x <- seq(0, 1, length=200)
par(mfrow = c(2,3))
# distribution a posteriori beta
plot(x,dbeta(x, 1, 1),type='l',xlab='q',ylab='Density',main='beta(1,1)',lwd=3,col='red',ylim=c(0,1.5))
plot(x,dbeta(x, 2, 1),type='l',xlab='q',ylab='',main='beta(2,1)',lwd=3,col='red',ylim=c(0,2))
plot(x,dbeta(x, 1, 2),type='l',xlab='q',ylab='',main='beta(1,2)',lwd=3,col='red',ylim=c(0,2))
plot(x,dbeta(x, 2, 2),type='l',xlab='q',ylab='Density',main='beta(2,2)',lwd=3,col='red',ylim=c(0,1.5))
plot(x,dbeta(x, 10, 10),type='l',xlab='q',ylab='',main='beta(10,10)',lwd=3,col='red',ylim=c(0,3.5))
plot(x,dbeta(x, 0.8, 0.8),type='l',xlab='q',ylab='',main='beta(0.8,0.8)',lwd=3,col='red',ylim=c(0.5,2.5))
```
## The Bayesian approach
* We assume a priori that $\theta \sim Beta(a,b)$ so that $\Pr(\theta) = \theta^{a-1} (1 - \theta)^{b-1}$
`r insert_pause()`
* Then we have:
$$
\begin{aligned}
{\color{red}{Pr(\theta \mid k)}} & \propto {\color{blue}{\binom{n}{k}\theta^k(1-\theta)^{n-k}}} \; {\color{green}{\theta^{a-1} (1 - \theta)^{b-1}}}\\
& \propto {\theta^{(a+k)-1}} {(1-\theta)^{(b+n-k)-1}}
\end{aligned}
$$
`r insert_pause()`
* That is:
$$ \theta \mid k \sim Beta(a+k,b+n-k)$$
`r insert_pause()`
* Take a Beta prior with a Binomial likelihood, you get a Beta posterior (conjugacy)
## Application to the deer example
`r insert_inc_bullet()` Posterior distribution of survival is $\theta \sim Beta(a+k,b+n-k)$.
`r insert_inc_bullet()` If we take a Uniform prior, i.e. $Beta(1,1)$, then we have:
`r insert_inc_bullet()` $\theta_{treatment} \sim Beta(1+19,1+57-19)=Beta(20,39)$
`r insert_inc_bullet()` Note that in this specific situation, the posterior has an explicit expression, easy to manipulate.
`r insert_inc_bullet()` In particular, $E(Beta(a,b)) = \displaystyle{\frac{a}{a+b}} = 20/59$ to be compared with the MLE $19/57$.
## A general result
**This is a general result, the Bayesian and frequentist estimates will always agree if there is sufficient data, so long as the likelihood is not explicitly ruled out by the prior.**
## Prior $Beta(1,1)$ and posterior survival $Beta(20,39)$
```{r echo=FALSE}
x <- seq(0, 1, length=200)
# distribution a posteriori beta
plot(x,dbeta(x, 20,39),type='l',xlab='',ylab='',main='',lwd=3,col='red')
# distribution a priori uniforme
points(x,dbeta(x, 1, 1),type='l',lwd=3)
```
## Prior $Beta(1,1)$ and posterior survival $Beta(20,39)$
```{r echo=FALSE}
x <- seq(0, 1, length=200)
# distribution a posteriori beta
plot(x,dbeta(x, 20,39),type='l',xlab='',ylab='',main='',lwd=3,col='red')
# distribution a priori uniforme
points(x,dbeta(x, 1, 1),type='l',lwd=3)
abline(v = 19/57, lwd = 3, lty = 2, col = 'blue')
text(x = 0.28, y = 0, 'MLE', col = 'blue')
```
## Notation
Our model so far
`r insert_html_math()`
\begin{align*}
y &\sim \text{Binomial}(N, \theta) &\text{[likelihood]}
\\
\theta &\sim \text{Beta}(1, 1) &\text{[prior for }\theta \text{]} \\
\end{align*}
`r insert_html_math()`
`r insert_slide_break()`

# A detour to explore priors
# Influence of the prior
## Prior $Beta(0.5,0.5)$ and posterior survival $Beta(19.5,38.5)$
```{r echo=FALSE}
x <- seq(0, 1, length=200)
# distribution a posteriori beta
plot(x,dbeta(x, .5+19,.5+57-19),type='l',xlab='',ylab='',main='',lwd=3,col='red')
# distribution a priori uniforme
points(x,dbeta(x, .5, .5),type='l',lwd=3)
```
## Prior $Beta(2,2)$ and posterior survival $Beta(21,40)$
```{r echo=FALSE}
x <- seq(0, 1, length=200)
# distribution a posteriori beta
plot(x,dbeta(x, 2+19,2+57-19),type='l',xlab='',ylab='',main='',lwd=3,col='red')
# distribution a priori uniforme
points(x,dbeta(x, 2, 2),type='l',lwd=3)
```
## Prior $Beta(20,1)$ and posterior survival $Beta(39,49)$
```{r echo=FALSE}
x <- seq(0, 1, length=200)
# distribution a posteriori beta
plot(x,dbeta(x, 20+19,1+57-19),type='l',xlab='',ylab='',main='',lwd=3,col='red')
# distribution a priori uniforme
points(x,dbeta(x, 20, 1),type='l',lwd=3)
```
## The role of the prior
`r insert_inc_bullet()` In biological applications, the prior is a convenient means of incorporating expert opinion or information from previous or related studies that would otherwise need to be ignored. We'll get back to that.
`r insert_inc_bullet()` With sparse data, the role of the prior can be to enable inference on key parameters that would otherwise be impossible.
`r insert_inc_bullet()` With sufficiently large and informative datasets the prior typically has little effect on the results.
`r insert_inc_bullet()` Always perform a sensitivity analysis.
## Informative priors vs. no information
`r insert_inc_bullet()` Informative priors aim to reflect information available to the analyst that is gained independently of the data being studied.
`r insert_inc_bullet()` In the absence of any prior information on one or more model parameters we wish to ensure that this lack of knowledge is properly reflected in the prior.
`r insert_inc_bullet()` Always perform a sensitivity analysis.
`r insert_slide_break()`
```{r, out.width = '11cm',out.height='7cm',fig.align='center',echo=FALSE}
knitr::include_graphics('img/falling_man.jpg')
```
# How to incorporate prior information?
## Estimating survival using capture-recapture data
* A bird might captured, missed and recaptured; this is coded $101$.
`r insert_pause()`
* Simplest model relies on constant survival $\phi$ and detection $p$ probabilities.
`r insert_pause()`
* Likelihood for that particular bird:
$$\Pr(101) = \phi (1-p) \phi p $$
`r insert_pause()`
* We assume a vague prior:
$$\phi_{prior} \sim \text{Beta}(1,1) = \text{Uniform}(0,1)$$
## Notation
* $y_{i,t} = 1$ if individual $i$ detected at occasion $t$ and $0$ otherwise
* $z_{i,t} = 1$ if individual $i$ alive between occasions $t$ and $t+1$ and $0$ otherwise
`r insert_html_math()`
\begin{align*}
y_{i,t} \mid z_{i,t} &\sim \text{Bernoulli}(p \; z_{i,t}) &\text{[likelihood (observation eq.)]} \\
z_{i,t+1} \mid z_{i,t}&\sim \text{Bernoulli}(\phi \; z_{i,t}) &\text{[likelihood (state eq.)]} \\
\phi &\sim \text{Beta}(1, 1) &\text{[prior for }\phi \text{]} \\
p &\sim \text{Beta}(1, 1) &\text{[prior for p]} \\
\end{align*}
`r insert_html_math()`
## European dippers in Eastern France (1981-1987)
```{r, out.width = '10cm',out.height='6cm',fig.align='center',echo=FALSE}
knitr::include_graphics('img/dipper.png')
```
## How to incorporate prior information?
`r insert_inc_bullet()` If no information, mean posterior survival is $\phi_{posterior} = 0.56$ with credible interval $[0.51,0.61]$.
`r insert_inc_bullet()` Using information on body mass and annual survival of 27 European passerines, we can predict survival of European dippers using only body mass.
`r insert_inc_bullet()` For dippers, body mass is 59.8g, therefore $\phi = 0.57$ with $\text{sd} = 0.073$.
`r insert_inc_bullet()` Assuming an informative prior $\phi_{prior} \sim \text{Normal}(0.57,0.073^2)$.
`r insert_inc_bullet()` Mean posterior $\phi_{posterior} = 0.56$ with credible interval $[0.52, 0.60]$.
`r insert_inc_bullet()` No increase of precision in posterior inference.
## How to incorporate prior information?
`r insert_inc_bullet()` Now if you had only the three first years of data, what would have happened?
`r insert_inc_bullet()` Width of credible interval is 0.47 (vague prior) vs. 0.30 (informative prior).
`r insert_inc_bullet()` Huge increase of precision in posterior inference ($40\%$ gain)!
## Compare \textcolor{blue}{vague} vs. \textcolor{red}{informative} prior
```{r include=FALSE}
# read in data
data <- as.matrix(read.table("dat/dipper.dat"))
# number of individuals
n <- dim(data)[[1]]
# number of capture occasions
K <- dim(data)[[2]]
# compute the date of first capture
e <- NULL
for (i in 1:n){
temp <- 1:K
e <- c(e,min(temp[data[i,]==1]))
}
# data
datax <- list(N=n,Years=K,obs=data,First=e)
# mark-recapture analysis for European Dippers
model <-
paste("
model
{
for (i in 1:N){
alive[i,First[i]] <- 1
for (j in (First[i]+1):Years){
alive[i,j] ~ dbern(alivep[i,j])
alivep[i,j] <- surv * alive[i,j-1]
obs[i,j] ~ dbern(sightp[i,j])
sightp[i,j] <- resight * alive[i,j]
}
}
surv~dunif(0,1)
resight~dunif(0,1)
}
")
writeLines(model,"code/CJS.txt")
# In JAGS we have to give good initial values for the latent state alive. At all occasions when an individual was observed, its state is alive = 1 for sure. In addition, if an individual was not observed at an occasion, but was alive for sure, because it was observed before and thereafter (i.e. has a capture history of e.g. {101} or {10001}), then we know that the individual was alive at all of these occasions, and thus alive = 1. Therefore, we should provide initial values of alive = 1 at these positions as well. The following function provides such initial values from the observed capture histories (from Kery and Schaub book)
known.state.cjs <- function(ch){
state <- ch
for (i in 1:dim(ch)[1]){
n1 <- min(which(ch[i,]==1))
n2 <- max(which(ch[i,]==1))
state[i,n1:n2] <- 1
state[i,n1] <- NA
}
state[state==0] <- NA
return(state)
}
Xinit <- known.state.cjs(data)
# first list of inits
init1 <- list(surv=.1,resight=.1,alive=Xinit)
# second list of inits
init2 <- list(surv=.9,resight=.9,alive=Xinit)
# specify the parameters to be monitored
parameters <- c("resight","surv")
# load R2jags
library(R2jags)
# run the MCMC analysis WITHOUT PRIOR INFORMATION
CJS.sim <-jags(data=datax, inits=list(init1,init2), parameters,n.iter=1000,model.file="code/CJS.txt",n.chains=2,n.burnin=500)
# to see the numerical results
# CJS.sim
# traceplot(CJS.sim) # diagnostic de convergence
# keep 3 first years only
data = data[,1:3]
databis = NULL
for (i in 1:nrow(data)){
# discard all non existing individuals i.e. those that were never captured
# test whether there was at least 1 detection and keep this individual if it was the case
if (sum(data[i,] == c(0,0,0))<3) databis = rbind(databis,data[i,])
}
data = databis
# number of individuals
n <- dim(data)[[1]]
# number of capture occasions
K <- dim(data)[[2]]
# compute the date of first capture
e <- NULL
for (i in 1:n){
temp <- 1:K
e <- c(e,min(temp[data[i,]==1]))
}
# data
datax <- list(N=n,Years=K,obs=data,First=e)
Xinit <- known.state.cjs(data)
# first list of inits
init1 <- list(surv=.1,resight=.1,alive=Xinit)
# second list of inits
init2 <- list(surv=.9,resight=.9,alive=Xinit)
# specify the parameters to be monitored
parameters <- c("resight","surv")
# run the MCMC analysis WITHOUT PRIOR INFORMATION
CJS.sim.wo.apriori <-jags(data=datax, inits=list(init1,init2), parameters,n.iter=1000,model.file="code/CJS.txt",n.chains=2,n.burnin=500)
# same model but with informative prior on survival
model <-
paste("
model
{
for (i in 1:N){
alive[i,First[i]] <- 1
for (j in (First[i]+1):Years){
alive[i,j] ~ dbern(alivep[i,j])
alivep[i,j] <- surv * alive[i,j-1]
obs[i,j] ~ dbern(sightp[i,j])
sightp[i,j] <- resight * alive[i,j]
}
}
surv~dnorm(0.57,187.6) # Norm(0.57,sd=0.073) ; precision = 1/var = 1/0.073^2
resight~dunif(0,1)
}
")
writeLines(model,"code/CJS2.txt")
CJS.sim.apriori <-jags(data=datax, inits=list(init1,init2), parameters,n.iter=1000,model.file="code/CJS2.txt",n.chains=2,n.burnin=500)
```
```{r echo=FALSE, message=FALSE, warning=FALSE}
res = as.mcmc(CJS.sim.wo.apriori)
res = rbind(res[[1]],res[[2]])
#head(res)
res2 = as.mcmc(CJS.sim.apriori)
res2 = rbind(res2[[1]],res2[[2]])
#head(res2)
plot(density(res2[,'surv']),xlab='survival',ylab='probability density',col='red',lwd=4,main='',xlim=c(0.2,1))
lines(density(res[,'surv']),xlab='survival',ylab='probability density',col='blue',lwd=4,main='')
legend('topleft',lwd=2,legend=c('with prior info','without prior info'),col=c('red','blue'))
```
# Prior elicitation via moment matching
## Remember the Beta distribution
* Recall that the Beta distribution is a continuous distribution with values between 0 and 1. Useful for modelling survival or detection probabilities.
`r insert_pause()`
* If $X \sim Beta(\alpha,\beta)$, then the first and second moments of $X$ are:
$$\mu = \text{E}(X) = \frac{\alpha}{\alpha + \beta}$$
$$\sigma^2 = \text{Var}(X) = \frac{\alpha\beta}{(\alpha + \beta)^2 (\alpha + \beta + 1)}$$
## Moment matching
* In the capture-recapture example, we know a priori that the mean of the probability we're interested in is $\mu = 0.57$ and its variance is $\sigma^2 = 0.073^2$?
`r insert_pause()`
* Parameters $\mu$ and $\sigma^2$ are seen as the moments of a $Beta(\alpha,\beta)$ distribution.
`r insert_pause()`
* Now we look for values of $\alpha$ and $\beta$ that match the observed moments of the Beta distribution ($\mu$ and $\sigma^2$).
`r insert_pause()`
* We need another set of equations:
$$\alpha = \bigg(\frac{1-\mu}{\sigma^2}- \frac{1}{\mu} \bigg)\mu^2$$
$$\beta = \alpha \bigg(\frac{1}{\mu}-1\bigg)$$
`r insert_slide_break()`