-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path03-sampling-the-imaginary.qmd
5798 lines (4522 loc) · 175 KB
/
03-sampling-the-imaginary.qmd
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
---
format: html
execute:
cache: true
---
# Sampling the Imaginary {#sec-chap03}
::: my-objectives
::: my-objectives-header
Learning Objectives:
:::
::: my-objectives-container
This chapter teaches the basic skills for working with samples from the
posterior distribution. We'll begin to use samples to summarize and
simulate model output. The skills learned here will apply to every
problem in the remainder of the book, even though the details of the
models and how the samples are produced will vary.
The chapter exploits the fact that people are better in counts than in
probabilities. We will take the probability distributions from the
previous chapter and sampling from them to produce counts.
:::
:::
## Vampire Example {.unnumbered}
### ORIGINAL {.unnumbered}
::: my-definition
::: my-definition-header
::: {#def-chap-03-1}
: Probability Notation
:::
:::
::: my-definition-container
As a repetition and to get a better understanding of the following
formulae in this section I read a very [basic introduction into
probability
notation]((https://www.mathsisfun.com/data/probability-events-conditional.html))
$P(A)$ means "**Probability Of Event A**".
::: my-example
::: my-example-header
Probability of an Event
:::
::: my-example-container
What is the probability of $2$ after throwing a dice?
$$P(A) = \frac{1}{6}$$
:::
:::
$P(B \mid A)$ means "**Probability of Event B given A**".
This is a conditional probability. After event $A$ has happened, what is
the probability of $B$? If the events are independent from each other
than the changes do not influence each other.
::: my-example
::: my-example-header
Independent Conditional Events
:::
::: my-example-container
The probability to throw $2$ in a second dice throw are still
$P(B \mid A) = \frac{1}{6}$. If the events are dependent of each other
then "Probability of event A and event B equals the probability of event
A times the probability of event B given event A."
$$
P(A \space and\space B) = P(A) \times P(B \mid A)
$$
:::
:::
::: my-example
::: my-example-header
Dependent Conditional Events
:::
::: my-example-container
Typical example is removing marble from a bag without replacement. Let's
take a red marble from a bag of $5$ red and $5$ blue marbles without
replacement. Here the probability of a red marble (in the second draw)
given the probability of a red marble (in the first draw) is
$$
\frac{5}{10} \times \frac{4}{9} = \frac{2}{9}
$$
:::
:::
:::
:::
#### a) Medical Test Scenario with Bayes theorem {.unnumbered}
> "suppose there is a blood test that correctly detects vampirism 95% of
> the time. In more precise and mathematical notation,
> $Pr(\text{positive test result} \mid vampire) = 0.95$. It's a very
> accurate test, nearly always catching real vampires. It also make
> mistakes, though, in the form of false positives. One percent of the
> time, it incorrectly diagnoses normal people as vampires,
> $Pr(\text{positive test result}|mortal) = 0.01$. The final bit of
> information we are told is that vampires are rather rare, being only
> $0.1\%$ of the population, implying $Pr(vampire) = 0.001$. Suppose now
> that someone tests positive for vampirism. What's the probability that
> he or she is a bloodsucking immortal?" ([McElreath, 2020, p.
> 49](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=68&annotation=W9MU6VCZ))
> "The correct approach is just to use Bayes' theorem to invert the
> probability, to compute $Pr(vampire|positive)$. The calculation can be
> presented as:
$$
\begin{align*}
Pr(vampire\mid positive) = \frac{Pr(positive\mid vampire) Pr(vampire)}{Pr(positive)}\\
\text{where Pr(positive) is the average probability of a positive test result, that is,}\\ Pr(positive) = Pr(positive \mid vampire) Pr(vampire) \\
+ Pr(positive \mid mortal) 1 − Pr(vampire)
\end{align*}
$$ {#eq-vampire} " ([McElreath, 2020, p.
49](zotero://select/groups/5243560/items/NFUEVASQ))
([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=68&annotation=X4KD33AT))
::: my-r-code
::: my-r-code-header
::: {#cnj-vampire-bayes-a}
a: Performing vampire calculation with `r glossary("Bayes’ theorem")` in
Base R
:::
:::
::: my-r-code-container
```{r}
#| label: vampire-bayes-a
## R code 3.1a Vampire ##################
pr_positive_vampire_a <- 0.95
pr_positive_mortal_a <- 0.01
pr_vampire_a <- 0.001
pr_positive_a <- pr_positive_vampire_a * pr_vampire_a +
pr_positive_mortal_a * (1 - pr_vampire_a)
(
pr_vampire_positive_a <- pr_positive_vampire_a * pr_vampire_a / pr_positive_a
)
```
:::
:::
There is only an `r pr_vampire_positive_a`% chance that the suspect is
actually a vampire.
> "Most people find this result counterintuitive. And it's a very
> important result, because it mimics the structure of many realistic
> testing contexts, such as HIV and DNA testing, criminal profiling, and
> even statistical significance testing (see the Rethinking box at the
> end of this section). Whenever the condition of interest is very rare,
> having a test that finds all the true cases is still no guarantee that
> a positive result carries much information at all. The reason is that
> most positive results are false positives, even when all the true
> positives are detected correctly" ([McElreath, 2020, p.
> 49](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=68&annotation=CMMR49PQ))
#### b) Medical test scenario with natural frequencies {.unnumbered}
> "There is a way to present the same problem that does make it more
> intuitive" ([McElreath, 2020, p.
> 50](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=69&annotation=2DWF7729))
```
(1) In a population of 100,000 people, 100 of them are vampires.
(2) Of the 100 who are vampires, 95 of them will test positive for vampirism.
(3) Of the 99,900 mortals, 999 of them will test positive for vampirism.
```
There are 999 + 95 = `r 999 + 95` people tested positive. But from these
people only 95 / (999 + 95) = `r (95 / (999 + 95)) * 100` % are actually
vampires.
Or with a slightly different wording it is still easier to understand:
1. We can just count up the number of people who test positive:
$95 + 999 = 1094$.
2. Out of these $1094$ positive tests, $95$ of them are real vampires,
so that implies:
$$
Pr(positive \mid vampire) = \frac{95}{1094}
$$
::: my-r-code
::: my-r-code-header
::: {#cnj-vampire-frequencies-a}
a: Performing vampire calculation with frequencies in Base R
:::
:::
::: my-r-code-container
```{r}
#| label: vampire-frequencies-a
pr_vampire_a2 <- 100 / 100000
pr_positive_vampire_a2 <- 95 / 100
pr_positive_mortal_a2 <- 999 / 99900
pr_positive_a2 <- 95 + 999
(
pr_vampire_positive_a2 <-
pr_positive_vampire_a2 * 100 / pr_positive_a2
)
```
:::
:::
> "The second presentation of the problem, using counts rather than
> probabilities, is often called the frequency format or natural
> frequencies. Why a frequency format helps people intuit the correct
> approach remains contentious. Some people think that human psychology
> naturally works better when it receives information in the form a
> person in a natural environment would receive it. In the real world,
> we encounter counts only. No one has ever seen a probability, the
> thinking goes. But everyone sees counts ("frequencies") in their daily
> lives." ([McElreath, 2020, p.
> 50](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=69&annotation=G26ZTDUZ))
> "many scientists are uncomfortable with integral calculus, even though
> they have strong and valid intuitions about how to summarize data.
> Working with samples transforms a problem in calculus into a problem
> in data summary, into a frequency format problem. An integral in a
> typical Bayesian context is just the total probability in some
> interval. That can be a challenging calculus problem. But once you
> have samples from the probability distribution, it's just a matter of
> counting values in the interval. An empirical attack on the posterior
> allows the scientist to ask and answer more questions about the model,
> without relying upon a captive mathematician. For this reason, it is
> easier and more intuitive to work with samples from the posterior,
> than to work with probabilities and integrals directly." ([McElreath,
> 2020, p. 51](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=70&annotation=M7I2DV3C))
### TIDYVERSE {.unnumbered}
#### a) Medical Test Scenario with Bayes theorem {.unnumbered}
::: my-important
::: my-important-header
Vectors in Base R are tibble columns in tidyverse
:::
::: my-important-container
Whenever there is a calculation with vectors the pendant in tidyverse
mode is to generate columns in a tibble with `tibble::tibble()` or if
there is already a data frame with `dplyr::mutate()` and to do the
appropriate calculation with these columns.
The following @cnj-vampire-bayes-a transformed the Base R calculation
@cnj-vampire-bayes-b into a computation using the tidyverse approach.
:::
:::
::: my-r-code
::: my-r-code-header
::: {#cnj-vampire-bayes-b}
b: Performing the calculation using Bayes' theorem with tidyverse
approach in R
:::
:::
::: my-r-code-container
```{r}
#| label: vampire-bayes-b
## R code 3.1b Vampire ##########
tibble::tibble(pr_positive_vampire_b = .95,
pr_positive_mortal_b = .01,
pr_vampire_b = .001) |>
dplyr::mutate(pr_positive_b = pr_positive_vampire_b * pr_vampire_b
+ pr_positive_mortal_b * (1 - pr_vampire_b)) |>
dplyr::mutate(pr_vampire_positive_b =
pr_positive_vampire_b * pr_vampire_b / pr_positive_b) |>
dplyr::glimpse()
```
:::
:::
#### b) Medical test scenario with natural frequencies {.unnumbered}
::: my-r-code
::: my-r-code-header
::: {#cnj-vampire-frequencies-b}
b: Performing the calculation using frequencies with tidyverse approach
in R
:::
:::
::: my-r-code-container
```{r}
#| label: vampire-frequencies-b
tibble::tibble(pr_vampire_b2 = 100 / 100000,
pr_positive_vampire_b2 = 95 / 100,
pr_positive_mortal_b2 = 999 / 99900) |>
dplyr::mutate(pr_positive_b2 = 95 + 999) |>
dplyr::mutate(pr_vampire_positive_b2 =
pr_positive_vampire_b2 * 100 / pr_positive_b2) |>
dplyr::glimpse()
```
:::
:::
## Sampling from a grid-approximate posterior {#sec-chap03-sampling-grid}
### ORIGINAL
Before we are going to draw samples from the posterior distribution we
need to compute the distribution similar as we had done in the globe
tossing example.
> "Here's a reminder for how to compute the posterior for the globe
> tossing model, using grid approximation. Remember, the posterior here
> means the probability of p conditional on the data." ([McElreath,
> 2020, p. 52](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=71&annotation=KKQLR3FL))
::: my-r-code
::: my-r-code-header
::: {#cnj-grid-globe-tossing-a}
a: Generate the posterior distribution for the globe-tossing example
(Original)
:::
:::
::: my-r-code-container
```{r}
#| label: grid-globe-tossing-a
### R code 3.2a Grid Globe ##########################
# change prob_b to prior
# change prob_data to likelihood
# added variables: n_grid_a, n_success_a, n_trials_a
n_grid_a <- 1000L # number of grid points
n_success_a <- 6L # observed water
n_trials_a <- 9L # number of trials
p_grid_a <- seq(from = 0, to = 1, length.out = n_grid_a)
prior_a <- rep(1, n_grid_a) # = prior, = uniform distribution, 1000 times 1
likelihood_a <-
dbinom(n_success_a, size = n_trials_a, prob = p_grid_a) # = likelihood
posterior_a <- likelihood_a * prior_a
posterior_a <- posterior_a / sum(posterior_a)
```
:::
:::
> "Now we wish to draw 10,000 samples from this posterior. Imagine the
> posterior is a bucket full of parameter values, numbers such as
> $0.1, 0.7, 0.5, 1,$ etc. Within the bucket, each value exists in
> proportion to its posterior probability, such that values near the
> peak are much more common than those in the tails. We're going to
> scoop out 10,000 values from the bucket. Provided the bucket is well
> mixed, the resulting samples will have the same proportions as the
> exact posterior density. Therefore the individual values of $p$ will
> appear in our samples in proportion to the posterior plausibility of
> each value." ([McElreath, 2020, p.
> 52](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=71&annotation=GS5GCASA))
::: my-r-code
::: my-r-code-header
::: {#cnj-chap03-sample-posterior-globe-tossing}
a: Draw 1000 samples from the posterior distribution (Original)
:::
:::
::: my-r-code-container
```{r}
#| label: sample-globe-tossing-a
n_samples_a <- 1e4
base::set.seed(3) # for reproducibility
## R code 3.3a Sample Globe ##########################################
samples_a <- sample(p_grid_a,
prob = posterior_a, # from previous code chunk
size = n_samples_a, replace = TRUE)
```
:::
:::
The probability of each value is given by `posterior_a`, which we
computed with @cnj-grid-globe-tossing-a.
::: my-note
::: my-note-header
::: {#cor-excursion-a}
: Details for a better understanding and comparison with the tidyverse
version
:::
:::
::: my-note-container
To compare with the tidyverse version, I collected the three vectors
with `base::cbind()` into a matrix and displayed the first six lines
with `utils::head()`. Additionally I also displayed the first 10 values
of `samples_a` vector.
::: my-r-code
::: my-r-code-header
::: {#cnj-excursion-a}
a: Excursion for better comparison (Base R)
:::
:::
::: my-r-code-container
```{r}
#| label: excursion_a
# display grid results to compare with variant b
d_a <- cbind(p_grid_a, prior_a, likelihood_a, posterior_a)
head(d_a, 10)
# display sample results to compare with variant b
head(samples_a, 10)
```
:::
:::
:::
:::
::: my-r-code
::: my-r-code-header
::: {#cnj-globe-glossing-scatterplot-a}
a: Scatterplot of the drawn samples (Base R)
:::
:::
::: my-r-code-container
```{r}
#| label: fig-globe-tossing-scatterplot-a
#| fig-cap: "Scatterplot of the drawn samples (Base R)"
## R code 3.4a Globe Scatterplot #############
plot(samples_a)
```
:::
:::
> In fig-globe-glossing-plot-a "it's as if you are flying over the
> posterior distribution, looking down on it. There are many more
> samples from the dense region near 0.6 and very few samples below
> 0.25. On the right, the plot shows the density estimate computed from
> these samples." ([McElreath, 2020, p.
> 53](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=72&annotation=4WVLNZBT))
::: my-r-code
::: my-r-code-header
::: {#cnj-globe-tossing-density-plot-a}
a: Density estimate of the drawn samples (Rethinking)
:::
:::
::: my-r-code-container
```{r}
#| label: fig-globe-tossing-density-plot-a
#| fig-cap: "Density estimate of the drawn samples (Rethinking)"
## R code 3.5a Globe Density plot #############
rethinking::dens(samples_a)
```
:::
:::
### TIDYVERSE
::: my-r-code
::: my-r-code-header
::: {#cnj-grid-globe-tossing-b}
b: Generate the posterior distribution form the globe-tossing example
(Tidyverse)
:::
:::
::: my-r-code-container
```{r}
#| label: grid-globe-tossing-b
## R code 3.2b Grid Globe #####################
# how many grid points would you like?
n_grid_b <- 1000L
n_success_b <- 6L
n_trials_b <- 9L
d_b <-
tibble::tibble(p_grid_b = seq(from = 0, to = 1, length.out = n_grid_b),
prior_b = 1) |> # flat uniform prior, vector 1L recycling
dplyr::mutate(likelihood_b =
stats::dbinom(n_success_b, size = n_trials_b, prob = p_grid_b)) |>
dplyr::mutate(posterior_b =
(likelihood_b * prior_b) / sum(likelihood_b * prior_b))
head(d_b)
```
:::
:::
::: my-watch-out
::: my-watch-out-header
Variable names changed
:::
::: my-watch-out-container
I have changed McElreath's variable name `prob_p` and `prob_data` as
`prior_x` and `likelihood_x`, where `x` stands for `a` (Base R) or `b`
(Tidyverse).
To see the difference between grid and samples I will add "\_sample" to
all the other variable names.
:::
:::
::: my-r-code
::: my-r-code-header
::: {#cnj-sample-globe-tossing-b}
b: Draw 1000 samples from the posterior distribution (Tidyverse)
:::
:::
::: my-r-code-container
```{r}
#| label: sample-globe-tossing-b
## R code 3.3b Sample Globe #####################
# how many samples would you like?
n_samples_b <- 1e4
# make it reproducible
base::set.seed(3)
df_samples_b <-
d_b |>
dplyr::slice_sample(n = n_samples_b, weight_by = posterior_b, replace = T)
df_samples_b <- df_samples_b |>
dplyr::rename(samples_b = p_grid_b,
likelihood_samples_b = likelihood_b,
prior_samples_b = prior_b,
posterior_samples_b = posterior_b)
head(df_samples_b)
```
***
`identical(samples_a, df_samples_b$samples_b)` = `r identical(samples_a, df_samples_b$samples_b)`.
The column `samples_b` is identical with vector `samples_a`, because I
have used in both sampling processes `base::set.seed(3)`, so that I (and
you) could reproduce the data.
:::
:::
There are different possibilities to display data frames respectively
tibbles:
1. You can use the internal print facility of tibbles. It shows only
the first ten rows and all columns that fit on the screen. You see
an example in @cnj-sample-globe-tossing-b.
2. With the `utils::str()` function you will get a result with shorter
figures that is better adapted to a small screen.
3. Another alternative is the tidyverse approach of `dplyr::glimpse()`.
4. With `skimr::skim()` you will get a compact summary of all data.
::: my-r-code
::: my-r-code-header
::: {#cnj-excursion-b}
b: Excursion: Printing varieties for better comparison (Tidyverse)
:::
:::
::: my-r-code-container
```{r}
#| label: excursion-b
#| results: hold
glue::glue('USING THE str() FUNCTION:')
utils::str(df_samples_b)
glue::glue('#####################################################\n\n')
glue::glue('USING THE dplyr::glimpse() FUNCTION:')
dplyr::glimpse(df_samples_b)
glue::glue('#####################################################\n\n')
glue::glue('USING THE skimr::skim() FUNCTION:')
skimr::skim(df_samples_b)
```
:::
:::
We can plot the left panel of Figure 3.1 from the book with
`ggplot2::geom_point()`. But before we do, we'll need to add a variable
numbering the samples. This is necessary as the x-parameter of the plot.
::: my-r-code
::: my-r-code-header
::: {#cnj-globe-tossing-scatterplot-b}
b: Scatterplot of the drawn samples (Tidyverse)
:::
:::
::: my-r-code-container
```{r}
#| label: fig-globe-tossing-scatterplot-b
#| fig-cap: "Scatterplot of the drawn samples (Tidyverse)"
## R code 3.4b Globe Scatterplot ########################
df_samples_b |>
dplyr::mutate(sample_number = 1:dplyr::n()) |>
ggplot2::ggplot(ggplot2::aes(x = sample_number, y = samples_b)) +
ggplot2::geom_point(alpha = 1/10) +
ggplot2::scale_y_continuous("proportion of water (p)", limits = c(0, 1)) +
ggplot2::xlab("sample number") +
ggplot2::theme_bw()
```
:::
:::
If you hover over this link from @fig-globe-tossing-scatterplot-a you
can compare the Base R version with the tidyverse result.
Instead of the `rethinking::dens()` we'll plot the density in the right
panel of the books Figure 3.1 with `ggplot2::geom_density()`.
::: my-r-code
::: my-r-code-header
::: {#cnj-globe-tossing-densitiy-plot-b1}
b: Density estimate of the drawn samples with 1e4 grid points
(Tidyverse)
:::
:::
::: my-r-code-container
```{r}
#| label: fig-globe-tossing-density-plot-b1
#| fig-cap: "Density estimate of the drawn samples with 1e4 grid points (Tidyverse)"
## R code 3.5b(1) Globe Density ###########################
df_samples_b |>
ggplot2::ggplot(ggplot2::aes(x = samples_b)) +
ggplot2::geom_density(fill = "grey") +
ggplot2::scale_x_continuous("proportion of water (p)", limits = c(0, 1)) +
ggplot2::theme_bw()
```
:::
:::
Compare this somewhat smoother tidyverse plot with
@fig-globe-tossing-density-plot-a.
> "You can see that the estimated density is very similar to ideal
> posterior you computed via grid approximation. If you draw even more
> samples, maybe 1e5 or 1e6, the density estimate will get more and more
> similar to the ideal." ([McElreath, 2020, p.
> 53](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=72&annotation=EXBQWX2M))
Here's what it looks like with `1e6`.
::: my-r-code
::: my-r-code-header
::: {#cnj-ID-text}
b: Density estimate of the drawn samples with 1e6 grid points
(Tidyverse)
:::
:::
::: my-r-code-container
```{r}
#| label: fig-globe-tossing-density-plot-b2
#| fig-cap: "Density estimate of the drawn samples with 1e6 grid points (Tidyverse)"
base::set.seed(3)
## R code 3.5b(2) Globe Density ###########################
d_b |>
dplyr::slice_sample(n = 1e6, weight_by = posterior_b, replace = T) |>
ggplot2::ggplot(ggplot2::aes(x = p_grid_b)) +
ggplot2::geom_density(fill = "grey") +
ggplot2::scale_x_continuous("proportion of water (p)", limits = c(0, 1)) +
ggplot2::theme_bw()
```
:::
:::
## Sampling to Summarize {#sec-chap03-sampling-to-summarize}
All we have done so far is crudely replicate the posterior density we
had already computed in the previous chapter. Now it is time to use
these samples to describe and understand the posterior.
The description to understand the posterior can be divided into three
inquiries:
1. Questions about intervals of *defined boundaries*. See @sec-chap-03-defined-boundaries.
2. Questions about intervals of *defined probability mass*. See @sec-chap-03-probability-mass.
3. Questions about *point estimates*. See: @sec-chap-03-point-estimates.
### Intervals of Defined Boundaries {#sec-chap-03-defined-boundaries}
#### ORIGINAL
##### Grid-approximate Posterior
For instance: What is the probability that the proportion of water is
less than 0.5?
> "Using the grid-approximate posterior, you can just add up all of the
> probabilities, where the corresponding parameter value is less than
> 0.5:" ([McElreath, 2020, p.
> 53](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=72&annotation=Z7XSZ6WT))
::: my-r-code
::: my-r-code-header
::: {#cnj-grid-posterior-a}
a: Define boundaries using the grid-approximate posterior (Base R)
:::
:::
::: my-r-code-container
```{r}
#| label: grid-posterior-a
## R code 3.6a Grid Posterior Boundary ##############################
# add up posterior probability where p < 0.5
sum(posterior_a[p_grid_a < 0.5])
```
:::
:::
About 17% of the posterior probability is below 0.5.
##### Samples from the Posterior {#sec-chap03-samples-from-posterior}
But this easy calculation based on grid approximation is often not
practical when there are more parameters. In this case you can draw
samples from the posterior. But this approach requires a different
calculation:
> "This approach does generalize to complex models with many parameters,
> and so you can use it everywhere. All you have to do is similarly add
> up all of the samples below 0.5, but also // divide the resulting
> count by the total number of samples. In other words, find the
> frequency of parameter values below 0.5" (McElreath, 2020, p. 53/54)"
> ([McElreath, 2020, p.
> 53](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=72&annotation=SMQ6B78K))
::: my-r-code
::: my-r-code-header
::: {#cnj-sample-boundary-a}
a: Compute posterior probability below 0.5 using the sampling approach
(Base R)
:::
:::
::: my-r-code-container
```{r}
#| label: sample-boundary-a
## R code 3.7a Sample Boundary #############################
(p_boundary_a <- sum(samples_a < 0.5) / 1e4)
```
:::
:::
::: my-watch-out
::: my-watch-out-header
Different values with samples from the posterior
:::
::: my-watch-out-container
In comparison with the value of the posterior probability below 0.5 in
the book of 0.1726 the result in `r p_boundary_a` from
@cnj-sample-boundary-a is quite different.
The reason for the difference is that you can't get the same values in a
sampling processes. This is the nature of randomness. And McElreath did
not include the `base::set.seed()` function for (exact) reproducibility.
:::
:::
Using the same approach, you can ask how much posterior probability lies
between 0.5 and 0.75:
::: my-r-code
::: my-r-code-header
::: {#cnj-sample-interval-a}
a: Compute posterior probability between 0.5 and 0.75 using the sampling
approach (Base R)
:::
:::
::: my-r-code-container
```{r}
#| label: sample-interval-a
## R code 3.8a Sample Interval #############################
(p_boundary_a8 <- sum(samples_a > 0.5 & samples_a < 0.75) / 1e4)
```
:::
:::
#### TIDYVERSE
##### Grid-approximate Posterior
> To get the proportion of water less than some value of `p_grid_b`
> within the {**tidyverse}**, you might first `filter()` by that value
> and then take the `sum()` within `summarise()`.
> ([Kurz](https://bookdown.org/content/4857/sampling-the-imaginary.html#intervals-of-defined-boundaries.))
::: my-r-code
::: my-r-code-header
::: {#cnj-grid-boundary-b}
b: Compute posterior probability below 0.5 using the grid approach
(Tidyverse)
:::
:::
::: my-r-code-container
```{r}
#| label: grid-boundary-b
## R code 3.6b Grid Boundary ######################
# add up posterior probability where p < 0.5
d_b |> dplyr::filter(p_grid_b < 0.5) |>
dplyr::summarize(sum = base::sum(posterior_b))
```
:::
:::
##### Samples from the Posterior
Kurz offers several methods to calculate the posterior probability below
0.5:
1. **Method**: `filter()` & `n()` within `summarize()`
2. **Method**: `count()` followed by `mutate()`
3. **Method**: Logical condition within `mean()`
::: my-r-code
::: my-r-code-header
::: {#cnj-sample-boundary}
b: Compute posterior probability below 0.5 using the sampling approach
with different methods (Tidyverse)
:::
:::
::: my-r-code-container
```{r}
#| label: sample-boundary-b
#| results: hold
# add up all posterior probabilities of samples under .5
## R code 3.7b Sample Boundary #########################
###### Method (1) #######
method_1 <-
df_samples_b |>
dplyr::filter(samples_b < .5) |>
dplyr::summarize(sum = dplyr::n() / n_samples_b)
glue::glue('Method 1:\n')
method_1
glue::glue('##################################################\n\n')
###### Method (2) #######
method_2 <-
df_samples_b |>
dplyr::count(samples_b < .5) |>
dplyr::mutate(probability = n_samples_b / base::sum(n_samples_b))
glue::glue('Method 2:\n')
method_2
glue::glue('##################################################\n\n')
###### Method (3) #######
method_3 <-
df_samples_b |>
dplyr::summarize(sum = mean(samples_b < .5))
glue::glue('Method 3:\n')
method_3
```
:::
:::
To determine the posterior probability between 0.5 and 0.75, you can use
`&` within `filter()`. Just multiply that result by 100 to get the value
in percent.
::: my-r-code
::: my-r-code-header
::: {#cnj-sample-interval-b}
b: Compute posterior probability between 0.5 and 0.75 using the sampling
approach (Tidyverse)
:::
:::
::: my-r-code-container
```{r}
#| label: sample-interval-b
## R code 3.8b Sample Interval ##############
df_samples_b |>
dplyr::filter(samples_b > .5 & samples_b < .75) |>
dplyr::summarize(sum = dplyr::n() / n_samples_b)
```
:::
:::
And, of course, you can do this calculation with the other methods as
well.
To produce the top part of Figure 3.2 of the book we apply following
code lines:
::: my-r-code
::: my-r-code-header
::: {#cnj-fig-upper-part-3-2}
b: Posterior distribution produced with {**tidyverse**} approach
:::
:::
::: my-r-code-container
```{r}
#| label: fig-upper-part-3.2-b
#| fig-cap: "Upper part of SR2 Figure 3.2: Intervals of defined boundaries produced with {**tidyverse**} tools: Left: The blue area is the posterior probability below a parameter value of 0.5. Right: The posterior probability between 0.5 and 0.75."
## R Code Fig 3.2 Upper Part #############
# upper left panel
p1 <-
df_samples_b |>
ggplot2::ggplot(ggplot2::aes(x = samples_b, y = posterior_samples_b)) +
ggplot2::geom_line() +
ggplot2::geom_area(data = df_samples_b |>
dplyr::filter(samples_b < .5), fill = "deepskyblue") +
ggplot2::labs(x = "proportion of water (p)", y = "density") +
ggplot2::theme_bw()
# upper right panel
p2 <-
df_samples_b |>
ggplot2::ggplot(ggplot2::aes(x = samples_b, y = posterior_samples_b)) +
ggplot2::geom_line() +
ggplot2::geom_area(data = df_samples_b |>
dplyr::filter(samples_b > .5 & samples_b < .75), fill = "deepskyblue") +
ggplot2::labs(x = "proportion of water (p)", y = "density") +
ggplot2::theme_bw()
library(patchwork)
p1 + p2
```
:::
:::
### Intervals of Defined Probability Mass {#sec-chap-03-probability-mass}