-
Notifications
You must be signed in to change notification settings - Fork 1
/
04-geocentric-models.qmd
9110 lines (7285 loc) · 289 KB
/
04-geocentric-models.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
filters:
- quarto
- nameref
---
# Geocentric Models {#sec-chap04}
::: my-objectives
::: my-objectives-header
Learning Objectives:
:::
::: my-objectives-container
> "This chapter introduces `r glossary("linear regression")` as a
> Bayesian procedure. Under a probability interpretation, which is
> necessary for Bayesian work, linear regression uses a Gaussian
> (normal) distribution to describe our `r glossary("golem")`'s
> uncertainty about some measurement of interest." ([McElreath, 2020, p.
> 71](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=90&annotation=PHU5R9MI))
:::
:::
## Why normal distributions? {#sec-why-normal-dist-a}
Why are there so many distribution approximately normal, resulting in a
Gaussian curve? Because there will be more combinations of outcomes that
sum up to a "central" value, rather than to some extreme value.
::: my-important
::: my-important-header
Why are normal distributions normal?
:::
::: my-important-container
> "Any process that adds together random values from the same
> distribution converges to a normal." ([McElreath, 2020, p.
> 73](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=92&annotation=F8VYZH4I))
:::
:::
### Normal by addition
> "Whatever the average value of the source distribution, each sample
> from it can be thought of as a fluctuation from that average value.
> When we begin to add these fluctuations together, they also begin to
> cancel one another out. A large positive fluctuation will cancel a
> large negative one. The more terms in the sum, the more chances for
> each fluctuation to be canceled by another, or by a series of smaller
> ones in the opposite direction. So eventually the most likely sum, in
> the sense that there are the most ways to realize it, will be a sum in
> which every fluctuation is canceled by another, a sum of zero
> (relative to the mean)." ([McElreath, 2020, p.
> 73](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=92&annotation=PIK9MN9I))
> "It doesn't matter what shape the underlying distribution possesses.
> It could be uniform, like in our example above, or it could be
> (nearly) anything else. Depending upon the underlying distribution,
> the convergence might be slow, but it will be inevitable. Often, as in
> this example, convergence is rapid." ([McElreath, 2020, p.
> 74](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=93&annotation=GLCXRF8V))
::: my-resource
::: my-resource-header
Resources: Why normal distributions?
:::
::: my-resource-container
See the excellent article [Why is normal distribution so
ubiquitous?](https://ekamperi.github.io/mathematics/2021/01/29/why-is-normal-distribution-so-ubiquitous.html)
which also explains the example of random walks from SR2. See also the
scientific paper [Why are normal distribution
normal?](https://www.journals.uchicago.edu/doi/pdf/10.1093/bjps/axs046)
of the The British Journal for the Philosophy of Science.
:::
:::
### Normal by multiplication
This is not only valid for addition but also for multiplication of small
values: Multiplying small numbers is approximately the same as addition.
### Normal by log-multipliation
But even the multiplication of large values tend to produce Gaussian
distributions on the log scale.
### Using Gaussian distributions
The justifications for using the Gaussian distribution fall into two
broad categories:
1. **Ontological justification**: The Gaussian distributions is a
widespread pattern, appearing again and again at different scales
and in different domains.
2. **Epistemological justification**: When all we know is the mean and
variance of a distribution then the Gaussian distribution arises as
the most consistent with these assumptions.
::: my-watch-out
::: my-watch-out-header
WATCH OUT! Many processes have heavier tails than the Gaussian
distribution
:::
::: my-watch-out-container
> "... the Gaussian distribution has some very thin tails---there is
> very little probability in them. Instead most of the mass in the
> Gaussian lies within one standard deviation of the mean. Many natural
> (and unnatural) processes have much heavier tails." ([McElreath, 2020,
> p. 76](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=95&annotation=LFRDF45M))
:::
:::
::: my-definition
::: my-definition-header
::: {#def-mass-density}
: Probability mass and probability density
:::
:::
::: my-definition-container
- Probability distributions with only discrete outcomes, like the
binomial, are called `r glossary("probability mass function")`s and
denoted `Pr`.
- Continuous ones like the Gaussian are called
`r glossary("probability density function")`s, denoted with $p$ or
just plain old $f$, depending upon author and tradition.
> "Probability *density* is the rate of change in cumulative
> probability. So where cumulative probability is increasing rapidly,
> density can easily exceed 1. But if we calculate the area under the
> density function, it will never exceed 1. Such areas are also called
> *probability mass*." ([McElreath, 2020, p.
> 76](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=95&annotation=577IRETG))
For example `dnorm(0,0,0.1)` which is the way to make R calculate
$p(0 \mid 0, 0.1)$ results to `r dnorm(0,0,0.1)`.
:::
:::
> "The Gaussian distribution is routinely seen without σ but with
> another parameter, $\tau$ . The parameter $\tau$ in this context is
> usually called *precision* and defined as $\tau = 1/σ^2$. When
> $\sigma$ is large, $\tau$ is small." ([McElreath, 2020, p.
> 76](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=95&annotation=4UW673GU))
> "This form is common in Bayesian data analysis, and Bayesian model
> fitting software, such as `r glossary("BUGS")` or
> `r glossary("JAGS")`, sometimes requires using $\tau$ rather than
> $\sigma$." ([McElreath, 2020, p.
> 76](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=95&annotation=9VQCJW2G))
## Model describing language
::: my-procedure
::: my-procedure-header
::: {#prp-model-language}
: General receipt for describing models
:::
:::
::: my-procedure-container
1. First, we recognize a set of variables to work with. Some of these
variables are observable. We call these data. Others are
unobservable things like rates and averages. We call these
parameters.
2. We define each variable either in terms of the other variables or in
terms of a probability distribution.
3. The combination of variables and their probability distributions
defines a joint generative model that can be" ([McElreath, 2020, p.
77](zotero://select/groups/5243560/items/NFUEVASQ))
([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=96&annotation=IC4KGA5D))
:::
:::
::: my-definition
::: my-definition-header
::: {#def-model}
: What are statistical models?
:::
:::
::: my-definition-container
`r glossary("Statistical Model", "Models")` are "mappings of one set of
variables through a probability distribution onto another set of
variables." ([McElreath, 2020, p.
77](zotero://select/groups/5243560/items/NFUEVASQ))
([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=96&annotation=NSVA3R2F))
:::
:::
### Re-describing the globe tossing model
::: my-example
::: my-example-header
::: {#exm-formula-glob-tossing-model}
: Describe the globe tossing model from @sec-chap03
:::
:::
::: my-example-container
$$
\begin{align*}
W \sim \operatorname{Binomial}(N, p) \space \space (1)\\
p \sim \operatorname{Uniform}(0, 1) \space \space (2)
\end{align*}
$$ {#eq-globe-tossing-model}
- `W`: observed count of water
- `N`: total number of tosses
- `p`: proportion of water on the globe
The first line in these kind of models always defines the likelihood
function used in `r glossary("Bayes’ theorem")`. The other lines define
priors.
Read the above statement as:
1. **First line**: The count W is distributed binomially with sample
size `N` and probability `p`.
2. **Second line**: The prior for `p` is assumed to be uniform between
zero and one.
------------------------------------------------------------------------
Both of the lines in the model of @eq-globe-tossing-model are
`r glossary("stochastic")`, as indicated by the `~` symbol. A stochastic
relationship is just a mapping of a variable or parameter onto a
distribution. It is stochastic because no single instance of the
variable on the left is known with certainty. Instead, the mapping is
probabilistic: Some values are more plausible than others, but very many
different values are plausible under any model. Later, we'll have models
with deterministic definitions in them.
:::
:::
## Gaussian model of height {#sec-gaussian-model-of-height}
In this section we want a single measurement variable to model as a
Gaussian distribution. It is a preparation for the linear regression
model in @sec-linear-prediction-a where we will construct and add a
predictor variable to the model.
> "There will be two parameters describing the distribution's shape, the
> `r glossary("arithmetic mean", "mean")` `μ` and the
> `r glossary("standard deviation")` `σ`.
> `r glossary("Bayesian updating")` will allow us to consider every
> possible combination of values for μ and σ and to score each
> combination by its relativ // plausibility, in light of the data.
> These relative plausibilities are the
> `r glossary("posterior probability", "posterior probabilities")` of
> each combination of values μ, σ." ([McElreath, 2020, p.
> 78/79](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=98&annotation=RAYXZIGU))
### The data
::: my-resource
::: my-resource-header
Resource: Nancy Howell data
:::
::: my-resource-container
- Howell, N. (2001). Demography of the Dobe! Kung (2nd ed.).
Routledge.
- Howell, N. (2010). Life Histories of the Dobe !kung: Food, Fatness,
and Well-being over the Life Span: Food, Fatness, and Well-Being
Over the Life-Span Volume 4. University of California Press.
The data contained in `data(Howell1)` are partial census data for the
Dobe area !Kung San, compiled from interviews conducted by Nancy Howell
in the late 1960s.
Much more raw data is available for download from the [University of
Toronto
Library](https://tspace.library.utoronto.ca/simple-search?query=nancy+howell&filter_field_1=author&filter_type_1=equals&filter_value_1=Howell%2C+Nancy&sort_by=score&order=desc&rpp=10&etal=0&start=0)
> "For the non-anthropologists reading along, the !Kung San are the most
> famous foraging population of the twentieth century, largely because
> of detailed quantitative studies by people like Howell." ([McElreath,
> 2020, p. 79](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=98&annotation=XUZLTB86))
:::
:::
::: my-watch-out
::: my-watch-out-header
WATCH OUT! Loading data without attaching the package with `library()`
:::
::: my-watch-out-container
::: panel-tabset
###### Standard
Loading data from a package with the `data()` function is only possible
if you have already loaded the package.
::: my-r-code
::: my-r-code-header
::: {#cnj-standard-data-loading}
: Data loading from a package -- Standard procedure
:::
:::
::: my-r-code-container
```{r}
#| label: loading-data-from-package1_a
#| eval: false
## R code 4.7 not executed! #######################
# library(rethinking)
# data(Howell1)
# d_a <- Howell1
```
The standard loading of data from packages with
```
`library(rethinking)`
`data(Howell1)`
```
is in this book not executed: I want to prevent clashes with loading
{**rethinking**} and {**brms**} at the same time, because of their
similar functions.
:::
:::
###### Unusual (Original)
Because of many function name conflicts with {**brms**} I do not want to
load {**rethinking**} and will call the function of these conflicted
packages with `<package name>::<function name>()` Therefore I have to
use another, not so usual loading strategy of the data set.
::: my-r-code
::: my-r-code-header
::: {#cnj-unusual-data-loading-a}
a: Data loading from a package -- Unusual procedure (Original)
:::
:::
::: my-r-code-container
```{r}
#| label: loading-data-from-package2_a
data(package = "rethinking", list = "Howell1")
d_a <- Howell1
head(d_a)
```
:::
:::
The advantage of this unusual strategy is that I have not always to
detach the {**rethinking**} package and to make sure {**rethinking**} is
detached before using {**brms**} as it is necessary in the Kurz's
{**tidyverse**} / {**brms**} version.
###### Unusual (Tidyverse)
Because of many function name conflicts with {**brms**} I do not want to
load {**rethinking**} and will call the function of these conflicted
packages with `<package name>::<function name>()` Therefore I have to
use another, not so usual loading strategy of the data set.
::: my-r-code
::: my-r-code-header
::: {#cnj-unusual-data-loading-b}
b: Data loading from a package -- Unusual procedure (Tidyverse)
:::
:::
::: my-r-code-container
```{r}
#| label: loading-data-from-package_2b
data(package = "rethinking", list = "Howell1")
d_b <- tibble::as_tibble(Howell1)
head(d_b)
```
:::
:::
The advantage of this unusual strategy is that I have not always to
detach the {**rethinking**} package and to make sure {**rethinking**} is
detached before using {**brms**} as it is necessary in the Kurz's
{**tidyverse**} / {**brms**} version.
:::
:::
:::
#### Show the data
::: my-example
::: my-example-header
::: {#exm-show-data}
: Show and inspect the data
:::
:::
::: my-example-container
::: panel-tabset
###### str()
::: my-r-code
::: my-r-code-header
::: {#cnj-show-data-str-a}
a: Compactly Display the Structure of an Arbitrary R Object (Original)
:::
:::
::: my-r-code-container
```{r}
#| label: show-howell-data-str-a
#| results: hold
## R code 4.8 ####################
str(d_a)
```
`utils::str()` displays compactly the internal **str**ucture of any
reasonable R object.
Our Howell1 data contains four columns. Each column has 544 entries, so
there are 544 individuals in these data. Each individual has a recorded
height (centimeters), weight (kilograms), age (years), and "maleness" (0
indicating female and 1 indicating male).
:::
:::
###### precis()
::: my-r-code
::: my-r-code-header
::: {#cnj-show-data-precis-a}
a: Displays concise parameter estimate information for an existing model
fit (Original)
:::
:::
::: my-r-code-container
```{r}
#| label: show-howell-data-precis-a
#| results: hold
## R code 4.9 ###################
rethinking::precis(d_a)
```
`rethinking::precis()` creates a table of estimates and standard errors,
with optional confidence intervals and parameter correlations.
In this case we see the mean, the standard deviation, the width of a 89%
posterior interval and a small histogram of four variables: height
(centimeters), weight (kilograms), age (years), and "maleness" (0
indicating female and 1 indicating male).
Additionally there is also a console output. In our case:
`'data.frame': 544 obs. of 4 variables:` .
:::
:::
###### glimpse()
::: my-r-code
::: my-r-code-header
::: {#cnj-show-data-glimpse-b}
b: Get a glimpse of your data (Tidyverse)
:::
:::
::: my-r-code-container
```{r}
#| label: show-howell-data-glimpse-b
d_b |>
dplyr::glimpse()
```
`pillar::glimpse()` is re-exported by {**dplyr**} and is the tidyverse
analogue for `str()`. It works like a transposed version of `print()`:
columns run down the page, and data runs across.
`dplyr::glimpse()` shows that the Howell1 data contains four columns.
Each column has 544 entries, so there are 544 individuals in these data.
Each individual has a recorded height (centimeters), weight (kilograms),
age (years), and "maleness" (0 indicating female and 1 indicating male).
:::
:::
###### summary()
::: my-r-code
::: my-r-code-header
::: {#cnj-show-data-summary-b}
: Object summaries (Tidyverse)
:::
:::
::: my-r-code-container
```{r}
#| label: show-howell-data-summary-b
d_b |>
base::summary()
```
Kurz tells us that the {**brms**} package does not have a function that
works like `rethinking::precis()` for providing numeric and graphical
summaries of variables, as seen in @cnj-show-data-precis-a Kurz suggests
therefore to use `base::summary()` to get some of the information from
`rethinking::precis()`.
:::
:::
###### skim()
::: my-r-code
::: my-r-code-header
::: {#cnj-show-data-skim-b}
b: Skim a data frame, getting useful summary statistics
:::
:::
::: my-r-code-container
I think `skimr::skim()` is a better option as an alternative to
`rethinking::precis()` as `base::summary()` because it also has a
graphical summary of the variables. {**skimr**} has many other useful
functions and is very adaptable. I propose to install and to try it out.
```{r}
#| label: show-howell-data-skim-b
d_b |>
skimr::skim()
```
:::
:::
###### slice_sample()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap04-show-data-slice-sample}
: Show a random number of data records
::::::
:::
::::{.my-r-code-container}
```{r}
#| label: chap04-show-data-slice-sample
set.seed(4)
d_b |>
dplyr::slice_sample(n = 6)
```
::::
:::::
###### as_tbl_obs()
::: my-r-code
::: my-r-code-header
::: {#cnj-show-data-as-tbl-obs-b}
b: Randomly select a small number of observations and put it into
`knitr::kable()`
:::
:::
::: my-r-code-container
```{r}
#| label: show-howell-data-as-tbl-obs-b
#| warning: false
set.seed(4)
d_b |>
bayr::as_tbl_obs()
```
I just learned another method to print variables from a data frame. In
base R there is `utils::head()` and `utils::tail()` with the
disadvantage that the start resp. the end of data file could be atypical
for the variable values. The standard tibble printing method has the
same problem. In contrast `bayr::as_tbl_obs()` prints a random selection
of maximal 8 rows as a compact and nice output, that works on both,
console and {**knitr**} output.
Although `bayr::as_tbl_obs()` does not give a data *summary* as
discussed here in @exm-show-data but I wanted mention this printing
method as I have always looked for an easy way to display a
representative sample of some values of data frame.
:::
:::
###### print()
::: my-r-code
::: my-r-code-header
::: {#cnj-show-data-print-as-tibble-b}
b: Show data with the internal printing method of tibbles
:::
:::
::: my-r-code-container
```{r}
#| label: show-howell-data-print-as-tibble-b
print(d_b, n = 10)
```
Another possibility is to use the `tbl_df` internal printing method, one
of the main features of tibbles. Printing can be tweaked for a one-off
call by calling `print()` explicitly and setting arguments like $n$ and
$width$. More persistent control is available by setting the options
described in `pillar::pillar_options`.
Again this printing method does not give a data summary as is featured
in @exm-show-data. But it is an easy method -- especially as you are
already working with tibbles -- and sometimes this method is enough to
get a sense of the data.
:::
:::
:::
:::
:::
#### Select the height data of adults
> "All we want for now are heights of adults in the sample. The reason
> to filter out nonadults for now is that height is strongly correlated
> with age, before adulthood." ([McElreath, 2020, p.
> 80](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=99&annotation=VCYRP6W4))
::: my-example
::: my-example-header
::: {#exm-adult-data}
: Select the height data of adults (individuals older or equal than 18
years)
:::
:::
::: my-example-container
::: panel-tabset
###### Original
::: my-r-code
::: my-r-code-header
::: {#cnj-adult-data-a}
a: Select individuals older or equal than 18 years (Original)
:::
:::
::: my-r-code-container
```{r}
#| label: select-height-adults-a
## R code 4.11a ###################
d2_a <- d_a[d_a$age >= 18, ]
str(d2_a)
```
:::
:::
###### Tidyverse
::: my-r-code
::: my-r-code-header
::: {#cnj-adult-data-b}
b: Select individuals older or equal than 18 years (Tidyverse)
:::
:::
::: my-r-code-container
```{r}
#| label: select-height-adults-b
## R code 4.11b ###################
d2_b <-
d_b |>
dplyr::filter(age >= 18)
dplyr::glimpse(d2_b)
```
:::
:::
:::
:::
:::
### The model
Our goal is to model the data using a Gaussian distribution.
#### Plot the distribution of heights
::: my-example
::: my-example-header
::: {#exm-plot-height-dist}
: Plotting the distribution of height
:::
:::
::: my-example-container
::: panel-tabset
###### Original
::: my-r-code
::: my-r-code-header
::: {#cnj-plot-height-dist-a}
a: Plot the distribution of the heights of adults, overlaid by an ideal
Gaussian distribution (Original)
:::
:::
::: my-r-code-container
```{r}
#| label: fig-dist-heights-a
#| fig-cap: "The distribution of the heights data, overlaid by an ideal Gaussian distribution (Original)"
rethinking::dens(d2_a$height, adj = 1, norm.comp = TRUE)
```
:::
:::
With the option `norm.comp = TRUE` I have overlaid a Gaussian
distribution to see the differences to the actual data. There are some
differences locally, especially on the peak of the distribution. But the
tails looks nice and we can say that the overall impression of the curve
is Gaussian.
###### Tidyverse
::: my-r-code
::: my-r-code-header
::: {#cnj-plot-height-dist-b}
b: Plot the distribution of the heights of adults, overlaid by an ideal
Gaussian distribution (Tidyverse)
:::
:::
::: my-r-code-container
```{r}
#| label: fig-dist-heights-b
#| fig-cap: "The distribution of the heights data, overlaid by an ideal Gaussian distribution: tidyverse version"
d2_b |>
ggplot2::ggplot(ggplot2::aes(height)) +
ggplot2::geom_density() +
ggplot2::stat_function(
fun = dnorm,
args = with(d2_b, c(mean = mean(height), sd = sd(height)))
) +
ggplot2::labs(
x = "Height in cm",
y = "Density"
) +
ggplot2::theme_bw()
```
:::
:::
The plot of the heights distribution compared with the standard Gaussian
distribution is missing in Kurz's version. I added this plot after an
internet research by using the last example of [How to Plot a Normal
Distribution in
R](https://www.statology.org/plot-normal-distribution-r/). It uses the
`ggplot2::stat_function()` to compute and draw a function as a
continuous curve. This makes it easy to superimpose a function on top of
an existing plot.
:::
:::
:::
::: my-watch-out
::: my-watch-out-header
WATCH OUT! Looking at the raw data is not enough for a model decision
:::
::: my-watch-out-container
> "Gawking at the raw data, to try to decide how to model them, is
> usually not a good idea. The data could be a mixture of different
> Gaussian distributions, for example, and in that case you won't be
> able to detect the underlying normality just by eyeballing the outcome
> distribution." ([McElreath, 2020, p.
> 81](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=100&annotation=DMU8TC6L))
:::
:::
::: my-theorem
::: my-theorem-header
::: {#thm-def-heights}
: Define the heights as normally distributed with a mean $\mu$ and
standard deviation $\sigma$
:::
:::
::: my-theorem-container
$$
h_{i} \sim \operatorname{Normal}(σ, μ)
$$ {#eq-height-normal-dist}
- **Symbol h**: refers to the list of heights
- **Subscript i**: refers to each individual element of the list. It
is conventional to use $i$ because it stands for index. The index
$i$ takes on row numbers, and so in this example can take any value
from 1 to 352 (the number of heights in `d2_a$height`). As such, the
model above is saying that all the golem knows about each height
measurement is defined by the same normal distribution, with mean
$\mu$ and standard deviation $\sigma$.
@eq-height-normal-dist assumes that the values $h_{i}$ are
`r glossary("i.i.d.")` (independent and identically distributed)
:::
:::
> "The i.i.d. assumption doesn't have to seem awkward, as long as you
> remember that probability is inside the golem, not outside in the
> world. The i.i.d. assumption is about how the golem represents its
> uncertainty. It is an *epistemological* assumption. It is not a
> physical assumption about the world, an *ontological* one. E. T.
> Jaynes (1922--1998) called this the *mind projection fallacy*, the
> mistake of confusing epistemological claims with ontological claims."
> ([McElreath, 2020, p.
> 81](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=100&annotation=VFIF5ITN))
> "To complete the model, we're going to need some priors. The
> parameters to be estimated are both $\mu$ and $\sigma$, so we need a
> prior $Pr(\mu, \sigma)$, the joint prior probability for all
> parameters. In most cases, priors are specified independently for each
> parameter, which amounts to assuming
> $Pr(\mu, \sigma) = Pr(\mu)Pr(\sigma)$." ([McElreath, 2020, p.
> 82](zotero://select/groups/5243560/items/NFUEVASQ))
> ([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=101&annotation=5HVI6LB4))
::: my-theorem
::: my-theorem-header
::: {#thm-linear-heights-model}
: Define the linear heights model
:::
:::
::: my-theorem-container
$$
\begin{align*}
h_{i} \sim \operatorname{Normal}(\mu, \sigma) \space \space (1) \\
\mu \sim \operatorname{Normal}(178, 20) \space \space (2) \\
\sigma \sim \operatorname{Uniform}(0, 50) \space \space (3)
\end{align*}
$$ {#eq-height-linear-model-m4-1}
------------------------------------------------------------------------
1. First line represents the likelihood.
2. Second line is the chosen $\mu$ (mu, mean) prior. It is a broad
Gaussian prior, centered on 178 cm, with 95% of probability between
178 ± 40 cm.
3. Third line is the chosen $\sigma$ (sigma, standard deviation) prior.
:::
:::
Let's think about the chosen value for the priors more in detail:
**1. Choosing the mean prior**
- **Why normal distribution?**: As we have stated before in
@thm-def-heights the heights distribution of adults is a Gaussian
distribution.
- **Why 178cm?**: "Your author is 178 cm tall. And the range from 138
cm to 218 cm encompasses a huge range of plausible mean heights for
human populations. So domain-specific information has gone into this
prior." ([McElreath, 2020, p.
82](zotero://select/groups/5243560/items/NFUEVASQ))
([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=101&annotation=DUN4YP7H))
- **Why 95% and 40cm?**: 40cm (T= twice sigma = 2\* 20) and 95% is a
reference to the [68--95--99.7
rule](https://en.wikipedia.org/w/index.php?title=68%E2%80%9395%E2%80%9399.7_rule&oldid=1187581793)
that helps to remember how many percentages of values lie within an
interval estimate in a normal distribution:
$$
\begin{align}
\Pr(\mu-1\sigma \le X \le \mu+1\sigma) & \approx 68.27\% \\
\Pr(\mu-2\sigma \le X \le \mu+2\sigma) & \approx 95.45\% \\
\Pr(\mu-3\sigma \le X \le \mu+3\sigma) & \approx 99.73\%
\end{align}
$$
**2. Choosing the sigma prior**
- **Why uniform distribution?**: We assume `r glossary("i.i.d.")`,
e.g., the standard deviation is over the whole distribution
identical.
- **Why 0 as lower limit?**: "A standard deviation like σ must be
positive, so bounding it at zero makes sense." ([McElreath, 2020, p.
82](zotero://select/groups/5243560/items/NFUEVASQ))
([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=101&annotation=9KXSZF9A))
- **Why 50 as upper limit?** "... a standard deviation of 50 cm would
imply that 95% of individual heights lie within 100 cm of the
average height." ([McElreath, 2020, p.
82](zotero://select/groups/5243560/items/NFUEVASQ))
([pdf](zotero://open-pdf/groups/5243560/items/CPFRPHX8?page=101&annotation=5653WGIL))
Thas is a range large enough to include variation of heights.
::: my-important
::: my-important-header
Plot the chosen priors!
:::
::: my-important-container
It is important to plot the priors to get an idea about the assumptions
they build into your model.
:::
:::
::: my-example
::: my-example-header
::: {#exm-ID-text}
: Numbered Example Title
:::
:::
::: my-example-container
::: panel-tabset
###### $\mu$ (Original)
::: my-r-code
::: my-r-code-header
::: {#cnj-code-name-a}
a: Plot the chosen mean prior (Original)
:::
:::
::: my-r-code-container
```{r}
#| label: fig-mean-prior-a
#| fig-cap: "Plot of the chosen mean prior (Original)"
## R code 4.12 ###############################
graphics::curve(stats::dnorm(x, 178, 20), from = 100, to = 250)
```
:::
:::
You can see that the golem is assuming that the average height (not each
individual height) is almost certainly between 140 cm and 220 cm. So
this prior carries a little information, but not a lot.
###### $\sigma$ (Original)
::: my-r-code
::: my-r-code-header
::: {#cnj-code-name-b}
a: Plot chosen prior for the standard deviation (Original)
:::
:::
::: my-r-code-container
```{r}
#| label: fig-sd-prior-a
#| fig-cap: "Plot the chosen prior for the standard deviation (Original)"
## R code 4.13 ###########################
graphics::curve(stats::dunif(x, 0, 50), from = -10, to = 60)
```
:::
:::
###### $\mu$ (Tidyverse)
::: my-r-code
::: my-r-code-header
<div>
b: Plot the chosen mean prior (Tidyverse)
</div>
:::