-
Notifications
You must be signed in to change notification settings - Fork 0
/
12.Rmd
1215 lines (946 loc) · 50.2 KB
/
12.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: "Chapter 12. Bayesian Approaches to Testing a Point ('Null') Hypothesis"
author: "A Solomon Kurz"
date: "`r format(Sys.Date())`"
output:
github_document
---
```{r, echo = FALSE, cachse = FALSE}
knitr::opts_chunk$set(fig.retina = 2.5)
knitr::opts_chunk$set(fig.align = "center")
options(width = 100)
```
# Bayesian Approaches to Testing a Point ("Null") Hypothesis
> Suppose that you have collected some data, and now you want to answer the question, Is there a non-zero effect or not? Is the coin fair or not? Is there better-than-chance accuracy or not? Is there a difference between groups or not? In the previous chapter, [Kruschke] argued that answering this type of question via null hypothesis significance testing (NHST) has deep problems. This chapter describes Bayesian approaches to the question. [@kruschkeDoingBayesianData2015, p 335]
## The estimation approach
> Throughout this book, we have used Bayesian inference to derive a posterior distribution over a parameter of interest, such as the bias $\theta$ of a coin. We can then use the posterior distribution to discern the credible values of the parameter. If the null value is far from the credible values, then we reject the null value as not credible. But if all the credible values are virtually equivalent to the null value, then we can accept the null value. (p. 336)
### Region of practical equivalence.
Kruschke began: "A *region of practical equivalence* (ROPE) indicates a small range of parameter values that are considered to be practically equivalent to the null value for purposes of the particular application" (p. 336, *emphasis* in the original)
Here's a plot of Kruschke's initial coin flip ROPE.
```{r, fig.width = 6, fig.height = 1.125, warning = F, message = F}
library(tidyverse)
tibble(xmin = .45,
xmax = .55) %>%
ggplot() +
geom_rect(aes(xmin = xmin, xmax = xmax,
ymin = -Inf, ymax = Inf),
color = "transparent", fill = "white") +
annotate(geom = "text", x = .5, y = .5,
label = "ROPE", color = "grey67") +
scale_y_continuous(NULL, breaks = NULL) +
labs(title = "Kruschke's coin flip ROPE",
x = expression(theta)) +
coord_cartesian(0:1) +
theme(panel.grid.minor = element_blank())
```
In the first example (p. 336), we have $z = 325$ heads out of $N = 500$ coin flips. To visualize the analysis, we'll need the Bernoulli likelihood.
```{r}
bernoulli_likelihood <- function(theta, data) {
n <- length(data)
z <- sum(data)
return(theta^z * (1 - theta)^(n - sum(data)))
}
```
Now we'll follow the typical steps to combine the prior, which is flat in this case, and the likelihood to get the posterior.
```{r}
# the data summaries
n <- 500
z <- 325
trial_data <- c(rep(0, times = n - z), rep(1, times = z)) # (i.e., data)
d <-
tibble(theta = seq(from = 0, to = 1, length.out = 1e3)) %>% # (i.e., theta)
# recall Beta(1, 1) is flat
mutate(prior = dbeta(theta, shape1 = 1, shape2 = 1), # (i.e., p(theta))
likelihood = bernoulli_likelihood(theta = theta, # (i.e., p(D | theta))
data = trial_data)) %>%
mutate(posterior = likelihood * prior / sum(prior * likelihood)) # (i.e., p(theta | D))
glimpse(d)
```
Now we can plot the results.
```{r, fig.width = 6, fig.height = 2, warning = F, message = F}
ggplot(data = d) +
geom_rect(xmin = .45, xmax = .55,
ymin = -Inf, ymax = Inf,
color = "transparent", fill = "white") +
geom_ribbon(aes(x = theta, ymin = 0, ymax = posterior),
fill = "grey67") +
annotate(geom = "text", x = .5, y = .01,
label = "ROPE", color = "grey67") +
scale_y_continuous(NULL, breaks = NULL) +
labs(title = "Nope, that density ain't in that ROPE.",
x = expression(theta)) +
theme(panel.grid = element_blank())
```
With the formula by $\operatorname{beta} (\theta | z + \alpha, N - z + \beta)$, we can analytically compute the Beta parameters for the posterior.
```{r}
(alpha <- z + 1)
(beta <- n - z + 1)
```
With the `hdi_of_icdf()` function, we'll compute the HDIs.
```{r}
hdi_of_icdf <- function(name, width = .95, tol = 1e-8, ... ) {
incredible_mass <- 1.0 - width
interval_width <- function(low_tail_prob, name, width, ...) {
name(width + low_tail_prob, ...) - name(low_tail_prob, ...)
}
opt_info <- optimize(interval_width, c(0, incredible_mass),
name = name, width = width,
tol = tol, ...)
hdi_lower_tail_prob <- opt_info$minimum
return(c(name(hdi_lower_tail_prob, ...),
name(width + hdi_lower_tail_prob, ...)))
}
```
Compute those HDIs and save them as `h`.
```{r}
(
h <-
hdi_of_icdf(name = qbeta,
shape1 = alpha,
shape2 = beta)
)
```
Now let's remake the plot from above, this time with the analytically-derived HDI values.
```{r, fig.width = 6, fig.height = 2, warning = F, message = F}
tibble(theta = seq(from = 0, to = 1, length.out = 1e3)) %>%
ggplot() +
geom_rect(xmin = .45, xmax = .55,
ymin = -Inf, ymax = Inf,
color = "transparent", fill = "white") +
geom_ribbon(aes(x = theta,
ymin = 0, ymax = dbeta(theta, shape1 = alpha, shape2 = beta)),
fill = "grey67", size = 0) +
geom_segment(x = h[1], xend = h[2],
y = 0, yend = 0,
size = 3/4) +
annotate(geom = "text", x = .5, y = 17.5,
label = "ROPE", color = "grey67") +
annotate(geom = "text", x = .65, y = 4, label = "95%\nHDI") +
scale_y_continuous(NULL, breaks = NULL) +
labs(title = "That `hdi_of_icdf()` function really came through, for us.",
x = expression(theta)) +
theme(panel.grid = element_blank())
```
In his second example (p. 337), Kruschke considered $z = 490$ heads out of $N = 1000$ flips.
```{r, fig.width = 6, fig.height = 2, warning = F, message = F}
# we need these to compute the likelihood
n <- 1000
z <- 490
trial_data <- c(rep(0, times = n - z), rep(1, times = z))
tibble(theta = seq(from = 0, to = 1, length.out = 1e3)) %>% # (i.e., theta)
mutate(prior = dbeta(theta, shape1 = 1, shape2 = 1), # (i.e., p(theta))
likelihood = bernoulli_likelihood(theta = theta, # (i.e., p(D | theta))
data = trial_data)) %>%
mutate(posterior = (likelihood * prior) / sum(likelihood * prior)) %>% # (i.e., p(theta | D))
ggplot() +
geom_rect(xmin = .45, xmax = .55,
ymin = -Inf, ymax = Inf,
color = "transparent", fill = "white") +
geom_ribbon(aes(x = theta, ymin = 0, ymax = posterior),
fill = "grey67") +
scale_y_continuous(NULL, breaks = NULL) +
labs(title = "This posterior sits right within the ROPE.",
x = expression(theta)) +
theme(panel.grid = element_blank())
```
Here are the new HDIs.
```{r}
hdi_of_icdf(name = qbeta,
shape1 = z + 1,
shape2 = n - z + 1)
```
Further down the section, Kruschke offered some perspective on the ROPE approach.
> The ROPE limits, by definition, cannot be uniquely "correct," but instead are established by practical aims, bearing in mind that wider ROPEs yield more decisions to accept the ROPEd value and fewer decision to reject the ROPEd value. In many situations, the exact limit of the ROPE can be left indeterminate or tacit, so that the audience of the analysis can use whatever ROPE is appropriate at the time, as competing theories and measuring devices evolve. When the HDI is far from the ROPEd value, the exact ROPE is inconsequential because the ROPEd value would be rejected for any reasonable ROPE. When the HDI is very narrow and overlaps the target value, the HDI might again fall within any reasonable ROPE, again rendering the exact ROPE inconsequential. When, however, the HDI is only moderately narrow and near the target value, the analysis can report how much of the posterior falls within a ROPE as a function of different ROPE widths...
>
> It is important to be clear that any discrete decision about rejecting or accepting a null value does *not* exhaustively capture our knowledge about the parameter value. Our knowledge about the parameter value is described by the full posterior distribution. When making a binary decision, we have merely compressed all that rich detail into a single bit of information. The broader goal of Bayesian analysis is conveying an informative summary of the posterior, and where the value of interest falls within that posterior. Reporting the limits of an HDI region is more informative than reporting the declaration of a reject/accept decision. By reporting the HDI and other summary information about the posterior, different readers can apply different ROPEs to decide for themselves whether a parameter is practically equivalent to a null value. The decision procedure is separate from the Bayesian inference. The Bayesian part of the analysis is deriving the posterior distribution. The decision procedure uses the posterior distribution, but does not itself use Bayes’ rule. (pp. 338--339, *emphasis* in the original)
Full disclosure: I'm not a fan of the ROPE method. Though we're following along with the text and covering it, here, I will deemphasize it in later sections.
Kruschke then went on to compare the ROPE with frequentist equivalence tests. This is a part of the literature I have not waded into, yet. It appears psychologist Daniël Lakens and colleagues gave written a bit in the topic, recently. Interested readers might start with @lakensImprovingInferencesNull2020, @lakensEquivalenceTestingPsychological2018, or @lakensEquivalenceTestingSecond2018.
### Some examples.
Kruschke referenced an analysis from way back in Chapter 9. We'll need to re-fit the model. First we import data.
```{r, warning = F, message = F}
my_data <- read_csv("data.R/BattingAverage.csv")
glimpse(my_data)
```
Let's load **brms** and, while we're at it, **tidybayes**.
```{r, warning = F, message = F}
library(brms)
library(tidybayes)
```
Fit the model and retain its original name, `fit9.2`.
```{r fit9.2}
fit9.2 <-
brm(data = my_data,
family = binomial(link = logit),
Hits | trials(AtBats) ~ 1 + (1 | PriPos) + (1 | PriPos:Player),
prior = c(prior(normal(0, 1.5), class = Intercept),
prior(normal(0, 1), class = sd)),
iter = 3500, warmup = 500, chains = 3, cores = 3,
control = list(adapt_delta = .99),
seed = 9,
file = "fits/fit09.02")
```
Let's use `coef()` to pull the relevant posterior draws.
```{r, warning = F}
c <-
coef(fit9.2, summary = F)$PriPos %>%
as_tibble()
str(c)
```
As we pointed out in Chapter 9, keep in mind that `coef()` returns the values in the logit scale when used for logistic regression models. So we'll have to use `brms::inv_logit_scaled()` to convert the estimates to the probability metric. We can make the difference distributions after we've converted the estimates.
```{r}
c_small <-
c %>%
mutate_all(inv_logit_scaled) %>%
transmute(`Pitcher - Catcher` = Pitcher.Intercept - Catcher.Intercept,
`Catcher - 1st Base` = Catcher.Intercept - `1st Base.Intercept`)
head(c_small)
```
After a little wrangling, we'll be ready to re-plot the relevant parts of Figure 9.14.
```{r, fig.width = 8, fig.height = 2.5}
c_small %>%
pivot_longer(everything()) %>%
mutate(name = factor(name, levels = c("Pitcher - Catcher", "Catcher - 1st Base"))) %>%
ggplot(aes(x = value)) +
geom_rect(xmin = -0.05, xmax = 0.05,
ymin = -Inf, ymax = Inf,
color = "transparent", fill = "white") +
stat_histintervalh(aes(y = 0),
point_interval = mode_hdi, .width = .95,
fill = "grey67", slab_color = "grey92",
breaks = 20, slab_size = .25, outline_bars = T) +
scale_y_continuous(NULL, breaks = NULL) +
labs(title = "The ROPE ranges from −0.05 to +0.05",
x = expression(theta)) +
coord_cartesian(c(-.125, .125)) +
theme(panel.grid = element_blank(),
legend.position = "none") +
facet_wrap(~name, scales = "free")
```
In order to re-plot part of Figure 9.15, we'll need to employ `fitted()` to snatch the player-specific posteriors.
```{r, warning = F}
# this will make life easier. just go with it
name_list <- c("ShinSoo Choo", "Ichiro Suzuki")
# we'll define the data we'd like to feed into `fitted()`, here
nd <-
my_data %>%
filter(Player %in% c(name_list)) %>%
# these last two lines aren't typically necessary, but they allow us to
# arrange the rows in the same order we find the names in Figures 9.15 and 9/16
mutate(Player = factor(Player, levels = c(name_list))) %>%
arrange(Player)
f <-
fitted(fit9.2,
newdata = nd,
scale = "linear",
summary = F) %>%
as_tibble() %>%
mutate_all(inv_logit_scaled) %>%
set_names(name_list) %>%
# in this last section, we make our difference distributions
mutate(`ShinSoo Choo - Ichiro Suzuki` = `ShinSoo Choo` - `Ichiro Suzuki`)
glimpse(f)
```
Now we're ready to go.
```{r, fig.width = 4, fig.height = 2.5}
f %>%
ggplot() +
geom_rect(xmin = -0.05, xmax = 0.05,
ymin = -Inf, ymax = Inf,
color = "transparent", fill = "white") +
stat_histintervalh(aes(x = `ShinSoo Choo - Ichiro Suzuki`, y = 0),
point_interval = mode_hdi, .width = .95,
fill = "grey67", slab_color = "grey92",
breaks = 40, slab_size = .4, outline_bars = T) +
scale_y_continuous(NULL, breaks = NULL) +
labs(title = "ShinSoo Choo - Ichiro Suzuki",
x = expression(theta)) +
coord_cartesian(c(-.125, .125)) +
theme(panel.grid = element_blank())
```
### Differences of correlated parameters.
Kruschke didn't explicate where he got the data for Figure 12.1. If we're willing to presume a multivariate normal distribution, we can get close using the `MASS::mvrnorm()` function. You can get the basic steps from [Sven Hohenstein's answer to this stats.stacheschange question](https://stats.stackexchange.com/questions/164471/generating-a-simulated-dataset-from-a-correlation-matrix-with-means-and-standard).
```{r}
# first we'll make a correlation matrix
# a correlation of .9 seems about right
correlation_matrix <-
matrix(c(1, .9,
.9, 1),
nrow = 2, ncol = 2)
# next we'll specify the means and standard deviations
mu <- c(.58, .42)
sd <- c(.1, .1)
# now we'll use the correlation matrix and standard deviations to make a covariance matrix
covariance_matrix <-
sd %*% t(sd) * correlation_matrix
# after setting our seed, we're ready to simulate
set.seed(12)
d <-
MASS::mvrnorm(n = 1000,
mu = mu,
Sigma = covariance_matrix) %>%
as_tibble() %>%
set_names(str_c("theta[", 1:2, "]"))
```
Now it only takes some light wrangling to prepare the data to make the three histograms in the left panel of Figure 12.1.
```{r, fig.width = 8, fig.height = 2.75}
d %>%
mutate(`theta[1]-theta[2]` = `theta[1]` - `theta[2]`) %>%
gather() %>%
ggplot(aes(x = value, y = 0)) +
stat_histintervalh(point_interval = mode_hdi, .width = .95,
fill = "grey67", slab_color = "grey92",
breaks = 30, slab_size = .25, outline_bars = T,
normalize = "panels") +
scale_y_continuous(NULL, breaks = NULL) +
xlab(expression(theta)) +
theme(panel.grid = element_blank()) +
facet_wrap(~key, scales = "free_y", labeller = label_parsed)
```
Here's the scatter plot, showing the correlation. I think we got pretty close!
```{r, fig.height = 2.75}
d %>%
ggplot(aes(x = `theta[1]`, y = `theta[2]`)) +
geom_abline(color = "white") +
geom_point(size = 1/2, color = "grey50", alpha = 1/4) +
coord_equal(xlim = c(0, 1),
ylim = c(0, 1)) +
labs(x = expression(theta[1]),
y = expression(theta[2])) +
theme(panel.grid = element_blank())
```
To make the plots in the right panel of Figure 12.1, we just need to convert the correlation from .9 to -.9.
```{r}
# this time we'll make the correlations -.9
correlation_matrix <-
matrix(c(1, -.9,
-.9, 1),
nrow = 2, ncol = 2)
# we'll have to redo the covariance matrix
covariance_matrix <-
sd %*% t(sd) * correlation_matrix
# here's the updated data
set.seed(1)
d <- MASS::mvrnorm(n = 1000, mu = mu, Sigma = covariance_matrix) %>%
as_tibble() %>%
set_names(str_c("theta[", 1:2, "]"))
```
Here are our right-panel Figure 12.1 histograms.
```{r, fig.width = 8, fig.height = 2.75}
d %>%
mutate(`theta[1]-theta[2]` = `theta[1]` - `theta[2]`) %>%
gather() %>%
ggplot(aes(x = value, y = 0)) +
stat_histintervalh(point_interval = mode_hdi, .width = .95,
fill = "grey67", slab_color = "grey92",
breaks = 20, slab_size = .25, outline_bars = T,
normalize = "panels") +
scale_y_continuous(NULL, breaks = NULL) +
xlab(expression(theta)) +
theme(panel.grid = element_blank()) +
facet_wrap(~key, scales = "free_y", labeller = label_parsed)
```
Behold the second scatter plot.
```{r, fig.height = 2.75}
d %>%
ggplot(aes(x = `theta[1]`, y = `theta[2]`)) +
geom_abline(color = "white") +
geom_point(size = 1/2, color = "grey50", alpha = 1/4) +
coord_equal(xlim = c(0, 1),
ylim = c(0, 1)) +
labs(x = expression(theta[1]),
y = expression(theta[2])) +
theme(panel.grid = element_blank())
```
> In summary, the marginal distributions of two parameters do not indicate the relationship between the parameter values. The joint distribution of the two parameters might have positive or negative correlation (or even a non-linear dependency), and therefore the difference of the parameter values should be explicitly examined. (pp. 341--342)
### Why HDI and not equal-tailed interval?
Though Kruschke told us Figure 12.2 was of a gamma distribution, he didn't tell us the parameters for that particular gamma. After playing around for a bit, it appeared `dgamma(x, 2, .2)` worked pretty well.
```{r, fig.width = 4, fig.height = 2}
tibble(x = seq(from = 0, to = 40, by = .1)) %>%
ggplot(aes(x = x)) +
geom_ribbon(aes(ymin = 0,
ymax = dgamma(x, 2, .2)),
fill = "grey67") +
coord_cartesian(xlim = c(0, 35)) +
theme(panel.grid = element_blank())
```
If you want to get the quantile-based intervals (i.e., the ETIs), you can plug in the desired quantiles into the `qgamma()` function.
```{r}
(ex <- qgamma(c(.025, .975), shape = 2, rate = .2))
```
To analytically derive the gamma HDIs, we just use the good old `hdi_of_icdf()` function.
```{r}
(
hx <-
hdi_of_icdf(name = qgamma,
shape = 2,
rate = .2)
)
```
Next you need to determine how high up to go on the y-axis. For the quantile-based intervals, the ETIs, you can use `dgamma()`. The trick is pump the output of `qgamma()` into `dgamma()`.
```{r}
(
ey <-
qgamma(c(.025, .975), shape = 2, rate = .2) %>%
dgamma(shape = 2, rate = .2)
)
```
We follow the same basic principle to get the $y$-axis values for the HDIs.
```{r}
(
hy <-
hdi_of_icdf(name = qgamma, shape = 2, rate = .2) %>%
dgamma(shape = 2, rate = .2)
)
```
Now we've computed all those values, we can collect them into a tibble with the necessary coordinates to make the ETI and HDI lines in our plot.
```{r}
(
lines <-
tibble(interval = rep(c("eti", "hdi"), each = 4),
x = c(ex, hx) %>% rep(., each = 2),
y = c(ey[1], 0, 0, ey[2], 0, hy, 0))
)
```
We're finally ready to plot a more complete version of Figure 12.2.
```{r, fig.width = 6, fig.height = 3}
tibble(x = seq(from = 0, to = 40, by = .1)) %>%
ggplot(aes(x = x)) +
geom_ribbon(aes(ymin = 0, ymax = dgamma(x, 2, .2)),
fill = "grey67") +
geom_path(data = lines,
aes(y = y, color = interval),
size = 1) +
geom_text(data = tibble(
x = c(15, 12),
y = c(.004, .012),
label = c("95% ETI", "95% HDI"),
interval = c("eti", "hdi")
),
aes(y = y, color = interval, label = label)) +
scale_color_manual(values = c("black", "white")) +
scale_y_continuous(NULL, breaks = NULL) +
coord_cartesian(xlim = c(0, 35)) +
xlab("Density Value") +
theme(legend.position = "none",
panel.grid = element_blank())
```
To repeat, ETIs are the only types of intervals available directly by the **brms** package. When using the default `print()` or `summary()` output for a `brm()` model, the 95% ETIs are displayed in the 'l-95% CI' and 'u-95% CI' columns.
```{r}
print(fit9.2)
```
In the output of most other **brms** functions, the 95% ETIs appear in the `Q2.5` and `Q97.5` columns. Take `fitted()`, for example.
```{r}
fitted(fit9.2,
newdata = nd,
scale = "linear")
```
But as we just did, above, you can always use the convenience functions from the **tidybayes** package (e.g., `mean_hdi()`) to get HDIs from a **brms** fit.
```{r}
fitted(fit9.2,
newdata = nd,
scale = "linear",
summary = F) %>%
as_tibble() %>%
gather() %>%
group_by(key) %>%
mean_hdi(value)
```
As you may have gathered, Kruschke clearly prefers using HDIs over ETIs. His preference isn't without controversy. If you'd like to explore the topic further in the form of saucy twitter banter, the inimitable [Dan Simpson](https://twitter.com/dan_p_simpson) has just [the thread](https://twitter.com/dan_p_simpson/status/1134095728190676992) for you. Here's [the link](https://discourse.mc-stan.org/t/quantiles-vs-hpdi-from-rstan-summary/9025) to the corresponding thread in the Stan discourse forum.
## The model-comparison approach
> Recall that the motivating issue for this chapter is the question, Is the null value of a parameter credible? The previous section answered the question in terms of parameter estimation. In that approach, we started with a possibly informed prior distribution and examined the posterior distribution.
>
> In this section we take a different approach. Some researchers prefer instead to pose the question in terms of model comparison. In this framing of the question, the focus is not on estimating the magnitude of the parameter. Instead, the focus is on deciding which of two hypothetical prior distributions is least incredible. One prior expresses the hypothesis that the parameter value is exactly the null value. The alternative prior expresses the hypothesis that the parameter could be any value, according to some form of broad distribution. (p. 344)
### Is a coin fair or not?
Some [e.g., @leeModelingIndividualDifferences2005; @zhuCounterintuitiveNoninformativePrior2004] have argued the Haldane prior is superior to the uniform $\operatorname{beta} (1, 1)$ when choosing an uninformative prior for $\theta$. The Haldane, recall, is $\operatorname{beta} (\epsilon, \epsilon)$, where $\epsilon$ is some small value approaching zero (e.g., 0.01). We'll use our typical steps with the grid aproximation to compute the data for the left column of Figure 12.3 (i.e., the column based on the Haldane prior).
```{r}
# we need these to compute the likelihood
n <- 24
z <- 7
epsilon <- .01
trial_data <- c(rep(0, times = n - z), rep(1, times = z))
d <-
tibble(theta = seq(from = 0, to = 1, length.out = 1000)) %>%
mutate(prior = dbeta(x = theta, shape1 = epsilon, shape2 = epsilon),
likelihood = bernoulli_likelihood(theta = theta,
data = trial_data)) %>%
# we have to slice off the first and last values because they go to infinity on the prior,
# which creats problems when computing the denominator `sum(likelihood * prior)` (i.e., p(D))
slice(2:999) %>%
mutate(posterior = likelihood * prior / sum(likelihood * prior))
head(d)
```
Here's the left column of Figure 12.3.
```{r, fig.width = 4, fig.height = 6, warning = F, message = F}
p1 <-
d %>%
ggplot(aes(x = theta)) +
geom_ribbon(aes(ymin = 0, ymax = prior),
fill = "grey50") +
annotate(geom = "text", x = .1, y = 4,
label = expression(epsilon == 0.01), size = 3.5) +
labs(title = "Prior (beta)",
x = expression(theta),
y = expression("beta"*(theta*"|"*epsilon*", "*epsilon)))
p2 <-
d %>%
ggplot(aes(x = theta)) +
geom_ribbon(aes(ymin = 0, ymax = likelihood),
fill = "grey50") +
labs(title = "Likelihood (Bernoulli)",
x = expression(theta),
y = expression(p(D*"|"*theta)))
p3 <-
d %>%
ggplot(aes(x = theta)) +
geom_ribbon(aes(ymin = 0, ymax = posterior),
fill = "grey50") +
labs(title = "Posterior (beta)",
x = expression(theta),
y = expression("beta"*(theta*"|"*7.01*", "*17.01)))
library(patchwork)
(p1 / p2 / p3) &
scale_y_continuous(breaks = NULL) &
theme(panel.grid = element_blank())
```
We can calculate the beta parameters for the posterior using the formula $\operatorname{beta} (\theta | z + \alpha, N - z + \beta)$.
```{r}
# alpha
z + epsilon
# beta
n - z + epsilon
```
We need updated data for the right column, based on the $\operatorname{Beta} (2, 4)$ prior.
```{r}
alpha <- 2
beta <- 4
d <-
tibble(theta = seq(from = 0, to = 1, length.out = 1000)) %>%
mutate(prior = dbeta(x = theta, shape1 = alpha, shape2 = beta),
likelihood = bernoulli_likelihood(theta = theta,
data = trial_data)) %>%
# no need to `slice(2:999)` this time
mutate(posterior = likelihood * prior / sum(likelihood * prior))
head(d)
```
Now here's the right column of Figure 12.3.
```{r, fig.width = 4, fig.height = 6, warning = F, message = F}
p1 <-
d %>%
ggplot(aes(x = theta)) +
geom_ribbon(aes(ymin = 0, ymax = prior),
fill = "grey50") +
labs(title = "Prior (beta)",
x = expression(theta),
y = expression("beta"*(theta*"|"*2*", "*4)))
p2 <-
d %>%
ggplot(aes(x = theta)) +
geom_ribbon(aes(ymin = 0, ymax = likelihood),
fill = "grey50") +
labs(title = "Likelihood (Bernoulli)",
x = expression(theta),
y = expression(p(D*"|"*theta)))
p3 <-
d %>%
ggplot(aes(x = theta)) +
geom_ribbon(aes(ymin = 0, ymax = posterior),
fill = "grey50") +
labs(title = "Posterior (beta)",
x = expression(theta),
y = expression("beta"*(theta*"|"*9*", "*21)))
(p1 / p2 / p3) &
scale_y_continuous(breaks = NULL) &
theme(panel.grid = element_blank())
```
Here are those beta parameters for that posterior.
```{r}
# alpha
z + alpha
# beta
n - z + beta
```
Following the formula for the null hypothesis,
$$p(z, N|M_\text{null}) = \theta_\text{null}^z(1 - \theta_\text{null})^{(N - z)},$$
we can compute the probability of the data given the null hypothesis.
```{r}
theta <- .5
(p_d_null <- theta ^ z * (1 - theta) ^ (n - z))
```
The formula for the marginal likelihood for the alternative hypothesis $M_\text{alt}$ is
$$p(z, N| M_\text{alt}) = \frac{\operatorname{beta} (z + \alpha_\text{alt}, N - z + \beta_\text{alt})}{\operatorname{beta} (\alpha_\text{alt}, \beta_\text{alt})}.$$
We can make our own `p_d()` function to compute the probability of the data given alternative hypotheses. Here we'll simplify the function a bit to extract `z` and `n` out of the environment.
```{r}
p_d <- function(a, b) {
beta(z + a, n - z + b) / beta(a, b)
}
```
With `p_d_null` and our `p_d()` function in hand, we can reproduce and extend the results in Kruschke's Equation 12.4.
```{r}
options(scipen = 999)
tibble(shape1 = c(2, 1, .1, .01, .001, .0001, .00001),
shape2 = c(4, 1, .1, .01, .001, .0001, .00001)) %>%
mutate(p_d = p_d(a = shape1, b = shape2),
p_d_null = p_d_null) %>%
mutate(bf = p_d / p_d_null) %>%
# this just reduces the amount of significant digits in the output
mutate_all(round, digits = 6)
options(scipen = 0)
```
Did you notice our use of `options(scipen)`? With the first line, we turned off scientific notation in the print output. We turned scientific notation back on with the second line. But back to the text,
> for now, notice that when the alternative prior is uniform, with $a_\text{alt} = b_\text{alt} = 1.000$, the Bayes' factor shows a (small) preference for the alternative hypothesis, but when the alternative prior approximates the Haldane, the Bayes' factor shows a strong preference for the null hypothesis. As the alternative prior gets closer to the Haldane limit, the Bayes' factor changes by orders of magnitude. Thus, as we have seen before (e.g. Section 10.6, p. 292), the Bayes’ factor is *very sensitive to the choice of prior distribution*. (p. 345, *emphasis* added)
On page 346, Kruschke showed some of the 95% HDIs for the marginal distributions of the various $M_\text{alt}$s. We could compute those one at a time with `hdi_of_icdf()`. But why not work in bulk? Like we did in Chapter 10, let's make a custom variant `hdi_of_qbeta()`, which will be more useful within the context of `map2()`.
```{r}
hdi_of_qbeta <- function(shape1, shape2) {
hdi_of_icdf(name = qbeta,
shape1 = shape1,
shape2 = shape2) %>%
data.frame() %>%
mutate(level = c("ll", "ul")) %>%
spread(key = level, value = ".")
}
```
Compute the HDIs.
```{r}
tibble(shape1 = z + c(2, 1, .1, .01, .001, .0001, .00001),
shape2 = n - z + c(4, 1, .1, .01, .001, .0001, .00001)) %>%
mutate(h = map2(shape1, shape2, hdi_of_qbeta)) %>%
unnest(h) %>%
mutate_at(vars(ends_with("l")), .funs = ~round(., digits = 4))
```
As Kruschke mused,
> if we consider the posterior distribution instead of the Bayes' factor, we see that the posterior distribution on $\theta$ within the alternative model is only slightly affected by the prior... In all cases, the 95% HDI excludes the null value, although a wide ROPE might overlap the HDI. Thus, the explicit estimation of the bias parameter robustly indicates that the null value should be rejected, but perhaps only marginally. This contrasts with the Bayes' factor, model-comparison approach, which rejected the null or accepted the null depending on the alternative prior.
Further,
> of the Bayes' factors in Equation 12.4, which is most appropriate? If your analysis is driven by the urge for a default, uninformed alternative prior, then the prior that best approximates the Haldane is most appropriate. Following from that, we should strongly prefer the null hypothesis to the Haldane alternative. While this is mathematically correct, it is meaningless for an applied setting because the Haldane alternative represents nothing remotely resembling a credible alternative hypothesis. The Haldane prior sets prior probabilities of virtually zero at all values of $\theta$ except $\theta = 0$ and $\theta = 1$. There are very few applied settings where such a U-shaped prior represents a genuinely meaningful theory. (p. 346).
### Bayes' factor can accept null with poor precision.
Here are the steps to make the left column of Figure 12.4 (i.e., the column based on very weak data and the Haldane prior).
```{r, fig.width = 4, fig.height = 6, warning = F}
# we need these to compute the likelihood
n <- 2
z <- 1
trial_data <- c(rep(0, times = n - z), rep(1, times = z))
d <-
tibble(theta = seq(from = 0, to = 1, length.out = 1000)) %>%
mutate(prior = dbeta(x = theta, shape1 = epsilon, shape2 = epsilon),
likelihood = bernoulli_likelihood(theta = theta,
data = trial_data)) %>%
# like before, we have to slice off the first and last values because they go to infinity on the
# prior, which creats problems when computing the denominator `sum(likelihood * prior)` (i.e., p(D))
slice(2:999) %>%
mutate(posterior = likelihood * prior / sum(likelihood * prior))
p1 <-
d %>%
ggplot(aes(x = theta)) +
geom_ribbon(aes(ymin = 0, ymax = prior),
fill = "grey50") +
annotate(geom = "text", x = .1, y = 4,
label = expression(epsilon == 0.01), size = 3.5) +
labs(title = "Prior (beta)",
x = expression(theta),
y = expression("beta"*(theta*"|"*epsilon*", "*epsilon)))
p2 <-
d %>%
ggplot(aes(x = theta)) +
geom_ribbon(aes(ymin = 0, ymax = likelihood),
fill = "grey50") +
labs(title = "Likelihood (Bernoulli)",
x = expression(theta),
y = expression(p(D*"|"*theta)))
p3 <-
d %>%
ggplot(aes(x = theta)) +
geom_ribbon(aes(ymin = 0, ymax = posterior),
fill = "grey50") +
labs(title = "Posterior (beta)",
x = expression(theta),
y = expression("beta"*(theta*"|"*7.01*", "*17.01)))
(p1 / p2 / p3) &
scale_y_continuous(breaks = NULL) &
theme(panel.grid = element_blank())
```
That is one flat posterior! Here are the shape parameters and the HDIs.
```{r}
(alpha <- z + epsilon)
(beta <- n - z + epsilon)
hdi_of_icdf(name = qbeta,
shape1 = alpha,
shape2 = beta) %>%
round(digits = 3)
```
How do we compute the BF?
```{r}
theta <- .5
a <- epsilon
b <- epsilon
# pD_{null} pD_{alternative}
(theta ^ z * (1 - theta) ^ (n - z)) / (beta(z + a, n - z + b) / beta(a, b))
```
Just like in the text, "the Bayes' factor is 51.0 in favor of the null hypothesis" (p. 347)!
Here are the steps to make the right column of Figure 12.4, which is based on stronger data and a flat $\operatorname{beta} (1, 1)$ prior.
```{r, fig.width = 4, fig.height = 6, warning = F}
# we need these to compute the likelihood
n <- 14
z <- 7
trial_data <- c(rep(0, times = n - z), rep(1, times = z))
d <-
tibble(theta = seq(from = 0, to = 1, length.out = 1e3)) %>%
mutate(prior = dbeta(x = theta, shape1 = alpha, shape2 = beta),
likelihood = bernoulli_likelihood(theta = theta,
data = trial_data)) %>%
# no need to `slice(2:999)` this time
mutate(posterior = likelihood * prior / sum(likelihood * prior))
p1 <-
d %>%
ggplot(aes(x = theta)) +
geom_ribbon(aes(ymin = 0, ymax = prior),
fill = "grey50") +
labs(title = "Prior (beta)",
x = expression(theta),
y = expression("beta"*(theta*"|"*1*", "*1)))
p2 <-
d %>%
ggplot(aes(x = theta)) +
geom_ribbon(aes(ymin = 0, ymax = likelihood),
fill = "grey50") +
labs(title = "Likelihood (Bernoulli)",
x = expression(theta),
y = expression(p(D*"|"*theta)))
p3 <-
d %>%
ggplot(aes(x = theta)) +
geom_ribbon(aes(ymin = 0, ymax = posterior),
fill = "grey50") +
labs(title = "Posterior (beta)",
x = expression(theta),
y = expression("beta"*(theta*"|"*8*", "*8)))
(p1 / p2 / p3) &
scale_y_continuous(breaks = NULL) &
theme(panel.grid = element_blank())
```
Here are the updated shape parameters and the HDIs.
```{r}
(alpha <- z + epsilon)
(beta <- n - z + epsilon)
hdi_of_icdf(name = qbeta,
shape1 = alpha,
shape2 = beta) %>%
round(digits = 3)
```
Those HDIs are still pretty wide, but much less so than before. Let's compute the BF.
```{r}
a <- 1
b <- 1
# pD_{null} pD_{alternative}
(theta ^ z * (1 - theta) ^ (n - z)) / (beta(z + a, n - z + b) / beta(a, b))
```
A BF of 3.14 in favor of the null is lackluster evidence. And happily so given the breadth of the HDIs.
Kruschke discussed how we'd need $z = 1200$ and $N = 2400$ before the posterior HDIs would fit within a narrow ROPE like .48 and .52. Here's what that would look like based on the priors from Figure 12.4.
```{r, fig.width = 6, fig.height = 3.5, warning = F, message = F}
z <- 1200
n <- 2400
alpha <- z + epsilon
beta <- n - z + epsilon
d <- tibble(theta = seq(from = 0, to = 1, length.out = 1e3))
# the Haldane-based plot
p1 <-
d %>%
ggplot(aes(x = theta)) +
geom_rect(xmin = .48, xmax = .52,
ymin = -Inf, ymax = Inf,
color = "transparent", fill = "white") +
geom_ribbon(aes(ymin = 0, ymax = dbeta(theta, shape1 = alpha, shape2 = beta)),
fill = "grey67", size = 0) +
annotate(geom = "text", x = .01, y = 35,
label = expression(epsilon == 0.01), size = 3.5) +
labs(title = "This posterior used the Haldane prior.",
x = expression(theta))
# redefine the Beta parameters
alpha <- z + 1
beta <- n - z + 1
# the Beta(1, 1)-based plot
p2 <-
d %>%
ggplot(aes(x = theta)) +
geom_rect(xmin = .48, xmax = .52,
ymin = -Inf, ymax = Inf,
color = "transparent", fill = "white") +
geom_ribbon(aes(ymin = 0, ymax = dbeta(theta, shape1 = alpha, shape2 = beta)),
fill = "grey67", size = 0) +
labs(title = "This time we used the flat beta (1, 1).",
x = expression(theta))
(p1 / p2) &
scale_y_continuous(NULL, breaks = NULL) &
theme(panel.grid = element_blank())
```
> There is no way around this inconvenient statistical reality: high precision demands a large sample size (and a measurement device with minimal possible noise). But when we are trying to accept a specific value of $\theta$, is seems logically appropriate that we should have a reasonably precise estimate indicating that specific value. (p. 348)
### Are different groups equal or not?
> Researchers often want to ask the question, Are the groups different or not?
>
> As a concrete example, suppose we conduct an experiment about the effect of background music on the ability to remember. As a simple test of memory, each person tries to memorize the same list of 20 words (such as "chair," "shark," "radio," etc.). They see each word for a specific time, and then, after a brief retention interval, recall as many words as they can. (p. 348)
If you look in Kruschke's `OneOddGroupModelComp2E.R` file, you can get his simulation code. Here we've dramatically simplified it. This attempt does not exactly reproduce what his script did, but it gets it in spirit.
```{r}
# For each subject, specify the condition s/he was in,
# the number of trials s/he experienced, and the number correct.
n_g <- 20 # number of subjects per group
n_t <- 20 # number of trials per subject
set.seed(12)
my_data <-
tibble(condition = factor(c("Das Kruschke", "Mozart", "Bach", "Beethoven"),
levels = c("Das Kruschke", "Mozart", "Bach", "Beethoven")),