-
Notifications
You must be signed in to change notification settings - Fork 0
/
10.Rmd
1626 lines (1231 loc) · 71 KB
/
10.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
```{r, echo = F}
knitr::opts_chunk$set(fig.retina = 2.5)
knitr::opts_chunk$set(fig.align = "center")
```
# Model Comparison and Hierarchical Modeling
> There are situations in which different models compete to describe the same set of data...
>
> ...Bayesian inference is reallocation of credibility over possibilities. In model comparison, the focal possibilities are the models, and Bayesian model comparison reallocates credibility across the models, given the data. In this chapter, we explore examples and methods of Bayesian inference about the relative credibilities of models. [@kruschkeDoingBayesianData2015, pp. 265--266]
In the text, the emphasis is on the Bayes Factor paradigm. While we will discuss that, we will also present the alternatives available with information criteria, model averaging, and model stacking.
## General formula and the Bayes factor
So far we have spoken of
* the data, denoted by $D$ or $y$;
* the model parameters, generically denoted by $\theta$;
* the likelihood function, denoted by $p(D | \theta)$; and
* the prior distribution, denoted by $p(\theta)$.
Now we add to that $m$, which is a model index with $m = 1$ standing for the first model, $m = 2$ standing for the second model, and so on. So when we have more than one model in play, we might refer to the likelihood as $p_m(y | \theta_m, m)$ and the prior as $p_m(\theta_m | m)$. It's also the case, then, that each model can be given a prior probability $p(m)$.
"The Bayes factor (BF) is the ratio of the probabilities of the data in models 1 and 2" (p. 268).
This can be expressed simply as
$$\text{BF} = \frac{p(D | m = 1)}{p(D | m = 2)}.$$
Kruschke further explained that
> one convention for converting the magnitude of the BF to a discrete decision about the models is that there is "substantial" evidence for model $m = 1$ when the BF exceeds 3.0 and, equivalently, "substantial" evidence for model $m = 2$ when the BF is less than 1/3 [@jeffreysTheoryProbability1961; @kassBayesFactors1995; @wetzelsStatisticalEvidenceExperimental2011]. (p. 268)
However, as with $p$-values, effect sizes, and so on, BF values exist within continua and might should be evaluated in terms of degree more so than as ordered kinds.
## Example: Two factories of coins
Kruschke considered the coin bias of two factories, each described by the beta distribution. We can organize how to derive the $\alpha$ and $\beta$ parameters from $\omega$ and $\kappa$ with a tibble.
```{r, warning = F, message = F}
library(tidyverse)
d <-
tibble(factory = 1:2,
omega = c(.25, .75),
kappa = 12) %>%
mutate(alpha = omega * (kappa - 2) + 1,
beta = (1 - omega) * (kappa - 2) + 1)
d %>%
knitr::kable()
```
Thus given $\omega_1 = .25$, $\omega_2 = .75$ and $\kappa = 12$, we can describe the bias of the two coin factories as $\operatorname{beta}(\theta_{[m = 1]} | 3.5, 8.5)$ and $\operatorname{beta}(\theta_{[m = 2]} | 8.5, 3.5)$. With a little wrangling, we can use our `d` tibble to make the densities of Figure 10.2. But before we do, we should discuss plotting.
In the past few chapters, we have explored different plotting conventions using themes from Wilke's [**cowplot** package](https://wilkelab.org/cowplot), such as `theme_cowplot()` and `theme_minimal_grid()`. We also modified some of our plots using principles from Wilke's [-@wilkeFundamentalsDataVisualization2019] text, [*Fundamentals of data visualization*](https://clauswilke.com/dataviz/), and his [-@Wilke2019Themes] [*Themes*](https://wilkelab.org/cowplot/articles/themes.html) vignette. To further build on those principles, each chapter from here onward will have its own color scheme. The scheme in this chapter is based on [Katsushika Hokusai](https://www.katsushikahokusai.org/)'s [-@HokusaiGreatWaveOffKanagawa1820] woodblock print, [*The great wave off Kanagawa*](https://artsandculture.google.com/asset/the-great-wave-off-kanagawa/MgHm0BHMRIT73g). We can get a prearranged color palette based on *The great wave off Kanagawa* from [Tyler Littlefield](https://twitter.com/tyluRp)'s [**lisa** package](https://github.com/tyluRp/lisa) [@R-lisa].
```{r, warning = F, message = F, fig.width = 3, fig.height = 1}
library(lisa)
lisa_palette("KatsushikaHokusai")
plot(lisa_palette("KatsushikaHokusai"))
```
The `"KatsushikaHokusai"` palette comes out of the box with five colors. However, we can use the `lisa_palette()` function to expand the palette by setting `type = "continuous"` and then increasing the `n` argument to a value larger than five. Here's what happens when you set `n = 9` and `n = 1000`.
```{r, fig.width = 3, fig.height = 1}
plot(lisa_palette("KatsushikaHokusai", n = 9, type = "continuous"))
plot(lisa_palette("KatsushikaHokusai", n = 1000, type = "continuous"))
```
Next, we will use the five base colors from `"KatsushikaHokusai"` to adjust the global theme default for all ggplots in this chapter. We can accomplish this with the `ggplot2::theme_set()` function. First, we start with the default `theme_grey()` as our base and then modify several of the settings with arguments within the `theme()` function.
```{r}
theme_set(
theme_grey() +
theme(text = element_text(color = lisa_palette("KatsushikaHokusai")[1]),
axis.text = element_text(color = lisa_palette("KatsushikaHokusai")[1]),
axis.ticks = element_line(color = lisa_palette("KatsushikaHokusai")[1]),
legend.background = element_blank(),
legend.box.background = element_blank(),
legend.key = element_rect(fill = lisa_palette("KatsushikaHokusai")[5]),
panel.background = element_rect(fill = lisa_palette("KatsushikaHokusai")[5],
color = lisa_palette("KatsushikaHokusai")[1]),
panel.grid = element_blank(),
plot.background = element_rect(fill = lisa_palette("KatsushikaHokusai")[5],
color = lisa_palette("KatsushikaHokusai")[5]),
strip.background = element_rect(fill = lisa_palette("KatsushikaHokusai")[4]),
strip.text = element_text(color = lisa_palette("KatsushikaHokusai")[1]))
)
```
You can undo this by executing `theme_set(theme_grey())`. Next we'll save the color names from a 9-color version of "KatsushikaHokusai" as a conveniently-named object, `kh`. We'll use `kh` to adjust the `fill` and `color` settings within our plots on the fly.
```{r}
kh <- lisa_palette("KatsushikaHokusai", 9, "continuous")
kh
```
Okay, it's time to get a sense of what we've done by making our version of Figure 10.2.
```{r, fig.width = 6, fig.height = 2}
length <- 101
d %>%
expand(nesting(factory, alpha, beta),
theta = seq(from = 0, to = 1, length.out = length)) %>%
mutate(label = str_c("factory ", factory)) %>%
ggplot(aes(x = theta, y = dbeta(x = theta, shape1 = alpha, shape2 = beta))) +
geom_area(fill = kh[6]) +
scale_y_continuous(NULL, breaks = NULL,
expand = expansion(mult = c(0, 0.05))) +
xlab(expression(theta)) +
facet_wrap(~ label)
```
We might recreate the top panel with `geom_col()`.
```{r, fig.width = 3, fig.height = 2}
tibble(Model = c("1", "2"), y = 1) %>%
ggplot(aes(x = Model, y = y)) +
geom_col(width = .75, fill = kh[5]) +
scale_y_continuous(expand = expansion(mult = c(0, 0.05)))
```
Consider the Bernoulli bar plots in the bottom panels of Figure 10.2. The heights of the bars are arbitrary and just intended to give a sense of the Bernoulli distribution. If we wanted the heights to correspond to the Beta distributions above them, we might do so like this.
```{r, fig.width = 5, fig.height = 2}
crossing(factory = str_c("factory ", 1:2),
flip = factor(c("tails", "heads"), levels = c("tails", "heads"))) %>%
mutate(prob = c(.75, .25, .25, .75)) %>%
ggplot(aes(x = flip, y = prob)) +
geom_col(width = .75, fill = kh[4]) +
scale_y_continuous(NULL, breaks = NULL,
expand = expansion(mult = c(0, 0.05))) +
xlab(NULL) +
theme(axis.ticks.x = element_blank(),
panel.grid = element_blank()) +
facet_wrap(~ factory)
```
But now
> suppose we flip the coin nine times and get six heads. Given those data, what are the posterior probabilities of the coin coming from the head-biased or tail-biased factories? We will pursue the answer three ways: via formal analysis, grid approximation, and MCMC. (p. 270)
Before we move on to a formal analysis, here's a more faithful version of Kruschke's Figure 10.2 based on the method from my blog post, [*Make model diagrams, Kruschke style*](https://solomonkurz.netlify.app/post/make-model-diagrams-kruschke-style/).
```{r, fig.width = 3.9, fig.height = 5, message = F}
library(patchwork)
library(ggforce)
p1 <-
tibble(x = 1:2,
d = c(.75, .75)) %>%
ggplot(aes(x = x, y = d)) +
geom_col(fill = alpha(kh[5], .9), width = .45) +
annotate(geom = "text",
x = 1.5, y = .2,
label = "categorical",
size = 5, color = kh[1]) +
annotate(geom = "text",
x = 1.5, y = .85,
label = "italic(P[m])",
size = 5, color = kh[1], family = "Times", parse = TRUE) +
coord_cartesian(xlim = c(-.5, 3.5),
ylim = 0:1) +
theme_void() +
theme(axis.line.x = element_line(size = 0.5, color = kh[1]))
## an annotated arrow
# save our custom arrow settings
my_arrow <- arrow(angle = 20, length = unit(0.35, "cm"), type = "closed")
p2 <-
tibble(x = .5,
y = 1,
xend = .5,
yend = 0) %>%
ggplot(aes(x = x, xend = xend,
y = y, yend = yend)) +
geom_segment(arrow = my_arrow, color = kh[1]) +
annotate(geom = "text",
x = .375, y = 1/3,
label = "'~'",
size = 10, color = kh[1], family = "Times", parse = T) +
xlim(0, 1) +
theme_void()
p3 <-
tibble(x = seq(from = .01, to = .99, by = .01),
d = (dbeta(x, 5, 10) / max(dbeta(x, 5, 10)))) %>%
ggplot(aes(x = x, y = d)) +
geom_area(fill = alpha(kh[4], .85)) +
annotate(geom = "text",
x = .5, y = .2,
label = "beta",
size = 5, color = kh[1]) +
annotate(geom = "text",
x = .5, y = .6,
label = "list(italic(A)[1], italic(B)[1])",
size = 5, color = kh[1], family = "Times", parse = TRUE) +
scale_x_continuous(expand = c(0, 0)) +
theme_void() +
theme(axis.line.x = element_line(size = 0.5, color = kh[1]))
p4 <-
tibble(x = seq(from = .01, to = .99, by = .01),
d = (dbeta(x, 10, 5) / max(dbeta(x, 10, 5)))) %>%
ggplot(aes(x = x, y = d)) +
geom_area(fill = kh[6]) +
annotate(geom = "text",
x = .5, y = .2,
label = "beta",
size = 5, color = kh[1]) +
annotate(geom = "text",
x = .5, y = .6,
label = "list(italic(A)[2], italic(B)[2])",
size = 5, color = kh[1], family = "Times", parse = TRUE) +
scale_x_continuous(expand = c(0, 0)) +
theme_void() +
theme(axis.line.x = element_line(size = 0.5, color = kh[1]))
# bar plot of Bernoulli data
p5 <-
tibble(x = 0:1,
d = (dbinom(x, size = 1, prob = 1/3)) / max(dbinom(x, size = 1, prob = 1/3))) %>%
ggplot(aes(x = x, y = d)) +
geom_col(fill = alpha(kh[4], .85), width = .4) +
annotate(geom = "text",
x = .5, y = .2,
label = "Bernoulli",
size = 7, color = kh[1]) +
annotate(geom = "text",
x = .5, y = .94,
label = "theta",
size = 7, color = kh[1], family = "Times", parse = T) +
xlim(-.75, 1.75) +
theme_void() +
theme(axis.line.x = element_line(size = 0.5, color = kh[1]))
# another bar plot of Bernoulli data
p6 <-
tibble(x = 0:1,
d = (dbinom(x, size = 1, prob = 2/3)) / max(dbinom(x, size = 1, prob = 2/3))) %>%
ggplot(aes(x = x, y = d)) +
geom_col(fill = kh[6], width = .4) +
annotate(geom = "text",
x = .5, y = .2,
label = "Bernoulli",
size = 7, color = kh[1]) +
annotate(geom = "text",
x = .5, y = .94,
label = "theta",
size = 7, color = kh[1], family = "Times", parse = T) +
xlim(-.75, 1.75) +
theme_void() +
theme(axis.line.x = element_line(size = 0.5, color = kh[1]))
# another annotated arrow
p7 <-
tibble(x = c(.375, .625),
y = c(1/3, 1/3),
label = c("'~'", "italic(i)")) %>%
ggplot(aes(x = x, y = y, label = label)) +
geom_text(size = c(10, 7), parse = T, family = "Times") +
geom_segment(x = .5, xend = .5,
y = 1, yend = 0,
arrow = my_arrow, color = kh[1]) +
xlim(0, 1) +
theme_void()
# some text
p8 <-
tibble(x = 1,
y = .5,
label = "italic(y[i])") %>%
ggplot(aes(x = x, y = y, label = label)) +
geom_text(size = 7, color = kh[1], parse = T, family = "Times") +
xlim(0, 2) +
theme_void()
# dashed borders
p9 <-
tibble(x = c(0, 0.999, 0.999, 0, 1.001, 2, 2, 1.001),
y = c(0, 0, 1, 1, 0, 0, 1, 1),
z = rep(letters[1:2], each = 4)) %>%
ggplot(aes(x = x, y = y, group = z)) +
geom_shape(fill = "transparent", color = kh[1], linetype = 2,
radius = unit(1, 'cm')) +
scale_x_continuous(NULL, breaks = NULL, expand=c(0,0)) +
scale_y_continuous(NULL, breaks = NULL, expand=c(0,0)) +
theme_void()
# define the layout
layout <- c(
# cat
area(t = 1, b = 5, l = 5, r = 9),
area(t = 6, b = 8, l = 5, r = 9),
# beta
area(t = 9, b = 13, l = 2, r = 6),
area(t = 9, b = 13, l = 8, r = 12),
# arrow
area(t = 14, b = 16, l = 2, r = 6),
area(t = 14, b = 16, l = 8, r = 12),
# bern
area(t = 17, b = 21, l = 2, r = 6),
area(t = 17, b = 21, l = 8, r = 12),
area(t = 23, b = 25, l = 5, r = 9),
area(t = 26, b = 27, l = 5, r = 9),
area(t = 8, b = 23, l = 1, r = 13)
)
# combine and plot!
(p1 + p2 + p3 + p4 + p2 + p2 + p5 + p6 + p7 + p8 + p9) +
plot_layout(design = layout) &
ylim(0, 1) &
theme(plot.margin = margin(0, 5.5, 0, 5.5))
```
Note how we used the `geom_shape()` function from the [**ggforce** package](https://CRAN.R-project.org/package=ggforce) [@R-ggforce] to make the two dashed borders with the rounded edges. You can learn more from Pedersen's [-@pedersenDrawPolygonsExpansion] vignette, [*Draw polygons with expansion/contraction and/or rounded corners — geom_shape*](https://ggforce.data-imaginist.com/reference/geom_shape.html).
### Solution by formal analysis.
Here we rehearse if we have $\operatorname{beta}(\theta, a, b)$ prior for $\theta$ of the Bernoulli likelihood function, then the analytic solution for the posterior is $\operatorname{beta}(\theta | z + a, N – z + b)$. Within this paradigm, if you would like to compute $p(D | m)$, don't use the following function. If suffers from [underflow](https://en.wikipedia.org/wiki/Arithmetic_underflow) with large values.
```{r, eval = F}
p_d <- function(z, n, a, b) {
beta(z + a, n - z + b) / beta(a, b)
}
```
This version is more robust.
```{r p_d}
p_d <- function(z, n, a, b) {
exp(lbeta(z + a, n - z + b) - lbeta(a, b))
}
```
You'd use it like this to compute $p(D|m_1)$.
```{r}
p_d(z = 6, n = 9, a = 3.5, b = 8.5)
```
So to compute our BF, $\frac{p(D|m_1)}{p(D|m_2)}$, you might use the `p_d()` function like this.
```{r}
p_d_1 <- p_d(z = 6, n = 9, a = 3.5, b = 8.5)
p_d_2 <- p_d(z = 6, n = 9, a = 8.5, b = 3.5)
p_d_1 / p_d_2
```
And if we computed the BF the other way, it'd look like this.
```{r}
p_d_2 / p_d_1
```
Since the BF itself is only $\text{BF} = \frac{p(D | m = 1)}{p(D | m = 2)}$, we'd need to bring in the priors for the models themselves to get the posterior probabilities, which follows the form
$$\frac{p(m = 1 | D)}{p(m = 2 | D)} = \left (\frac{p(D | m = 1)}{p(D | m = 2)} \right ) \left ( \frac{p(m = 1)}{p(m = 2)} \right).$$
If for both our models $p(m) = .5$, then the BF is the same it was, before.
```{r}
(p_d_1 * .5) / (p_d_2 * .5)
```
As Kruschke pointed out, because we're working in the probability metric, the sum of $p(m = 1 | D )$ and $p(m = 2 | D )$ must be 1. By simple algebra then,
$$p(m = 2 | D ) = 1 - p(m = 1 | D ).$$
Therefore, it's also the case that
$$\frac{p(m = 1 | D)}{1 - p(m = 1 | D)} = 0.2135266.$$
Thus, 0.2135266 is in an odds metric. If you want to convert odds to a probability, you follow the formula
$$\text{odds} = \frac{\text{probability}}{1 - \text{probability}}.$$
And with more algebraic manipulation, you can solve for the probability.
\begin{align*}
\text{odds} & = \frac{\text{probability}}{1 - \text{probability}} \\
\text{odds} - \text{odds} \cdot \text{probability} & = \text{probability} \\
\text{odds} & = \text{probability} + \text{odds} \cdot \text{probability} \\
\text{odds} & = \text{probability} (1 + \text{odds}) \\
\frac{\text{odds}}{1 + \text{odds}} & = \text{probability}
\end{align*}
Thus, the posterior probability for $m = 1$ is
$$p(m = 1 | D) = \frac{0.2135266}{1 + 0.2135266}.$$
We can express that in code like so.
```{r}
odds <- (p_d_1 * .5) / (p_d_2 * .5)
odds / (1 + odds)
```
Relative to $m = 2$, our posterior probability for $m = 1$ is about .18. Therefore the posterior probability of $m = 2$ is 1 minus that.
```{r}
1 - (odds / (1 + odds))
```
Given the data, the two models and the prior assumption they were equally credible, we conclude $m = 2$ is .82 probable.
### Solution by grid approximation.
As in earlier chapters, we won't be able to make the wireframe plots on the left of Figure 10.3. But we can do some of the others. Here's the upper right panel.
```{r, fig.width = 3.5, fig.height = 3, warning = F, message = F}
p13 <-
tibble(omega = seq(from = 0, to = 1, length.out = length)) %>%
mutate(m_p = ifelse(omega %in% c(.25, .75), 15, 0)) %>%
ggplot(aes(xmin = 0, xmax = m_p, y = omega)) +
geom_ribbon(fill = kh[4], color = kh[4]) +
scale_x_continuous(expand = expansion(mult = c(0.002, 0.05)), limits = c(0, 25)) +
scale_y_continuous(expand = expansion(mult = c(0, 0))) +
labs(x = expression(Marginal~p(omega)),
y = expression(omega))
p13 + labs(subtitle = "Remember, the scale on the x is arbitrary.")
```
Building on that, here's the upper middle panel of the "two [prior] dorsal fins" (p. 271).
```{r, fig.height = 3, fig.width = 3.25}
d <-
crossing(omega = seq(from = 0, to = 1, length.out = length),
theta = seq(from = 0, to = 1, length.out = length)) %>%
mutate(prior = ifelse(omega == .25, dbeta(theta, 3.5, 8.5),
ifelse(omega == .75, dbeta(theta, 8.5, 3.5),
0)))
p12 <-
d %>%
ggplot(aes(x = theta, y = omega, fill = prior)) +
geom_raster(interpolate = T) +
scale_fill_gradient(low = kh[1], high = kh[9], breaks = NULL) +
scale_x_continuous(expression(theta), breaks = 0:5 / 5, expand = c(0, 0)) +
scale_y_continuous(expression(omega), breaks = 0:5 / 5, expand = c(0, 0))
p12
```
This time we'll separate $p_{m = 1}(\theta)$ and $p_{m = 2}(\theta)$ into the two short plots on the right of the next row down.
```{r, fig.width = 3.5, fig.height = 3, warning = F, message = F}
p23 <-
d %>%
filter(omega %in% c(.25, .75)) %>%
mutate(omega = factor(str_c("omega == ", omega),
levels = str_c("omega == ", c(.75, .25)))) %>%
ggplot(aes(x = theta, y = prior)) +
geom_area(fill = kh[4]) +
scale_x_continuous(expression(theta), breaks = 0:5 / 5,
expand = expansion(mult = c(0, 0))) +
scale_y_continuous(expression(Marginal~p(theta*"|"*omega)),
expand = expansion(mult = c(0, 0.05)), limits = c(0, NA)) +
facet_wrap(~ omega, ncol = 1, scales = "free", labeller = label_parsed)
p23
```
We can continue to build on those sensibilities for the middle panel of the same row. Here we're literally adding $p_{m = 1}(\theta)$ to $p_{m = 2}(\theta)$ and taking their average.
```{r, fig.width = 3.5, fig.height = 3}
p22 <-
tibble(theta = seq(from = 0, to = 1, length.out = length)) %>%
mutate(d_75 = dbeta(x = theta, shape1 = 8.5, shape2 = 3.5),
d_25 = dbeta(x = theta, shape1 = 3.5, shape2 = 8.5)) %>%
mutate(mean_prior = (d_75 + d_25) / 2) %>%
ggplot(aes(x = theta, y = mean_prior)) +
geom_area(fill = kh[4]) +
scale_x_continuous(expression(theta), breaks = 0:5 / 5,
expand = expansion(mult = c(0, 0))) +
scale_y_continuous(expression(Marginal~p(theta)),
expand = expansion(mult = c(0, 0.05)), limits = c(0, 3))
p22
```
We need the Bernoulli likelihood function for the next step.
```{r}
bernoulli_likelihood <- function(theta, data) {
n <- length(data)
z <- sum(data)
return(theta^z * (1 - theta)^(n - sum(data)))
}
```
Time to feed our data and the parameter space into `bernoulli_likelihood()`, which will allow us to make the 2-dimensional density plot at the heart of Figure 10.3.
```{r, fig.height = 3, fig.width = 3.25}
n <- 9
z <- 6
trial_data <- rep(0:1, times = c(n - z, z))
d <-
d %>%
mutate(likelihood = bernoulli_likelihood(theta = theta,
data = trial_data))
p32 <-
d %>%
ggplot(aes(x = theta, y = omega, fill = likelihood)) +
geom_raster(interpolate = T) +
scale_fill_gradient(low = kh[1], high = kh[9], breaks = NULL) +
scale_x_continuous(expression(theta), breaks = 0:5 / 5, expand = c(0, 0)) +
scale_y_continuous(expression(omega), breaks = 0:5 / 5, expand = c(0, 0))
p32
```
Now we just need the marginal likelihood, $p(D)$, to compute the posterior. Our first depiction will be the middle panel of the second row from the bottom--the panel with the uneven dolphin fins.
```{r, fig.height = 3, fig.width = 3.25}
d <-
d %>%
mutate(marginal_likelihood = sum(prior * likelihood)) %>%
mutate(posterior = (prior * likelihood) / marginal_likelihood)
p42 <-
d %>%
ggplot(aes(x = theta, y = omega, fill = posterior)) +
geom_raster(interpolate = T) +
scale_fill_gradient(low = kh[1], high = kh[9], breaks = NULL) +
scale_x_continuous(expression(theta), breaks = 0:5 / 5, expand = c(0, 0)) +
scale_y_continuous(expression(omega), breaks = 0:5 / 5, expand = c(0, 0))
p42
```
Here, then, is a way to get the panel in on the right of the second row from the bottom.
```{r, fig.width = 3.5, fig.height = 3}
p43 <-
d %>%
mutate(marginal = (posterior / max(posterior)) * 25) %>%
ggplot(aes(xmin = 0, xmax = marginal, y = omega)) +
geom_ribbon(fill = kh[6], color = kh[6]) +
scale_x_continuous(expression(omega),
expand = expansion(mult = c(0.002, 0.05)), limits = c(0, 25)) +
scale_y_continuous(expression(Marginal~p(omega*"|"*D)),
expand = expansion(mult = c(0, 0)))
p43
```
To make the middle bottom panel of Figure 10.3, we have to average the posterior values of $\theta$ over the grid of $\omega$ values. That is, we have to marginalize.
```{r, fig.width = 3.5, fig.height = 3, message = F}
p52 <-
d %>%
group_by(theta) %>%
summarise(marginal_theta = mean(posterior)) %>%
ggplot(aes(x = theta, y = marginal_theta)) +
geom_area(fill = kh[6]) +
scale_x_continuous(expression(theta), breaks = 0:5 / 5,
expand = expansion(mult = c(0, 0))) +
scale_y_continuous(expression(Marginal~p(theta*"|"*D)),
expand = expansion(mult = c(0, 0.05)), limits = c(0, NA))
p52
```
For the lower right panel of Figure 10.3, we'll `filter()` to our two focal values of $\omega$ and then facet by them.
```{r, fig.width = 3.5, fig.height = 3}
p53 <-
d %>%
filter(omega %in% c(.25, .75)) %>%
mutate(omega = factor(str_c("omega == ", omega),
levels = str_c("omega == ", c(.75, .25)))) %>%
ggplot(aes(x = theta, y = posterior)) +
geom_area(fill = kh[6]) +
scale_x_continuous(expression(theta), breaks = 0:5 / 5,
expand = expansion(mult = c(0, 0))) +
scale_y_continuous(expression(Marginal~p(theta*"|"*omega*", "*D)),
expand = expansion(mult = c(0, 0.05)), limits = c(0, NA)) +
facet_wrap(~ omega, ncol = 1, scales = "free", labeller = label_parsed)
p53
```
Do note the different scales on the $y$. Here's what they'd look like on the same scale.
```{r, fig.width = 3.5, fig.height = 3}
d %>%
filter(omega %in% c(.25, .75)) %>%
mutate(omega = str_c("omega == ", omega)) %>%
ggplot(aes(x = theta, y = posterior)) +
geom_area(fill = kh[6]) +
scale_x_continuous(expression(theta), breaks = 0:5 / 5,
expand = expansion(mult = c(0, 0))) +
scale_y_continuous(expression(Marginal~p(theta*"|"*omega)),
expand = expansion(mult = c(0, 0.05)), limits = c(0, NA)) +
facet_wrap(~ omega, ncol = 1, labeller = label_parsed)
```
Hopefully that helps build the intuition of what Kruschke meant when he wrote "*visual inspection suggests that the ratio of the heights is about 5 to 1, which matches the Bayes factor of 4.68 that we computed exactly in the previous section*" (p. 273, *emphasis* in the original).
Before we move on to the BF, let's save a few more ggplots and combine them with the previous bunch to make the full version of Figure 10.3.
```{r, fig.width = 6.5, fig.height = 9, warning = F, message = F}
p21 <-
tibble(x = 1,
y = 8:7,
label = c("Prior", "K==12"),
size = c(2, 1)) %>%
ggplot(aes(x = x, y = y, label = label)) +
geom_text(aes(size = size),
color = kh[1], parse = T, hjust = 0, show.legend = F) +
scale_size_continuous(range = c(3.5, 5.5)) +
coord_cartesian(xlim = c(1, 2),
ylim = c(4, 11)) +
theme(axis.text = element_text(color = kh[9]),
axis.ticks = element_blank(),
panel.background = element_rect(color = kh[9]),
text = element_text(color = kh[9]))
p33 <-
tibble(x = 1,
y = 8:7,
label = c("Likelihood", "D = 6 heads, 3 tails"),
size = c(2, 1)) %>%
ggplot(aes(x = x, y = y, label = label)) +
geom_text(aes(size = size),
hjust = 0, show.legend = F, color = kh[1]) +
scale_size_continuous(range = c(3.5, 5.5)) +
coord_cartesian(xlim = c(1, 2),
ylim = c(4, 11)) +
theme(axis.text = element_text(color = kh[9]),
axis.ticks = element_blank(),
panel.background = element_rect(color = kh[9]),
text = element_text(color = kh[9]))
p51 <-
ggplot() +
annotate(geom = "text", x = 1, y = 8,
label = "Posterior", size = 6, hjust = 0, color = kh[1]) +
coord_cartesian(xlim = c(1, 2),
ylim = c(3, 11)) +
theme(axis.text = element_text(color = kh[9]),
axis.ticks = element_blank(),
panel.background = element_rect(color = kh[9]),
text = element_text(color = kh[9]))
p11 <- plot_spacer()
# combine and plot!
(p11 / p21 / p11 / p11 / p51) | (p12 / p22 / p32 / p42 / p52) | (p13 / p23 / p33 / p43 / p53)
```
Oh mamma! Using the grid, you might compute that BF like this.
```{r, message = F}
d %>%
filter(omega %in% c(.25, .75)) %>%
group_by(omega) %>%
summarise(sum_posterior = sum(posterior)) %>%
mutate(model = c("model_1", "model_2")) %>%
pivot_wider(-omega,
names_from = model,
values_from = sum_posterior) %>%
mutate(BF = model_2 / model_1)
```
Please note[^3] how, in the previous section, Kruschke computed the BF as
$$\frac{p(m = 1 | D)}{p(m = 2 | D)} = .213,$$
which we achieved with this code:
```{r}
p_d_1 / p_d_2
```
Here, we're flipping the ratio to
$$\frac{p(m = 2 | D)}{p(m = 1 | D)},$$
which is why we now have a BF near 5.
```{r}
p_d_2 / p_d_1
```
But anyway, both the posterior distributions in the figure and the BF indicate $\omega = .75$ is a better representation of the data than $\omega = .25$.
## Solution by MCMC
Kruschke started with: "For large, complex models, we cannot derive $p(D | m)$ analytically or with grid approximation, and therefore we will approximate the posterior probabilities using MCMC methods" (p. 274). He's not kidding. Welcome to modern Bayes.
### Nonhierarchical MCMC computation of each model's marginal likelihood.
Before you get excited, Kruschke warned: "For complex models, this method might not be tractable. [But] for the simple application here, however, the method works well, as demonstrated in the next section" (p. 277).
#### Implementation with ~~JAGS~~ brms.
Load **brms**.
```{r, warning = F, message = F}
library(brms)
```
Let's save the `trial_data` as a tibble.
```{r}
trial_data <-
tibble(y = trial_data)
```
Time to learn a new **brms** skill. When you want to enter variables into the parameters defining priors in `brms::brm()`, you need to specify them using the `stanvar()` function. Since we want to do this for two variables, we’ll use `stanvar()` twice and save the results as an object, conveniently named `stanvars`.
```{r}
omega <- .75
kappa <- 12
stanvars <-
stanvar( omega * (kappa - 2) + 1, name = "my_alpha") +
stanvar((1 - omega) * (kappa - 2) + 1, name = "my_beta")
```
Now we have our `stanvars` object, we are ready to fit the first model (i.e., the model for which $\omega = .75$).
```{r fit10.1}
fit10.1 <-
brm(data = trial_data,
family = bernoulli(link = identity),
y ~ 1,
# stanvars lets us do this
prior(beta(my_alpha, my_beta), class = Intercept),
iter = 11000, warmup = 1000, chains = 4, cores = 4,
seed = 10,
stanvars = stanvars,
control = list(adapt_delta = .999),
file = "fits/fit10.01")
```
Note how we fed our `stanvars` object into the `stanvars` function.
Anyway, let's inspect the chains.
```{r, fig.width = 8, fig.height = 1.4}
plot(fit10.1)
```
They look great. Now we glance at the model summary.
```{r}
print(fit10.1)
```
Next we'll follow Kruschke and extract the posterior samples, saving them as `theta`.
```{r}
theta <- posterior_samples(fit10.1)
head(theta)
```
The `fixef()` function will return the posterior summaries for the model intercept (i.e., $\theta$). We can then index and save the desired summaries.
```{r}
fixef(fit10.1)
(mean_theta <- fixef(fit10.1)[1])
(sd_theta <- fixef(fit10.1)[2])
```
Now we'll convert them to the $\alpha$ and $\beta$ parameters, `a_post` and `b_post`, respectively.
```{r}
a_post <- mean_theta * ( mean_theta * (1 - mean_theta) / sd_theta^2 - 1)
b_post <- (1 - mean_theta) * ( mean_theta * (1 - mean_theta) / sd_theta^2 - 1)
```
Recall we've already defined several values.
```{r}
n <- 9
z <- 6
omega <- .75
kappa <- 12
```
The reason we're saving all these values is we're aiming to compute $p(D)$, the probability of the data (i.e., the marginal likelihood), given the model. But our intermediary step will be computing its reciprocal, $\frac{1}{p(D)}$. Here we'll express Kruschke's `oneOverPD` as a function, `one_over_pd()`.
```{r}
one_over_pd <- function(theta) {
mean(dbeta(theta, a_post, b_post ) /
(theta^z * (1 - theta)^(n - z) *
dbeta(theta, omega * (kappa - 2) + 1, (1 - omega) * (kappa - 2) + 1 )))
}
```
We're ready to use `one_over_pd()` to help compute $p(D)$.
```{r}
theta %>%
summarise(pd = 1 / one_over_pd(theta = b_Intercept))
```
That matches up nicely with Kruschke's value at the top of page 278! Let's rinse, wash, and repeat for $\omega = .25$. First, we'll need to redefine `omega` and our `stanvars`.
```{r}
omega <- .25
stanvars <-
stanvar( omega * (kappa - 2) + 1, name = "my_alpha") +
stanvar((1 - omega) * (kappa - 2) + 1, name = "my_beta")
```
Fit the model.
```{r fit10.2}
fit10.2 <-
brm(data = trial_data,
family = bernoulli(link = identity),
y ~ 1,
prior(beta(my_alpha, my_beta), class = Intercept),
iter = 11000, warmup = 1000, chains = 4, cores = 4,
seed = 10,
stanvars = stanvars,
control = list(adapt_delta = .999),
file = "fits/fit10.02")
```
We'll do the rest in bulk.
```{r}
theta <- posterior_samples(fit10.2)
mean_theta <- fixef(fit10.2)[1]
sd_theta <- fixef(fit10.2)[2]
a_post <- mean_theta * ( mean_theta * (1 - mean_theta) / sd_theta^2 - 1)
b_post <- (1 - mean_theta) * ( mean_theta * (1 - mean_theta) / sd_theta^2 - 1)
theta %>%
summarise(pd = 1 / one_over_pd(theta = b_Intercept))
```
Boom!
### Hierarchical MCMC computation ~~of relative model probability~~ is not available in brms: We'll cover information criteria instead.
I'm not aware of a way to specify a model "in which the top-level parameter is the index across models" in **brms** (p. 278). If you know of a way, [share your code](https://github.com/ASKurz/Doing-Bayesian-Data-Analysis-in-brms-and-the-tidyverse/issues).
However, we do have options. We can compare and weight models using information criteria, about which you can learn more [here](https://youtu.be/t0pRuy1_190?t=978) or [here](https://www.youtube.com/watch?v=gjrsYDJbRh0&list=PLDcUM9US4XdNM4Edgs7weiyIguLSToZRI&index=8)
. In **brms**, the LOO and WAIC are two primary information criteria available. You can compute them for a given model with the `loo()` and `waic()` functions, respectively. Here's a quick example of how to use the `waic()` function.
```{r}
waic(fit10.1)
```
We'll explain that output in a bit. Before we do, you should know the current recommended workflow for information criteria with **brms** models is to use the `add_criterion()` function, which will allow us to compute information-criterion-related output and save it to our **brms** fit objects. Here's how to do that with both our fits.
```{r ic_fit10.1_fit10.2, message = F}
fit10.1 <- add_criterion(fit10.1, criterion = c("loo", "waic"))
fit10.2 <- add_criterion(fit10.2, criterion = c("loo", "waic"))
```
You can extract the same WAIC output for `fit10.1` we saw above by executing `fit10.1$criteria$waic`. Here we look at the LOO summary for `fit10.2`, instead.
```{r}
fit10.2$criteria$loo
```
You get a wealth of output, more of which can be seen by executing `str(fit10.1$criteria$loo)`. First, notice the message "All Pareto k estimates are good (k < 0.5)." Pareto $k$ values can be used for diagnostics [@vehtariUsingLooPackage2020, [*Plotting Pareto* $k$ *diagnostics*](https://cran.r-project.org/web/packages/loo/vignettes/loo2-example.html#plotting-pareto-k-diagnostics)]. Each case in the data gets its own $k$ value and we like it when those $k$s are low. The makers of the [**loo** package](https://github.com/stan-dev/loo) get worried when $k$ values exceed 0.7 and, as a result, we will get warning messages when they do. Happily, we have no such warning messages in this example.
In the main section, we get estimates for the expected log predictive density (`elpd_loo`), the estimated effective number of parameters (`p_loo`), and the Pareto smoothed importance-sampling leave-one-out cross-validation (PSIS-LOO; `looic`). Each estimate comes with a standard error (i.e., `SE`). Like other information criteria, the LOO values aren't of interest in and of themselves. However, the estimate of one model's LOO relative to that of another is of great interest. We generally prefer models with lower information criteria. With the `loo_compare()` function, we can compute a formal difference score between two models.
```{r}
loo_compare(fit10.1, fit10.2, criterion = "loo")
```
The `loo_compare()` output rank orders the models such that the best fitting model appears on top. All models receive a difference score relative to the best model. Here the best fitting model is `fit10.1` and since the LOO for `fit10.1` minus itself is zero, the values in the top row are all zero.
Each difference score also comes with a standard error. In this case, even though `fit10.1` has the lower estimates, the standard error is twice the magnitude of the difference score. So the LOO difference score puts the two models on similar footing. You can do a similar analysis with the WAIC estimates.
In addition to difference-score comparisons, you can also use the LOO or WAIC for AIC-type model weighting. In **brms**, you do this with the `model_weights()` function.
```{r mw_fit10.1_and_fit10.2}
(mw <- model_weights(fit10.1, fit10.2))
```
I don't know that I'd call these weights probabilities, but they do sum to one. In this case, the analysis suggests we put about five times more weight to `fit10.1` relative to `fit10.2`.
```{r}
mw[1] / mw[2]
```
With `brms::model_weights()`, we have a variety of weighting schemes available to us. Since we didn't specify any in the `weights` argument, we used the default `"stacking"`, which is--perhaps confusingly given the name--the stacking method according to the paper by @yaoUsingStackingAverage2018 Vehtari has [written about the paper](https://statmodeling.stat.columbia.edu/2017/04/11/stacking-pseudo-bma-and-aic-weights/) on Gelman's blog, too. But anyway, the point is that different weighting schemes might not produce the same results. For example, here's the result from weighting using the WAIC.
```{r}
model_weights(fit10.1, fit10.2, weights = "waic")
```
The results are similar, for sure. But they're not the same. The stacking method via the **brms** default `weights = "stacking"` is the current preferred method by the folks on the Stan team (e.g., the authors of the above linked paper).
For more on stacking and other weighting schemes, see Vehtari and Gabry's [-@vehtariBayesianStackingPseudoBMA] vignette, [*Bayesian Stacking and Pseudo-BMA weights using the loo package*](https://CRAN.R-project.org/package=loo/vignettes/loo2-weights.html), or Vehtari's [modelselection_tutorial GitHub repository](https://github.com/avehtari/modelselection_tutorial). But don't worry. We will have more opportunities to practice with information criteria, model weights, and such later in this project.
#### ~~Using~~ [No need to use] pseudo-priors to reduce autocorrelation.
Since we didn't use Kruschke's method from the last subsection, we don't have the same worry about autocorrelation. For example, here are the autocorrelation plots for `fit10.1`.
```{r, fig.width = 4, fig.height = 4, message = F, warning = F}
library(bayesplot)
color_scheme_set(scheme = c(lisa_palette("KatsushikaHokusai", n = 9, type = "continuous")[6:1]))
mcmc_acf(posterior_samples(fit10.1, add_chain = T),
pars = "b_Intercept",
lags = 35)
```
Our autocorrelations were a little high for HMC, but nowhere near pathological. The results for `fit10.2` were similar. Before we move on, note our use of `bayesplot::color_scheme_set()`, which allowed us to customize the color scheme **bayesplot** used within the plot. Based on that code, here is our new color scheme for all plots made by **bayesplot**.
```{r, fig.height = 2.75}
color_scheme_view()
color_scheme_get()
```
In case you were curious, here is the default.
```{r, fig.height = 2.75}
color_scheme_view(scheme = "blue")
```
Anyway, as you might imagine from the moderate autocorrelations, the $N_{eff}/N$ ratio for `b_Intercept` wasn't great.
```{r, fig.width = 6, fig.height = 1.25}
neff_ratio(fit10.1)[1] %>%
mcmc_neff() +
yaxis_text(hjust = 0)
```
But we specified a lot of post-warmup iterations, so we're still in good shape. Plus, the $\hat R$ was fine.
```{r}
rhat(fit10.1)[1]
```
### Models with different "noise" distributions in ~~JAGS~~ brms.
> Probability distribution[s are] sometimes [called "noise"] distribution[s] because [they describe] the random variability of the data values around the underlying trend. In more general applications, different models can have different noise distributions. For example, one model might describe the data as log-normal distributed, while another model might describe the data as gamma distributed. (p. 288)
If there are more than one plausible noise distributions for our data, we might want to compare the models. Kruschke then gave us a general trick in the form of this JAGS code:
```{r, eval = F}
data {
C <- 10000 # JAGS does not warn if too small!
for (i in 1:N) {
ones[i] <- 1 }
} model {
for (i in 1:N) {
spy1[i] <- pdf1(y[i], parameters1) / C # where pdf1 is a formula
spy2[i] <- pdf2(y[i], parameters2) / C # where pdf2 is a formula
spy[i] <- equals(m,1) * spy1[i] + equals(m, 2) * spy2[i]
ones[i] ~ dbern(spy[i])
}
parameters1 ~ dprior1...
parameters2 ~ dprior2...