-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05.Rmd
1764 lines (1395 loc) · 64.4 KB
/
05.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: "Ch. 5 Multivariate Linear Models"
author: "A Solomon Kurz"
date: "`r format(Sys.Date())`"
output:
github_document
---
```{r, echo = F, cache = F}
knitr::opts_chunk$set(fig.retina = 2.5)
options(width = 100)
```
# Multivariate Linear Models
McElreath's listed reasons for multivariable regression include
* statistical control for confounds,
* multiple causation, and
* interactions.
We'll approach the first two in this chapter. Interactions are reserved for [Chapter 7][Interactions].
#### Rethinking: Causal inference.
"Despite its central importance, there is no unified approach to causal inference yet in the sciences or in statistics" (p. 120).
McElreath didn't cover this much in this edition of the text. However, it appears his second edition will cover it more extensively. He announced as much in [this blog post](https://elevanth.org/blog/2018/07/14/statistical-rethinking-edition-2-eta-2020/) and experimented in mixing it in with the material in during his [Statistical Rethinking Winter 2019](https://www.youtube.com/channel/UCNJK6_DZvcMqNSzQdEkzvzA/playlists) lecture series. To dip in, you might check out the recent blog post by Finn Lattimore and David Rohde, [*Causal Inference with Bayes Rule*](https://gradientinstitute.org/blog/6/).
## Spurious associations
Load the [Waffle House](https://www.snopes.com/fact-check/fema-waffle-house-index/) data.
```{r, message = F, warning = F}
library(rethinking)
data(WaffleDivorce)
d <- WaffleDivorce
```
Unload rethinking and load brms and, while we're at it, the tidyverse.
```{r, message = F, warning = F}
rm(WaffleDivorce)
detach(package:rethinking, unload = T)
library(brms)
library(tidyverse)
```
I'm not going to show the output, but you might go ahead and investigate the data with the typical functions. E.g.,
```{r, results = "hide"}
head(d)
glimpse(d)
```
Now we have our data, we can reproduce Figure 5.1. One convenient way to get the handful of sate labels into the plot was with the `geom_text_repel()` function from the [ggrepel package](https://cran.r-project.org/package=ggrepel). But first, we spent the last few chapters warming up with ggplot2. Going forward, each chapter will have its own plot theme. In this chapter, we'll characterize the plots with `theme_bw() + theme(panel.grid = element_rect())` and coloring based off of `"firebrick"`.
```{r, fig.width = 3, fig.height = 3}
# install.packages("ggrepel", depencencies = T)
library(ggrepel)
d %>%
ggplot(aes(x = WaffleHouses/Population, y = Divorce)) +
stat_smooth(method = "lm", fullrange = T, size = 1/2,
color = "firebrick4", fill = "firebrick", alpha = 1/5) +
geom_point(size = 1.5, color = "firebrick4", alpha = 1/2) +
geom_text_repel(data = d %>% filter(Loc %in% c("ME", "OK", "AR", "AL", "GA", "SC", "NJ")),
aes(label = Loc),
size = 3, seed = 1042) + # this makes it reproducible
scale_x_continuous("Waffle Houses per million", limits = c(0, 55)) +
ylab("Divorce rate") +
coord_cartesian(xlim = 0:50, ylim = 5:15) +
theme_bw() +
theme(panel.grid = element_blank())
```
Since these are geographically-based data, we might plot our three major variables in a map format. The [urbnmapr package](https://github.com/UrbanInstitute/urbnmapr) provides latitude and longitude data for the 50 states and the `geom_sf()` function for plotting them. We'll use the `left_join()` function to combine those data with our primary data `d`.
```{r, fig.width = 8, fig.height = 2, warning = F, message = F}
# devtools::install_github("UrbanInstitute/urbnmapr")
library(urbnmapr)
left_join(
# get the map data
get_urbn_map(map = "states", sf = TRUE),
# add the primary data
d %>%
# tandardize the three variables to put them all on the same scale
mutate(Divorce_z = (Divorce - mean(Divorce)) / sd(Divorce),
MedianAgeMarriage_z = (MedianAgeMarriage - mean(MedianAgeMarriage)) / sd(MedianAgeMarriage),
Marriage_z = (Marriage - mean(Marriage)) / sd(Marriage),
# convert the state names to characters to match the map data
state_name = Location %>% as.character()) %>%
select(Divorce_z:Marriage_z:state_name),
by = "state_name"
) %>%
# convert to the long format for faceting
pivot_longer(ends_with("_z")) %>%
# plot!
ggplot() +
geom_sf(aes(fill = value, geometry = geometry),
size = 0) +
scale_fill_gradient(low = "#f8eaea", high = "firebrick4") +
theme_void() +
theme(legend.position = "none",
strip.text = element_text(margin = margin(0, 0, .5, 0))) +
facet_wrap(~name)
```
One of the advantages of this visualization method is it just became clear that Nevada is missing from the `WaffleDivorce` data. Execute `d %>% distinct(Location)` to see for yourself and click [here](https://github.com/rmcelreath/rethinking/issues/62) to find out why it's missing. Those missing data should motivate the skills we'll cover in [Chapter 14][Missing Data and Other Opportunities]. But let's get back on track.
Here we'll officially standardize the predictor, `MedianAgeMarriage`.
```{r}
d <-
d %>%
mutate(MedianAgeMarriage_s = (MedianAgeMarriage - mean(MedianAgeMarriage)) /
sd(MedianAgeMarriage))
```
Now we're ready to fit the first univariable model.
```{r b5.1}
b5.1 <-
brm(data = d,
family = gaussian,
Divorce ~ 1 + MedianAgeMarriage_s,
prior = c(prior(normal(10, 10), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 10), class = sigma)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5,
file = "fits/b05.01")
```
Check the summary.
```{r}
print(b5.1)
```
We'll employ `fitted()` to make Figure 5.2.b. In preparation for `fitted()` we'll make a new tibble, `nd`, composed of a handful of densely-packed values for our predictor, `MedianAgeMarriage_s`. With the `newdata` argument, we'll use those values to return model-implied expected values for `Divorce`.
```{r, fig.width = 3, fig.height = 3}
# define the range of `MedianAgeMarriage_s` values we'd like to feed into `fitted()`
nd <- tibble(MedianAgeMarriage_s = seq(from = -3, to = 3.5, length.out = 30))
# now use `fitted()` to get the model-implied trajectories
f <-
fitted(b5.1, newdata = nd) %>%
as_tibble() %>%
# tack the `nd` data onto the `fitted()` results
bind_cols(nd)
# plot
ggplot(data = f,
aes(x = MedianAgeMarriage_s, y = Estimate)) +
geom_smooth(aes(ymin = Q2.5, ymax = Q97.5),
stat = "identity",
fill = "firebrick", color = "firebrick4", alpha = 1/5, size = 1/4) +
geom_point(data = d,
aes(y = Divorce),
size = 2, color = "firebrick4") +
ylab("Divorce") +
coord_cartesian(xlim = range(d$MedianAgeMarriage_s),
ylim = range(d$Divorce)) +
theme_bw() +
theme(panel.grid = element_blank())
```
Before fitting the next model, we'll standardize `Marriage`.
```{r}
d <-
d %>%
mutate(Marriage_s = (Marriage - mean(Marriage)) / sd(Marriage))
```
We're ready to fit our second univariable model, this time with `Marriage_s` as the predictor.
```{r b5.2}
b5.2 <-
brm(data = d,
family = gaussian,
Divorce ~ 1 + Marriage_s,
prior = c(prior(normal(10, 10), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 10), class = sigma)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5,
file = "fits/b05.02")
```
```{r}
print(b5.2)
```
Now we'll wangle and plot our version of Figure 5.2.a.
```{r, fig.width = 3, fig.height = 3}
nd <- tibble(Marriage_s = seq(from = -2.5, to = 3.5, length.out = 30))
f <-
fitted(b5.2, newdata = nd) %>%
as_tibble() %>%
bind_cols(nd)
ggplot(data = f,
aes(x = Marriage_s, y = Estimate)) +
geom_smooth(aes(ymin = Q2.5, ymax = Q97.5),
stat = "identity",
fill = "firebrick", color = "firebrick4", alpha = 1/5, size = 1/4) +
geom_point(data = d,
aes(y = Divorce),
size = 2, color = "firebrick4") +
ylab("Divorce") +
coord_cartesian(xlim = range(d$Marriage_s),
ylim = range(d$Divorce)) +
theme_bw() +
theme(panel.grid = element_blank())
```
> But merely comparing parameter means between different bivariate regressions is no way to decide which predictor is better Both of these predictors could provide independent value, or they could be redundant, or one could eliminate the value of the other. So we'll build a multivariate model with the goal of measuring the partial value of each predictor. The question we want answered is:
>
>> *What is the predictive value of a variable, once I already know all of the other predictor variables?* (p. 123, *emphasis* in the original)
### Multivariate notation.
Now we'll get both predictors in there with our very first multivariable model. We can write the statistical model as
\begin{align*}
\text{Divorce}_i & \sim \operatorname{Normal}(\mu_i, \sigma) \\
\mu_i & = \alpha + \beta_1 \text{Marriage_s}_i + \beta_2 \text{MedianAgeMarriage_s}_i \\
\alpha & \sim \operatorname{Normal}(10, 10) \\
\beta_1 & \sim \operatorname{Normal}(0, 1) \\
\beta_2 & \sim \operatorname{Normal}(0, 1) \\
\sigma & \sim \operatorname{Uniform}(0, 10).
\end{align*}
> It might help to read the $+$ symbols as "or" and then say: *A State’s divorce rate can be a function of its marriage rate **or** its median age at marriage*. The "or" indicates independent associations, which may be purely statistical or rather causal. (p. 124, *emphasis* in the original)
### Fitting the model.
Much like we used the `+` operator to add single predictors to the intercept, we just use more `+` operators in the `formula` argument to add more predictors. Also notice we're using the same prior `prior(normal(0, 1), class = b)` for both predictors. Within the brms framework, they are both of `class = b`. But if we wanted their priors to differ, we'd make two `prior()` statements and differentiate them with the `coef` argument. You'll see examples of that later on.
```{r b5.3}
b5.3 <-
brm(data = d,
family = gaussian,
Divorce ~ 1 + Marriage_s + MedianAgeMarriage_s,
prior = c(prior(normal(10, 10), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 10), class = sigma)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5,
file = "fits/b05.03")
```
Our multivariable summary will have multiple rows below the 'Intercept' row.
```{r}
print(b5.3)
```
The `mcmc_plot()` function is an easy way to get a default coefficient plot. You just put the brmsfit object into the function.
```{r, fig.width = 6, fig.height = 1.5}
mcmc_plot(b5.3)
```
There are numerous ways to make a coefficient plot. Another is with the `mcmc_intervals()` function from the [bayesplot package](https://cran.r-project.org/package=bayesplot). A nice feature of the bayesplot package is its convenient way to alter the color scheme with the `color_scheme_set()` function. Here, for example, we'll make the theme `red`. But note how the `mcmc_intervals()` function requires you to work with the `posterior_samples()` instead of the brmsfit object.
```{r, message = F, warning = F, fig.width = 6, fig.height = 1.5}
# install.packages("bayesplot", dependencies = T)
library(bayesplot)
post <- posterior_samples(b5.3)
color_scheme_set("red")
mcmc_intervals(post[, 1:4],
prob = .5,
point_est = "median") +
ggtitle("My fancy bayesplot-based coefficient plot") +
theme_bw() +
theme(axis.text.y = element_text(hjust = 0),
axis.ticks.y = element_blank(),
panel.grid = element_blank())
```
Because bayesplot produces a ggplot2 object, the plot was adjustable with familiar ggplot2 syntax. For more ideas, check out [this vignette](https://cran.r-project.org/package=bayesplot/vignettes/plotting-mcmc-draws.html).
The `tidybaes::stat_pointintervalh()` function offers a third way, this time with a more ground-up ggplot2 workflow.
```{r, message = F, warning = F, fig.width = 6, fig.height = 1.5}
library(tidybayes)
post %>%
select(b_Intercept:sigma) %>%
gather() %>%
ggplot(aes(x = value, y = reorder(key, value))) + # note how we used `reorder()` to arrange the coefficients
geom_vline(xintercept = 0, color = "firebrick4", alpha = 1/10) +
stat_pointintervalh(point_interval = mode_hdi, .width = .95,
size = 3/4, color = "firebrick4") +
labs(title = "My tidybayes-based coefficient plot",
x = NULL, y = NULL) +
theme_bw() +
theme(axis.text.y = element_text(hjust = 0),
axis.ticks.y = element_blank(),
panel.grid = element_blank(),
panel.grid.major.y = element_line(color = alpha("firebrick4", 1/4), linetype = 3))
```
The substantive interpretation of all those coefficient plots is: "*Once we know median age at marriage for a State, there is little or no additive predictive power in also knowing the rate of marriage in that State*" (p. 126, *emphasis* in the original).
### Plotting multivariate posteriors.
McElreath's prose is delightfully deflationary. "There is a huge literature detailing a variety of plotting techniques that all attempt to help one understand multiple linear regression. None of these techniques is suitable for all jobs, and most do not generalize beyond linear regression" (p. 126). Now you're inspired, let's learn three:
* Predictor residual plots,
* Counterfactual plots, and
* Posterior prediction plots.
#### Predictor residual plots.
To get ready to make our residual plots, we'll predict `Marriage_s` with `MedianAgeMarriage_s`.
```{r b5.4}
b5.4 <-
brm(data = d,
family = gaussian,
Marriage_s ~ 1 + MedianAgeMarriage_s,
prior = c(prior(normal(0, 10), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 10), class = sigma)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5,
file = "fits/b05.04")
```
```{r}
print(b5.4)
```
With `fitted()`, we compute the expected values for each state (with the exception of Nevada). Since the `MedianAgeMarriage_s` values for each state are in the date we used to fit the model, we'll omit the `newdata` argument.
```{r}
f <-
fitted(b5.4) %>%
as_tibble() %>%
bind_cols(d)
head(f)
```
After a little data processing, we can make Figure 5.3.
```{r, fig.width = 3, fig.height = 3}
f %>%
ggplot(aes(x = MedianAgeMarriage_s, y = Marriage_s)) +
geom_point(size = 2, shape = 1, color = "firebrick4") +
geom_segment(aes(xend = MedianAgeMarriage_s, yend = Estimate),
size = 1/4) +
geom_line(aes(y = Estimate),
color = "firebrick4") +
coord_cartesian(ylim = range(d$Marriage_s)) +
theme_bw() +
theme(panel.grid = element_blank())
```
We get the residuals with the well-named `residuals()` function. Much like with `brms::fitted()`, `brms::residuals()` returns a four-vector matrix with the number of rows equal to the number of observations in the original data (by default, anyway). The vectors have the familiar names: `Estimate`, `Est.Error`, `Q2.5`, and `Q97.5`. See the [brms reference manual](https://cran.r-project.org/package=brms/brms.pdf) for details.
With our residuals in hand, we just need a little more data processing to make Figure 5.4.a.
```{r, fig.width = 3, fig.height = 3}
r <-
residuals(b5.4) %>%
# to use this in ggplot2, we need to make it a tibble or data frame
as_tibble() %>%
bind_cols(d)
# for the annotation at the top
text <-
tibble(Estimate = c(- 0.5, 0.5),
Divorce = 14.1,
label = c("slower", "faster"))
# plot
r %>%
ggplot(aes(x = Estimate, y = Divorce)) +
stat_smooth(method = "lm", fullrange = T,
color = "firebrick4", fill = "firebrick4",
alpha = 1/5, size = 1/2) +
geom_vline(xintercept = 0, linetype = 2, color = "grey50") +
geom_point(size = 2, color = "firebrick4", alpha = 2/3) +
geom_text(data = text,
aes(label = label)) +
scale_x_continuous("Marriage rate residuals", limits = c(-2, 2)) +
coord_cartesian(xlim = range(r$Estimate),
ylim = c(6, 14.1)) +
theme_bw() +
theme(panel.grid = element_blank())
```
To get the `MedianAgeMarriage_s` residuals, we have to fit the corresponding model first.
```{r b5.4b}
b5.4b <-
brm(data = d,
family = gaussian,
MedianAgeMarriage_s ~ 1 + Marriage_s,
prior = c(prior(normal(0, 10), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 10), class = sigma)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5,
file = "fits/b05.04b")
```
And now we'll get the new batch of residuals, do a little data processing, and make a plot corresponding to Figure 5.4.b.
```{r, fig.width = 3, fig.height = 3}
# redefine the annotation data
text <-
tibble(Estimate = c(- 0.7, 0.5),
Divorce = 14.1,
label = c("younger", "older"))
# extract the residuals
residuals(b5.4b) %>%
as_tibble() %>%
bind_cols(d) %>%
# plot
ggplot(aes(x = Estimate, y = Divorce)) +
stat_smooth(method = "lm", fullrange = T,
color = "firebrick4", fill = "firebrick4",
alpha = 1/5, size = 1/2) +
geom_vline(xintercept = 0, linetype = 2, color = "grey50") +
geom_point(size = 2, color = "firebrick4", alpha = 2/3) +
geom_text(data = text,
aes(label = label)) +
scale_x_continuous("Age of marriage residuals", limits = c(-2, 3)) +
coord_cartesian(xlim = range(r$Estimate),
ylim = c(6, 14.1)) +
theme_bw() +
theme(panel.grid = element_blank())
```
> So what's the point of all this? There’s direct value in seeing the model-based predictions displayed against the outcome, after subtracting out the influence of other predictors. The plots in Figure 5.4 do this. But this procedure also brings home the message that regression models answer with the remaining association of each predictor with the outcome, after already knowing the other predictors. In computing the predictor residual plots, you had to perform those calculations yourself. In the unified [multivariable] model, it all happens automatically. (p. 129)
#### Counterfactual plots.
> A second sort of inferential plot displays the implied predictions of the model. I call these plots *counterfactual*, because they can be produced for any values of the predictor variable you like, even unobserved or impossible combinations like very high median age of marriage and very high marriage rate. There are no States with this combination, but in a counterfactual plot, you can ask the model for a prediction for such a State. (p. 129, *emphasis* in the original)
Making Figure 5.5.a requires a little more data wrangling than before.
```{r, fig.width = 3, fig.height = 3}
# we need new `nd` data
nd <-
tibble(Marriage_s = seq(from = -3, to = 3, length.out = 30),
MedianAgeMarriage_s = mean(d$MedianAgeMarriage_s))
fitted(b5.3, newdata = nd) %>%
as_tibble() %>%
# since `fitted()` and `predict()` name their intervals the same way,
# we'll need to `rename()` them to keep them straight
rename(f_ll = Q2.5,
f_ul = Q97.5) %>%
# note how we're just nesting the `predict()` code right inside `bind_cols()`
bind_cols(
predict(b5.3, newdata = nd) %>%
as_tibble() %>%
# since we only need the intervals, we'll use `transmute()` rather than `mutate()`
transmute(p_ll = Q2.5,
p_ul = Q97.5),
# now tack on the `nd` data
nd) %>%
# we're finally ready to plot
ggplot(aes(x = Marriage_s, y = Estimate)) +
geom_ribbon(aes(ymin = p_ll, ymax = p_ul),
fill = "firebrick", alpha = 1/5) +
geom_smooth(aes(ymin = f_ll, ymax = f_ul),
stat = "identity",
fill = "firebrick", color = "firebrick4", alpha = 1/5, size = 1/4) +
labs(subtitle = "Counterfactual plot for which\nMedianAgeMarriage_s = 0",
y = "Divorce") +
coord_cartesian(xlim = range(d$Marriage_s),
ylim = c(6, 14)) +
theme_bw() +
theme(panel.grid = element_blank())
```
We follow the same process for Figure 5.5.b.
```{r, fig.width = 3, fig.height = 3}
# new data
nd <-
tibble(MedianAgeMarriage_s = seq(from = -3, to = 3.5, length.out = 30),
Marriage_s = mean(d$Marriage_s))
# `fitted()` + `predict()`
fitted(b5.3, newdata = nd) %>%
as_tibble() %>%
rename(f_ll = Q2.5,
f_ul = Q97.5) %>%
bind_cols(
predict(b5.3, newdata = nd) %>%
as_tibble() %>%
transmute(p_ll = Q2.5,
p_ul = Q97.5),
nd
) %>%
# plot
ggplot(aes(x = MedianAgeMarriage_s, y = Estimate)) +
geom_ribbon(aes(ymin = p_ll, ymax = p_ul),
fill = "firebrick", alpha = 1/5) +
geom_smooth(aes(ymin = f_ll, ymax = f_ul),
stat = "identity",
fill = "firebrick", color = "firebrick4", alpha = 1/5, size = 1/4) +
labs(subtitle = "Counterfactual plot for which\nMarriage_s = 0",
y = "Divorce") +
coord_cartesian(xlim = range(d$MedianAgeMarriage_s),
ylim = c(6, 14)) +
theme_bw() +
theme(panel.grid = element_blank())
```
> A tension with such plots, however, lies in their counterfactual nature. In the small world of the model, it is possible to change median age of marriage without also changing the marriage rate. But is this also possible in the large world of reality? Probably not...
>
> ...If our goal is to intervene in the world, there may not be any realistic way to manipulate each predictor without also manipulating the others. This is a serious obstacle to applied science, whether you are an ecologist, an economist, or an epidemiologist [or a psychologist] (p. 131)
#### Posterior prediction plots.
"In addition to understanding the estimates, it's important to check the model fit against the observed data" (p. 131). For more on the topic, check out Gabry and colleagues' [*Visualization in Bayesian workflow*](https://arxiv.org/abs/1709.01449) or Simpson's related blog post, [*Touch me, I want to feel your data*](https://statmodeling.stat.columbia.edu/2017/09/07/touch-want-feel-data/).
In this version of Figure 5.6.a, the thin lines are the 95% intervals and the thicker lines are $\pm$ the posterior $SD$, both of which are returned when you use `fitted()`.
```{r, fig.width = 3, fig.height = 3}
p1 <-
fitted(b5.3) %>%
as_tibble() %>%
bind_cols(d) %>%
ggplot(aes(x = Divorce, y = Estimate)) +
geom_abline(linetype = 2, color = "grey50", size = .5) +
geom_point(size = 1.5, color = "firebrick4", alpha = 3/4) +
geom_linerange(aes(ymin = Q2.5, ymax = Q97.5),
size = 1/4, color = "firebrick4") +
geom_linerange(aes(ymin = Estimate - Est.Error,
ymax = Estimate + Est.Error),
size = 1/2, color = "firebrick4") +
# Note our use of the dot placeholder, here: https://magrittr.tidyverse.org/reference/pipe.html
geom_text(data = . %>% filter(Loc %in% c("ID", "UT")),
aes(label = Loc),
hjust = 0, nudge_x = - 0.65) +
labs(x = "Observed divorce",
y = "Predicted divorce") +
theme_bw() +
theme(panel.grid = element_blank())
p1
```
In order to make Figure 5.6.b, we need to clarify the relationships among `fitted()`, `predict()`, and `residuals()`. Here's my attempt in a table.
```{r}
tibble(`brms function` = c("fitted", "predict", "residual"),
mean = c("same as the data", "same as the data", "in a deviance-score metric"),
scale = c("excludes sigma", "includes sigma", "excludes sigma")) %>%
knitr::kable()
```
Hopefully that clarified that if we want to incorporate the prediction interval in a deviance metric, we'll need to first use `predict()` and then subtract the intervals from their corresponding `Divorce` values in the data.
```{r, fig.width = 2.25, fig.height = 5.5}
p2 <-
residuals(b5.3) %>%
as_tibble() %>%
rename(f_ll = Q2.5,
f_ul = Q97.5) %>%
bind_cols(
predict(b5.3) %>%
as_tibble() %>%
transmute(p_ll = Q2.5,
p_ul = Q97.5),
d
) %>%
# here we put our `predict()` intervals into a deviance metric
mutate(p_ll = Divorce - p_ll,
p_ul = Divorce - p_ul) %>%
# now plot!
ggplot(aes(x = reorder(Loc, Estimate), y = Estimate)) +
geom_hline(yintercept = 0, size = 1/2,
color = "firebrick4", alpha = 1/10) +
geom_pointrange(aes(ymin = f_ll, ymax = f_ul),
size = 2/5, shape = 20, color = "firebrick4") +
geom_segment(aes(y = Estimate - Est.Error,
yend = Estimate + Est.Error,
x = Loc,
xend = Loc),
size = 1, color = "firebrick4") +
geom_segment(aes(y = p_ll, yend = p_ul,
x = Loc, xend = Loc),
size = 3, color = "firebrick4", alpha = 1/10) +
labs(x = NULL, y = NULL) +
coord_flip(ylim = c(-6, 5)) +
theme_bw() +
theme(axis.text.y = element_text(hjust = 0),
axis.ticks.y = element_blank(),
panel.grid = element_blank())
p2
```
Compared to the last couple plots, Figure 5.6.c is pretty simple.
```{r, warning = F, message = F, fig.width = 3, fig.height = 3}
p3 <-
residuals(b5.3) %>%
as_tibble() %>%
bind_cols(d) %>%
mutate(wpc = WaffleHouses / Population) %>%
ggplot(aes(x = wpc, y = Estimate)) +
geom_point(size = 1.5, color = "firebrick4", alpha = 1/2) +
stat_smooth(method = "lm", fullrange = T,
color = "firebrick4", size = 1/2,
fill = "firebrick", alpha = 1/5) +
geom_text_repel(data = . %>% filter(Loc %in% c("ME", "AR", "MS", "AL", "GA", "SC", "ID")),
aes(label = Loc),
seed = 5.6) +
scale_x_continuous("Waffles per capita", limits = c(0, 45)) +
ylab("Divorce error") +
coord_cartesian(xlim = range(0, 40)) +
theme_bw() +
theme(panel.grid = element_blank())
p3
```
For the sake of good practice, let’s use patchwork syntax to combine those three subplots like they appear in the text.
```{r, fig.width = 6.25, fig.height = 6.25}
library(patchwork)
((p1 / p3) | p2) + plot_annotation(tag_levels = "a",
tag_prefix = "(",
tag_suffix = ")")
```
More McElreath inspiration: "No matter how many predictors you've already included in a regression, it's still possible to find spurious correlations with the remaining variation" (p. 134).
##### Rethinking: Stats, huh, yeah what is it good for?
To keep our deflation train going, it's worthwhile repeating this message:
> Often people want statistical modeling to do things that statistical modeling cannot do. For example, we'd like to know whether an effect is real or rather spurious. Unfortunately, modeling merely quantifies uncertainty in the precise way that the model understands the problem. Usually answers to large world questions about truth and causation depend upon information not included in the model. For example, any observed correlation between an outcome and predictor could be eliminated or reversed once another predictor is added to the model. But if we cannot think of another predictor, we might never notice this. Therefore all statistical models are vulnerable to and demand critique, regardless of the precision of their estimates and apparent accuracy of their predictions. (p. 134)
##### Overthinking: Simulating spurious association.
Simulate the spurious predictor data.
```{r}
n <- 100 # number of cases
set.seed(5) # setting the seed makes the results reproducible
d <-
tibble(x_real = rnorm(n), # x_real as Gaussian with mean 0 and SD 1 (i.e., the defaults)
x_spur = rnorm(n, x_real), # x_spur as Gaussian with mean = x_real
y = rnorm(n, x_real)) # y as Gaussian with mean = x_real
```
Here are the quick `pairs()` plots.
```{r, fig.width = 4.5, fig.height = 4.5}
pairs(d, col = "firebrick4")
```
We may as well fit a model.
```{r b5.0_spur}
b5.0_spur <-
brm(data = d,
family = gaussian,
y ~ 1 + x_real + x_spur,
prior = c(prior(normal(0, 10), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 10), class = sigma)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5,
file = "fits/b05.00_spur")
```
```{r}
fixef(b5.0_spur) %>%
round(digits = 2)
```
## Masked relationship
> A second reason to use more than one predictor variable is to measure the direct influences of multiple factors on an outcome, when none of those influences is apparent from bivariate relationships. This kind of problem tends to arise when there are two predictor variables that are correlated with one another. However, one of these is positively correlated with the outcome and the other is negatively correlated with it. (p. 134)
Let's load the [Hindle and Milligan (2011)](https://www.researchgate.net/publication/51751742_Primate_milk_Proximate_mechanisms_and_ultimate_perspectives) `milk` data.
```{r, message = F}
library(rethinking)
data(milk)
d <- milk
```
Unload rethinking and load brms.
```{r, message = F, warning = F}
rm(milk)
detach(package:rethinking, unload = T)
library(brms)
```
You might inspect the data like this.
```{r, fig.width = 4.5, fig.height = 4.5}
d %>%
select(kcal.per.g, mass, neocortex.perc) %>%
pairs(col = "firebrick4")
```
By just looking at that mess, do you think you could describe the associations of `mass` and `neocortex.perc` with the criterion, `kcal.per.g`? I couldn't. It's a good thing we have math.
McElreath has us start of with a simple univariable `milk` model.
```{r b5.5}
b5.5 <-
brm(data = d,
family = gaussian,
kcal.per.g ~ 1 + neocortex.perc,
prior = c(prior(normal(0, 100), class = Intercept),
prior(normal(0, 1), class = b),
prior(cauchy(0, 1), class = sigma)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
seed = 5,
file = "fits/b05.05")
```
The uniform prior was difficult on Stan. After playing around a bit, I just switched to a unit-scale half Cauchy. Similar to the rethinking example in the text, brms warned that "Rows containing NAs were excluded from the model." This isn't necessarily a problem; the model fit just fine. But we should be ashamed of ourselves and look eagerly forward to [Chapter 14][Missing Data and Other Opportunities] where we'll learn how to do better.
To compliment how McElreath removed cases with missing values on our variables of interest with base R `complete.cases()`, here we'll do so with `tidyr::drop_na()` and a little help with `ends_with()`.
```{r}
dcc <-
d %>%
drop_na(ends_with("_s"))
```
But anyway, let's inspect the parameter summary.
```{r}
print(b5.5, digits = 3)
```
Did you notice now we set `digits = 3` within `print()` much the way McElreath set `digits=3` within `precis()`?
To get the brms answer to what McElreath did with `coef()`, we can use the `fixef()` function.
```{r, warning = F, message = F}
fixef(b5.5)[2] * (76 - 55)
```
Yes, indeed, "that's less than 0.1 kilocalories" (p. 137).
Just for kicks, we'll superimpose 50% intervals atop 95% intervals for the next few plots. Here's Figure 5.7, top left.
```{r, fig.width = 3, fig.height = 2.75, message = F}
nd <- tibble(neocortex.perc = 54:80)
fitted(b5.5,
newdata = nd,
probs = c(.025, .975, .25, .75)) %>%
as_tibble() %>%
bind_cols(nd) %>%
ggplot(aes(x = neocortex.perc, y = Estimate)) +
geom_ribbon(aes(ymin = Q2.5, ymax = Q97.5),
fill = "firebrick", alpha = 1/5) +
geom_smooth(aes(ymin = Q25, ymax = Q75),
stat = "identity",
fill = "firebrick4", color = "firebrick4", alpha = 1/5, size = 1/2) +
geom_point(data = dcc,
aes(y = kcal.per.g),
size = 2, color = "firebrick4") +
ylab("kcal.per.g") +
coord_cartesian(xlim = range(dcc$neocortex.perc),
ylim = range(dcc$kcal.per.g)) +
theme_bw() +
theme(panel.grid = element_blank())
```
Do note the `probs` argument in the `fitted()` code, above. Let's make the `log_mass` variable.
```{r}
dcc <-
dcc %>%
mutate(log_mass = log(mass))
```
Now we use `log_mass` as the new sole predictor.
```{r b5.6}
b5.6 <-
brm(data = dcc,
family = gaussian,
kcal.per.g ~ 1 + log_mass,
prior = c(prior(normal(0, 100), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 1), class = sigma)),
iter = 2000, warmup = 500, chains = 4, cores = 4,
control = list(adapt_delta = 0.9),
seed = 5,
file = "fits/b05.06")
```
```{r}
print(b5.6, digits = 3)
```
Make Figure 5.7, top right.
```{r, fig.width = 3, fig.height = 2.75, warning = F, message = F}
nd <- tibble(log_mass = seq(from = -2.5, to = 5, length.out = 30))
fitted(b5.6,
newdata = nd,
probs = c(.025, .975, .25, .75)) %>%
as_tibble() %>%
bind_cols(nd) %>%
ggplot(aes(x = log_mass, y = Estimate)) +
geom_ribbon(aes(ymin = Q2.5, ymax = Q97.5),
fill = "firebrick", alpha = 1/5) +
geom_smooth(aes(ymin = Q25, ymax = Q75),
stat = "identity",
fill = "firebrick4", color = "firebrick4", alpha = 1/5, size = 1/2) +
geom_point(data = dcc,
aes(y = kcal.per.g),
size = 2, color = "firebrick4") +
ylab("kcal.per.g") +
coord_cartesian(xlim = range(dcc$log_mass),
ylim = range(dcc$kcal.per.g)) +
theme_bw() +
theme(panel.grid = element_blank())
```
Finally, we're ready to fit with both predictors included in the "joint model." Here's the statistical formula:
\begin{align*}
\text{kcal.per.g}_i & \sim \operatorname{Normal}(\mu_i, \sigma) \\
\mu_i & = \alpha + \beta_1 \text{neocortex.perc}_i + \beta_2 \log (\text{mass}_i) \\
\alpha & \sim \operatorname{Normal}(0, 100) \\
\beta_1 & \sim \operatorname{Normal}(0, 1) \\
\beta_2 & \sim \operatorname{Normal}(0, 1) \\
\sigma & \sim \operatorname{Uniform}(0, 1).
\end{align*}
Note, the HMC chains required a longer `warmup` period and a higher `adapt_delta` setting for the model to converge properly. Life will be much better once we ditch the uniform prior for good.
```{r b5.7}
b5.7 <-
brm(data = dcc,
family = gaussian,
kcal.per.g ~ 1 + neocortex.perc + log_mass,
prior = c(prior(normal(0, 100), class = Intercept),
prior(normal(0, 1), class = b),
prior(uniform(0, 1), class = sigma)),
iter = 4000, warmup = 2000, chains = 4, cores = 4,
control = list(adapt_delta = 0.999),
seed = 5,
file = "fits/b05.07")
```
```{r}
print(b5.7, digits = 3)
```
Make Figure 5.7, bottom left.
```{r, fig.width = 3, fig.height = 2.5, warning = F, message = F}
nd <-
tibble(neocortex.perc = 54:80 %>% as.double(),
log_mass = mean(dcc$log_mass))
p1 <-
b5.7 %>%
fitted(newdata = nd,
probs = c(.025, .975, .25, .75)) %>%
as_tibble() %>%
bind_cols(nd) %>%
ggplot(aes(x = neocortex.perc, y = Estimate)) +
geom_ribbon(aes(ymin = Q2.5, ymax = Q97.5),
fill = "firebrick", alpha = 1/5) +
geom_smooth(aes(ymin = Q25, ymax = Q75),
stat = "identity",
fill = "firebrick4", color = "firebrick4", alpha = 1/5, size = 1/2) +
geom_point(data = dcc,
aes(y = kcal.per.g),
size = 2, color = "firebrick4") +
ylab("kcal.per.g") +
coord_cartesian(xlim = range(dcc$neocortex.perc),
ylim = range(dcc$kcal.per.g))
```
Now make Figure 5.7, bottom right, and combine.
```{r, fig.width = 6, fig.height = 2.75, warning = F, message = F}
nd <-
tibble(log_mass = seq(from = -2.5, to = 5, length.out = 30),
neocortex.perc = mean(dcc$neocortex.perc))
p2 <-
b5.7 %>%
fitted(newdata = nd,
probs = c(.025, .975, .25, .75)) %>%
as_tibble() %>%
bind_cols(nd) %>%
ggplot(aes(x = log_mass, y = Estimate)) +
geom_ribbon(aes(ymin = Q2.5, ymax = Q97.5),
fill = "firebrick", alpha = 1/5) +
geom_smooth(aes(ymin = Q25, ymax = Q75),
stat = "identity",
fill = "firebrick4", color = "firebrick4", alpha = 1/5, size = 1/2) +
geom_point(data = dcc,
aes(y = kcal.per.g),
size = 2, color = "firebrick4") +
ylab("kcal.per.g") +
coord_cartesian(xlim = range(dcc$log_mass),
ylim = range(dcc$kcal.per.g))
(p1 | p2) &
theme_bw() &
theme(panel.grid = element_blank())
```
> What [this regression model did was] ask if species that have high neocortex percent *for their body mass* have higher milk energy. Likewise, the model [asked] if species with high body mass *for their neocortex percent* have higher milk energy. Bigger species, like apes, have milk with less energy. But species with more neocortex tend to have richer milk. The fact that these two variables, body size and neocortex, are correlated across species makes it hard to see these relationships, unless we statistically account for both. (pp. 140--141, *emphasis* in the original)
#### Overthinking: Simulating a masking relationship.
Simulate the data.
```{r}
n <- 100 # number of cases
rho <- .7 # correlation between x_pos and x_neg
set.seed(5) # setting the seed makes the results reproducible
d <-
tibble(x_pos = rnorm(n), # x_pos as a standard Gaussian
x_neg = rnorm(n, rho * x_pos, sqrt(1 - rho^2)), # x_neg correlated with x_pos
y = rnorm(n, x_pos - x_neg)) # y equally associated with x_pos and x_neg
```
Here are the quick `pairs()` plots.
```{r, fig.width = 4.5, fig.height = 4.5}
pairs(d, col = "firebrick4")
```
Here we fit the models with a little help from the `update()` function.
```{r b5.0_both}
b5.0_both <-
brm(data = d, family = gaussian,
y ~ 1 + x_pos + x_neg,
prior = c(prior(normal(0, 100), class = Intercept),
prior(normal(0, 1), class = b),
prior(cauchy(0, 1), class = sigma)),
seed = 5,
file = "fits/b05.00_both")
b5.0_pos <-
update(b5.0_both,
formula = y ~ 1 + x_pos,
seed = 5,
file = "fits/b05.00_pos")
b5.0_neg <-
update(b5.0_both,
formula = y ~ 1 + x_neg,
seed = 5,
file = "fits/b05.00_neg")
```
Compare the coefficients.
```{r}
fixef(b5.0_pos) %>% round(digits = 2)
fixef(b5.0_neg) %>% round(digits = 2)