-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path21.Rmd
1842 lines (1483 loc) · 69.4 KB
/
21.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
```{r, echo = FALSE, cache = FALSE}
knitr::opts_chunk$set(fig.retina = 2.5)
knitr::opts_chunk$set(fig.align = "center")
options(width = 100)
```
# Dichotomous Predicted Variable
> This chapter considers data structures that consist of a dichotomous predicted variable. The early chapters of the book were focused on this type of data, but now we reframe the analyses in terms of the generalized linear model...
>
> The traditional treatment of these sorts of data structure is called "logistic regression." In Bayesian software it is easy to generalize the traditional models so they are robust to outliers, allow different variances within levels of a nominal predictor, and have hierarchical structure to share information across levels or factors as appropriate. [@kruschkeDoingBayesianData2015, pp. 621--622]
## Multiple metric predictors
"We begin by considering a situation with multiple metric predictors, because this case makes it easiest to visualize the concepts of logistic regression" (p. 623).
The 3D wireframe plot in Figure 21.1 is technically beyond the scope of our current **ggplot2** paradigm. But we will discuss an alternative in the end of [Section 21.1.2][Example: Height, weight, and gender.].
### The model and implementation in ~~JAGS~~ brms.
Our statistical model will follow the form
\begin{align*}
\mu & = \operatorname{logistic}(\beta_0 + \beta_1 x_1 + \beta_2 x_2) \\
y & \sim \operatorname{Bernoulli}(\mu)
\end{align*}
where
$$\operatorname{logistic}(x) = \frac{1}{[1 + \exp (-x)]}.$$
The generic **brms** code for logistic regression using the Bernoulli likelihood looks like so.
```{r, eval = F}
fit <-
brm(data = my_data,
family = bernoulli,
y ~ 1 + x1 + x2,
prior = c(prior(normal(0, 2), class = Intercept),
prior(normal(0, 2), class = b)))
```
Note that this syntax presumes the predictor variables have already been standardized.
We'd be remiss not to point out that you can also specify the model using the binomial distribution. That code would look like this.
```{r, eval = F}
fit <-
brm(data = my_data,
family = binomial,
y | trials(1) ~ 1 + x1 + x2,
prior = c(prior(normal(0, 2), class = Intercept),
prior(normal(0, 2), class = b)))
```
As long as the data are not aggregated, the results of these two should be the same within simulation variance. In **brms**, the default link for both `family = bernoulli` and `family = binomial` models is `logit`, which is exactly what we want, here. Also, note the additional `| trials(1) ` syntax on the left side of the model formula. You could get away with omitting this in older versions of **brms**. But newer versions prompt users to specify how many of trials each row in the data represents. This is because, as with the baseball data we'll use later in the chapter, the binomial distribution includes an $n$ parameter. When working with un-aggregated data like what we’re about to do, below, it's presumed that $n = 1$.
We won't be making our version of Figure 21.1 until a little later in the chapter. However, we can go ahead and make our version of the model diagram in Kruschke's Figure 21.2. Before we do, let's discuss the issues of plot colors and theme. For this chapter, we'll take our color palette from the [**PNWColors** package](https://CRAN.R-project.org/package=PNWColors) [@R-PNWColors], which provides color palettes inspired by the beauty of my birthplace,the US Pacific Northwest. Our color palette will be `"Mushroom"`.
```{r, warning = F, message = F, fig.width = 4, fig.height = 1}
library(PNWColors)
pm <- pnw_palette(name = "Mushroom", n = 8)
pm
```
Our overall plot theme will be a `"Mushroom"` infused extension of `theme_linedraw()`.
```{r, warning = F, message = F}
library(tidyverse)
theme_set(
theme_linedraw() +
theme(text = element_text(color = pm[1]),
axis.text = element_text(color = pm[1]),
axis.ticks = element_line(color = pm[1]),
legend.background = element_blank(),
legend.box.background = element_blank(),
legend.key = element_rect(fill = pm[8]),
panel.background = element_rect(fill = pm[8], color = pm[8]),
panel.border = element_rect(colour = pm[1]),
panel.grid = element_blank(),
strip.background = element_rect(fill = pm[1], color = pm[1]),
strip.text = element_text(color = pm[8]))
)
```
Now make Figure 21.2.
```{r, fig.width = 4, fig.height = 4.25, warning = F, message = F}
library(patchwork)
# normal density
p1 <-
tibble(x = seq(from = -3, to = 3, by = .1)) %>%
ggplot(aes(x = x, y = (dnorm(x)) / max(dnorm(x)))) +
geom_area(fill = pm[5]) +
annotate(geom = "text",
x = 0, y = .2,
label = "normal",
size = 7, color = pm[1]) +
annotate(geom = "text",
x = c(0, 1.5), y = .6,
label = c("italic(M)[0]", "italic(S)[0]"),
size = 7, color = pm[1], hjust = 0, family = "Times", parse = T) +
scale_x_continuous(expand = c(0, 0)) +
theme_void() +
theme(axis.line.x = element_line(size = 0.5),
plot.background = element_rect(fill = pm[8], color = "white", size = 1))
# second normal density
p2 <-
tibble(x = seq(from = -3, to = 3, by = .1)) %>%
ggplot(aes(x = x, y = (dnorm(x)) / max(dnorm(x)))) +
geom_area(fill = pm[5]) +
annotate(geom = "text",
x = 0, y = .2,
label = "normal",
size = 7, color = pm[1]) +
annotate(geom = "text",
x = c(0, 1.5), y = .6,
label = c("italic(M[j])", "italic(S[j])"),
size = 7, color = pm[1], hjust = 0, family = "Times", parse = T) +
scale_x_continuous(expand = c(0, 0)) +
theme_void() +
theme(axis.line.x = element_line(size = 0.5),
plot.background = element_rect(fill = pm[8], color = "white", size = 1))
## an annotated arrow
# save our custom arrow settings
my_arrow <- arrow(angle = 20, length = unit(0.35, "cm"), type = "closed")
p3 <-
tibble(x = .5,
y = 1,
xend = .85,
yend = 0) %>%
ggplot(aes(x = x, xend = xend,
y = y, yend = yend)) +
geom_segment(arrow = my_arrow, color = pm[1]) +
annotate(geom = "text",
x = .55, y = .4,
label = "'~'",
size = 10, color = pm[1], family = "Times", parse = T) +
xlim(0, 1) +
theme_void()
## another annotated arrow
p4 <-
tibble(x = .5,
y = 1,
xend = 1/3,
yend = 0) %>%
ggplot(aes(x = x, xend = xend,
y = y, yend = yend)) +
geom_segment(arrow = my_arrow, color = pm[1]) +
annotate(geom = "text",
x = c(.3, .48), y = .4,
label = c("'~'", "italic(j)"),
size = c(10, 7), color = pm[1], family = "Times", parse = T) +
xlim(0, 1) +
theme_void()
# likelihood formula
p5 <-
tibble(x = .5,
y = .5,
label = "logistic(beta[0]+sum()[italic(j)]~beta[italic(j)]~italic(x)[italic(ji)])") %>%
ggplot(aes(x = x, y = y, label = label)) +
geom_text(size = 7, color = pm[1], parse = T, family = "Times") +
scale_x_continuous(expand = c(0, 0), limits = c(0, 1)) +
ylim(0, 1) +
theme_void()
# a third annotated arrow
p6 <-
tibble(x = c(.375, .6),
y = c(1/2, 1/2),
label = c("'='", "italic(i)")) %>%
ggplot(aes(x = x, y = y, label = label)) +
geom_text(size = c(10, 7), color = pm[1], parse = T, family = "Times") +
geom_segment(x = .5, xend = .5,
y = 1, yend = 0,
arrow = my_arrow) +
xlim(0, 1) +
theme_void()
# bar plot of Bernoulli data
p7 <-
tibble(x = 0:1,
d = (dbinom(x, size = 1, prob = .6)) / max(dbinom(x, size = 1, prob = .6))) %>%
ggplot(aes(x = x, y = d)) +
geom_col(fill = pm[5], width = .4) +
annotate(geom = "text",
x = .5, y = .2,
label = "Bernoulli",
size = 7, color = pm[1]) +
annotate(geom = "text",
x = .5, y = .94,
label = "mu[italic(i)]",
size = 7, color = pm[1], family = "Times", parse = T) +
xlim(-.75, 1.75) +
theme_void() +
theme(axis.line.x = element_line(size = 0.5),
plot.background = element_rect(fill = pm[8], color = pm[8]))
# the final annotated arrow
p8 <-
tibble(x = c(.375, .625),
y = c(1/3, 1/3),
label = c("'~'", "italic(i)")) %>%
ggplot(aes(x = x, y = y, label = label)) +
geom_text(size = c(10, 7), color = pm[1], parse = T, family = "Times") +
geom_segment(x = .5, xend = .5,
y = 1, yend = 0,
color = pm[1], arrow = my_arrow) +
xlim(0, 1) +
theme_void()
# some text
p9 <-
tibble(x = 1,
y = .5,
label = "italic(y[i])") %>%
ggplot(aes(x = x, y = y, label = label)) +
geom_text(size = 7, color = pm[1], parse = T, family = "Times") +
xlim(0, 2) +
theme_void()
# define the layout
layout <- c(
area(t = 1, b = 2, l = 1, r = 2),
area(t = 1, b = 2, l = 3, r = 4),
area(t = 3, b = 3, l = 1, r = 2),
area(t = 3, b = 3, l = 3, r = 4),
area(t = 4, b = 4, l = 1, r = 4),
area(t = 5, b = 5, l = 2, r = 3),
area(t = 6, b = 7, l = 2, r = 3),
area(t = 8, b = 8, l = 2, r = 3),
area(t = 9, b = 9, l = 2, r = 3)
)
# combine and plot!
(p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9) +
plot_layout(design = layout) &
ylim(0, 1) &
theme(plot.margin = margin(0, 5.5, 0, 5.5))
```
### Example: Height, weight, and gender.
Load the height/weight data.
```{r, warning = F, message = F}
library(tidyverse)
my_data <- read_csv("data.R/HtWtData110.csv")
glimpse(my_data)
```
Let's standardize our predictors.
```{r}
my_data <-
my_data %>%
mutate(height_z = (height - mean(height)) / sd(height),
weight_z = (weight - mean(weight)) / sd(weight))
```
Before we fit a model, we might take a quick look at the data to explore the relations among the continuous variables `weight` and `height` and the dummy variable `male`. The `ggMarginal()` function from the [**ggExtra** package](https://github.com/daattali/ggExtra) [@R-ggExtra] will help us get a sense of the multivariate distribution by allowing us to add marginal densities to a scatter plot.
```{r, fig.width = 4.25, fig.height = 4}
library(ggExtra)
p <-
my_data %>%
ggplot(aes(x = weight, y = height, fill = male == 1)) +
geom_point(aes(color = male == 1),
alpha = 3/4) +
scale_color_manual(values = pm[c(3, 6)]) +
scale_fill_manual(values = pm[c(3, 6)]) +
theme(legend.position = "none")
p %>%
ggMarginal(data = my_data,
colour = pm[1],
groupFill = T,
alpha = .8,
type = "density")
```
Looks like the data for which `male == 1` are concentrated in the upper right and those for which `male == 0` are more so in the lower left. What we'd like is a model that would tell us the optimal dividing line(s) between our `male` categories with respect to those predictor variables.
Open **brms**.
```{r, warning = F, message = F}
library(brms)
```
Our first logistic model with `family = bernoulli` uses only `weight_z` as a predictor.
```{r fit21.1}
fit21.1 <-
brm(data = my_data,
family = bernoulli,
male ~ 1 + weight_z,
prior = c(prior(normal(0, 2), class = Intercept),
prior(normal(0, 2), class = b)),
iter = 2500, warmup = 500, chains = 4, cores = 4,
seed = 21,
file = "fits/fit21.01")
```
Here's the model summary.
```{r}
print(fit21.1)
```
Now let's get ready to make our version of Figure 21.3. First, we extract the posterior draws.
```{r}
draws <- as_draws_df(fit21.1)
```
Now we wrangle a bit to make the top panel of Figure 21.3.
```{r, fig.width = 4.5, fig.height = 3.75}
length <- 200
n_draw <- 20
draws %>%
tibble() %>%
# take 20 random samples of the posterior draws
slice_sample(n = n_draw) %>%
# add in a sequence of weight_z
expand(nesting(.draw, b_Intercept, b_weight_z),
weight_z = seq(from = -2, to = 3.5, length.out = length)) %>%
# compute the estimates of interest
mutate(male = inv_logit_scaled(b_Intercept + b_weight_z * weight_z),
weight = weight_z * sd(my_data$weight) + mean(my_data$weight),
thresh = -b_Intercept / b_weight_z * sd(my_data$weight) + mean(my_data$weight)) %>%
# plot!
ggplot(aes(x = weight)) +
geom_hline(yintercept = .5, color = pm[7], size = 1/2) +
geom_vline(aes(xintercept = thresh, group = .draw),
color = pm[6], size = 2/5, linetype = 2) +
geom_line(aes(y = male, group = .draw),
color = pm[1], size = 1/3, alpha = 2/3) +
geom_point(data = my_data,
aes(y = male),
alpha = 1/3, color = pm[1]) +
labs(title = "Data with Post. Pred.",
y = "male") +
coord_cartesian(xlim = range(my_data$weight))
```
We should discuss those thresholds (i.e., the vertical lines) a bit. Kruschke:
> The spread of the logistic curves indicates the uncertainty of the estimate; the steepness of the logistic curves indicates the magnitude of the regression coefficient. The $50\%$ probability threshold is marked by arrows that drop down from the logistic curve to the $x$-axis, near a weight of approximately $160$ pounds. The threshold is the $x$ value at which $\mu = 0.5$, which is $x = -\beta_0 / \beta_1$. (p. 626)
It's important to realize that when you compute the thresholds with $-\beta_0 / \beta_1$, this returns the values *on the scale of the predictor*. In our case, the predictor was `weight_z`. But since we wanted to plot the data on the scale of the unstandardized variable, `weight`, we have to convert the thresholds to that metric by multiplying their values by $s_\text{weight}$ and then add the product to $\overline{\text{weight}}$. If you study it closely, you'll see that's what we did when computing the `thresh` values, above.
Now here we show the marginal distributions in our versions of the lower panels of Figure 21.3.
```{r, fig.width = 6, fig.height = 2.5, warning = F, message = F}
library(tidybayes)
draws <-
draws %>%
# convert the parameter draws to their natural metric following Equation 21.1 (pp. 624--625)
transmute(Intercept = b_Intercept - (b_weight_z * mean(my_data$weight) / sd(my_data$weight)),
weight = b_weight_z / sd(my_data$weight)) %>%
pivot_longer(everything())
# plot
draws %>%
ggplot(aes(x = value, y = 0)) +
stat_halfeye(point_interval = mode_hdi, .width = .95,
shape = 15, point_size = 2.5, point_color = pm[4],
slab_color = pm[1], fill = pm[7], color = pm[1],
slab_size = 1/2, size = 2, normalize = "panels") +
scale_y_continuous(NULL, breaks = NULL) +
xlab(NULL) +
facet_wrap(~ name, scales = "free", ncol = 2)
```
And here are those exact posterior mode and 95% HDI values.
```{r}
draws %>%
group_by(name) %>%
mode_hdi() %>%
mutate_if(is.double, round, digits = 3)
```
If you look back at our code for the lower marginal plots for Figure 21.3, you'll notice we did a whole lot of argument tweaking within `tidybayes::stat_halfeye()`. We have a lot of marginal densities ahead of us in this chapter, so we might streamline our code with those settings saved in a custom function. As the vibe I'm going for in those settings is based on some of the plots in [Chapter 16](https://clauswilke.com/dataviz/visualizing-uncertainty.html) of Wilke's [-@wilkeFundamentalsDataVisualization2019], *Fundamentals of data visualization*, we'll call our function `stat_wilke()`.
```{r}
stat_wilke <- function(.width = .95,
shape = 15, point_size = 2.5, point_color = pm[4],
slab_color = pm[1], fill = pm[7], color = pm[1],
slab_size = 1/2, size = 2, ...) {
stat_halfeye(point_interval = mode_hdi, .width = .width,
shape = shape, point_size = point_size, point_color = point_color,
slab_color = slab_color, fill = fill, color = color,
slab_size = slab_size, size = size,
normalize = "panels",
...)
}
```
Now fit the two-predictor model using both `weight_z` and `height_z`.
```{r fit21.2}
fit21.2 <-
brm(data = my_data,
family = bernoulli,
male ~ 1 + weight_z + height_z,
prior = c(prior(normal(0, 2), class = Intercept),
prior(normal(0, 2), class = b)),
iter = 2500, warmup = 500, chains = 4, cores = 4,
seed = 21,
file = "fits/fit21.02")
```
Here's the model summary.
```{r}
print(fit21.2)
```
Before we make our plots for Figure 21.4, we'll need to extract the posterior samples and transform a little.
```{r, warning = F}
draws <-
as_draws_df(fit21.2) %>%
mutate(b_weight = b_weight_z / sd(my_data$weight),
b_height = b_height_z / sd(my_data$height),
Intercept = b_Intercept - ((b_weight_z * mean(my_data$weight) / sd(my_data$weight)) +
(b_height_z * mean(my_data$height) / sd(my_data$height)))) %>%
select(.draw, b_weight:Intercept)
head(draws)
```
Here's our version of Figure 21.4.a.
```{r, fig.width = 4.25, fig.height = 4}
set.seed(21) # we need this for the `slice_sample()` function
draws %>%
slice_sample(n = 20) %>%
expand(nesting(.draw, Intercept, b_weight, b_height),
weight = c(80, 280)) %>%
# this follows the Equation near the top of p. 629
mutate(height = (-Intercept / b_height) + (-b_weight / b_height) * weight) %>%
# now plot
ggplot(aes(x = weight, y = height)) +
geom_line(aes(group = .draw),
color = pm[7], size = 2/5, alpha = 2/3) +
geom_text(data = my_data,
aes(label = male, color = male == 1)) +
scale_color_manual(values = pm[c(4, 1)]) +
ggtitle("Data with Post. Pred.") +
coord_cartesian(xlim = range(my_data$weight),
ylim = range(my_data$height)) +
theme(legend.position = "none")
```
With just a tiny bit more wrangling, we'll be ready to make the bottom panels of Figure 21.4.
```{r, fig.width = 8, fig.height = 2.5, warning = F, message = F}
draws %>%
pivot_longer(-.draw) %>%
mutate(name = factor(str_remove(name, "b_"),
levels = c("Intercept", "weight", "height"))) %>%
ggplot(aes(x = value, y = 0)) +
stat_wilke() +
scale_y_continuous(NULL, breaks = NULL) +
xlab(NULL) +
facet_wrap(~ name, scales = "free", ncol = 3)
```
Did you notice our use of `stat_wilke()`? By now, you know how to use `mode_hdi()` to return those exact summary values if you'd like them.
Now remember how we backed away from Figure 21.1? Well, when you have a logistic regression with two predictors, there is a reasonable way to express those three dimensions on a two-dimensional grid. Now we have the results from `fit21.2`, let's try it out.
First, we need a grid of values for our two predictors, `weight_z` and `height_z`.
```{r}
length <- 100
nd <-
crossing(weight_z = seq(from = -3.5, to = 3.5, length.out = length),
height_z = seq(from = -3.5, to = 3.5, length.out = length))
```
Second, we plug those values into `fitted()` and wrangle.
```{r}
f <-
fitted(fit21.2,
newdata = nd,
scale = "linear") %>%
as_tibble() %>%
# note we're only working with the posterior mean, here
transmute(prob = Estimate %>% inv_logit_scaled()) %>%
bind_cols(nd) %>%
mutate(weight = (weight_z * sd(my_data$weight) + mean(my_data$weight)),
height = (height_z * sd(my_data$height) + mean(my_data$height)))
glimpse(f)
```
Third, we're ready to plot. Here we'll express the third dimension, probability, on a color spectrum.
```{r, fig.width = 4.75, fig.height = 4}
f %>%
ggplot(aes(x = weight, y = height)) +
geom_raster(aes(fill = prob),
interpolate = T) +
geom_text(data = my_data,
aes(label = male, color = male == 1),
show.legend = F) +
scale_color_manual(values = pm[c(8, 1)]) +
scale_fill_gradientn(colours = pnw_palette(name = "Mushroom", n = 101),
limits = c(0, 1)) +
scale_y_continuous(position = "right") +
coord_cartesian(xlim = range(my_data$weight),
ylim = range(my_data$height)) +
theme(legend.position = "left")
```
If you look way back to Figure 21.1 (p. 623), you'll see the following formula at the top:
$$y \sim \operatorname{dbern}(m), m = \operatorname{logistic}(0.018 x_1 + 0.7 x_2 - 50).$$
Now while you keep your finger on that equation, take another look at the last line in Kruschke's Equation 21.1,
$$
\operatorname{logit}(\mu) =
\underbrace{\zeta_0 - \sum_j \frac{\zeta_j}{s_{x_j}} \overline x_j}_{\beta_0} +
\sum_j \underbrace{\frac{\zeta_j}{s_{x_j}} \overline x_j}_{\beta_j},
$$
where the $\zeta$'s are the parameters from the model based on standardized predictors. Our `fit21.2` was based on standardized `weight` and `height` values (i.e., `weight_z` and `height_z`), yielding model coefficients in the $\zeta$ metric. Here we use the formula above to convert our `fit21.2` estimates to their unstandardized $\beta$ metric. For simplicity, we'll just take their means.
```{r, warning = F}
as_draws_df(fit21.2) %>%
transmute(beta_0 = b_Intercept - ((b_weight_z * mean(my_data$weight) / sd(my_data$weight)) +
((b_height_z * mean(my_data$height) / sd(my_data$height)))),
beta_1 = b_weight_z / sd(my_data$weight),
beta_2 = b_height_z / sd(my_data$height)) %>%
summarise_all(~ mean(.) %>% round(., digits = 3))
```
Within rounding error, those values are the same ones in the formula at the top of Kruschke's Figure 21.1! That is, our last plot was a version of Figure 21.1.
Hopefully this helps make sense of what the thresholds in Figure 21.4.a represented. But do note a major limitation of this visualization approach. By expressing the threshold with multiple lines drawn from the posterior in Figure 21.4.a, we expressed the uncertainty inherent in the posterior distribution. However, for this probability plane approach, we've taken a single value from the posterior, the mean (i.e., the `Estimate`), to compute the probabilities. Though beautiful, our probability-plane plot does a poor job expressing the uncertainty in the model. If you're curious how one might include uncertainty into a plot like this, check out the intriguing blog post by Adam Pearce, [*Communicating model uncertainty over space*](https://pair-code.github.io/interpretability/uncertainty-over-space/).
## Interpreting the regression coefficients
> In this section, I'll discuss how to interpret the parameters in logistic regression. The first subsection explains how to interpret the numerical magnitude of the slope coefficients in terms of "log odds." The next subsection shows how data with relatively few $1$'s or $0$'s can yield ambiguity in the parameter estimates. Then an example with strongly correlated predictors reveals tradeoffs in slope coefficients. Finally, I briefly describe the meaning of multiplicative interaction for logistic regression. (p. 629)
### Log odds.
> When the logistic regression formula is written using the logit function, we have $\operatorname{logit}(\mu) = \beta_0 + \beta_1 x_1 + \beta_2 x_2$. The formula implies that whenever $x_1$ goes up by $1$ unit (on the $x_1$ scale), then $\operatorname{logit}(\mu)$ goes up by an amount $\beta_1$. And whenever $x_2$ goes up by $1$ unit (on the $x_2$ scale), then $\operatorname{logit}(\mu)$ goes up by an amount $\beta_2$. Thus, the regression coefficients are telling us about increases in $\operatorname{logit}(\mu)$. To understand the regression coefficients, we need to understand $\operatorname{logit}(\mu)$. (pp. 629--630)
Given the logit function is the inverse of the logistic, which itself is
$$\operatorname{logistic}(x) = \frac{1}{1 + \exp (−x)},$$
and given the formula
$$\operatorname{logit}(\mu) = \log \left (\frac{\mu}{1 - \mu} \right),$$
where
$$0 < \mu < 1,$$
it may or may not be clear that the results of our logistic regression models have a nonlinear relation with the actual parameter of interest, $\mu$, which, recall, is the probability our criterion variable is 1 (e.g., `male == 1`). To get a sense of that nonlinear relation, we might make a plot.
```{r, fig.width = 3.25, fig.height = 3}
tibble(mu = seq(from = 0, to = 1, length.out = 300)) %>%
mutate(logit_mu = log(mu / (1 - mu))) %>%
ggplot(aes(x = mu, y = logit_mu)) +
geom_line(color = pm[3], size = 1.5) +
labs(x = expression(mu~"(i.e., the probability space)"),
y = expression(logit~mu~"(i.e., the parameter space)")) +
theme(legend.position = "none")
```
So whereas our probability space is bound between 0 and 1, the parameter space shoots off into negative and positive infinity. Also,
$$\operatorname{logit}(\mu) = \log \left (\frac{p(y = 1)}{p(y = 0)} \right ).$$
Thus, "the ratio, $p(y = 1) / p(y = 0)$, is called the odds of outcome 1 to outcome 0, and therefore $\operatorname{logit}(\mu)$ is the log odds of outcome 1 to outcome 0" (p. 630).
Here's a table layout of the height/weight examples in the middle of page 630.
```{r}
tibble(b0 = -50,
b1 = .02,
b2 = .7,
weight = 160,
inches = c(63:64, 67:68)) %>%
mutate(logit_mu = b0 + b1 * weight + b2 * inches) %>%
mutate(log_odds = logit_mu) %>%
mutate(p_male = 1 / (1 + exp(-log_odds))) %>%
knitr::kable()
```
> Thus, a regression coefficient in logistic regression indicates how much a $1$ unit change of the predictor increases the log odds of outcome $1$. A regression coefficient of $0.5$ corresponds to a rate of probability change of about $12.5$ percentage points per $x$-unit at the threshold $x$ value. A regression coefficient of $1.0$ corresponds to a rate of probability change of about $24.4$ percentage points per $x$-unit at the threshold $x$ value. When $x$ is much larger or smaller than the threshold $x$ value, the rate of change in probability is smaller, even though the rate of change in log odds is constant. (pp. 630--631)
### When there are few 1's or 0's in the data.
> In logistic regression, you can think of the parameters as describing the boundary between the $0$'s and the $1$'s. If there are many $0$'s and $1$'s, then the estimate of the boundary parameters can be fairly accurate. But if there are few $0$'s or few $1$'s, the boundary can be difficult to identify very accurately, even if there are many data points overall. (p. 631)
As far as I can tell, Kruschke must have used $n = 500$ to simulate the data he displayed in Figure 21.5. Using the coefficient values he displayed in the middle of page 631, here's an attempt at replicating them.
```{r}
b0 <- -3
b1 <- 1
n <- 500
set.seed(21)
d_rare <-
tibble(x = rnorm(n, mean = 0, sd = 1)) %>%
mutate(mu = b0 + b1 * x) %>%
mutate(y = rbinom(n, size = 1, prob = 1 / (1 + exp(-mu))))
glimpse(d_rare)
```
We're ready to fit the model. So far, we've been following along with Kruschke by using the Bernoulli distribution (i.e., `family = bernoulli`) in our **brms** models. Let's get frisky and use the $n = 1$ binomial distribution, here. You'll see it yields the same results.
```{r fit21.3}
fit21.3 <-
brm(data = d_rare,
family = binomial,
y | trials(1) ~ 1 + x,
prior = c(prior(normal(0, 2), class = Intercept),
prior(normal(0, 2), class = b)),
iter = 2500, warmup = 500, chains = 4, cores = 4,
seed = 21,
file = "fits/fit21.03")
```
Recall that when you use the binomial distribution in newer versions of **brms**, you need to use the `trials()` syntax to tell `brm()` how many trials each row in the data corresponds to. Anyway, behold the summary.
```{r}
print(fit21.3)
```
Looks like the model did a good job recapturing those data-generating `b0` and `b1` values. Now make the top left panel of Figure 21.5.
```{r, fig.width = 4.5, fig.height = 3.75}
draws <- as_draws_df(fit21.3)
# unclear if Kruschke still used 20 draws or not
# perhaps play with the `n_draw` values
n_draw <- 20
length <- 100
set.seed(21)
draws %>%
# take 20 random samples of the posterior draws
slice_sample(n = n_draw) %>%
# add in a sequence of x
expand(nesting(.draw, b_Intercept, b_x),
x = seq(from = -3.5, to = 3.5, length.out = length)) %>%
# compute the estimates of interest
mutate(y = inv_logit_scaled(b_Intercept + b_x * x),
thresh = -b_Intercept / b_x) %>%
# plot!
ggplot(aes(x = x)) +
geom_hline(yintercept = .5, color = pm[7], size = 1/2) +
geom_vline(aes(xintercept = thresh, group = .draw),
color = pm[6], size = 2/5, linetype = 2) +
geom_line(aes(y = y, group = .draw),
color = pm[1], size = 1/3, alpha = 2/3) +
geom_point(data = d_rare,
aes(y = y),
alpha = 1/3, color = pm[1]) +
ggtitle("Data with Post. Pred.") +
coord_cartesian(xlim = range(d_rare$x))
```
Here are the two subplots at the bottom, left.
```{r, fig.width = 6, fig.height = 2.5, warning = F, message = F}
draws %>%
mutate(Intercept = b_Intercept,
x = b_x) %>%
pivot_longer(Intercept:x) %>%
ggplot(aes(x = value, y = 0)) +
stat_wilke() +
scale_y_continuous(NULL, breaks = NULL) +
xlab(NULL) +
facet_wrap(~ name, scales = "free", ncol = 2)
```
Since our data were simulated without the benefit of knowing how Kruschke set his seed and such, our results will only approximate those in the text.
Okay, now we need to simulate the complimentary data, those for which $y = 1$ is a less-rare event.
```{r}
b0 <- 0
b1 <- 1
n <- 500
set.seed(21)
d_not_rare <-
tibble(x = rnorm(n, mean = 0, sd = 1)) %>%
mutate(mu = b0 + b1 * x) %>%
mutate(y = rbinom(n, size = 1, prob = 1 / (1 + exp(-mu))))
glimpse(d_not_rare)
```
Fitting this model is just like before.
```{r fit21.4}
fit21.4 <-
update(fit21.3,
newdata = d_not_rare,
iter = 2500, warmup = 500, chains = 4, cores = 4,
seed = 21,
file = "fits/fit21.04")
```
Behold the summary.
```{r}
print(fit21.4)
```
Here's the code for the main plot in Figure 21.5.b.
```{r}
draws <- as_draws_df(fit21.4)
set.seed(21)
p1 <-
draws %>%
slice_sample(n = n_draw) %>%
expand(nesting(.draw, b_Intercept, b_x),
x = seq(from = -3.5, to = 3.5, length.out = length)) %>%
mutate(y = inv_logit_scaled(b_Intercept + b_x * x),
thresh = -b_Intercept / b_x) %>%
ggplot(aes(x = x, y = y)) +
geom_hline(yintercept = .5, color = pm[7], size = 1/2) +
geom_vline(aes(xintercept = thresh, group = .draw),
color = pm[6], size = 2/5, linetype = 2) +
geom_line(aes(group = .draw),
color = pm[1], size = 1/3, alpha = 2/3) +
geom_point(data = d_rare,
alpha = 1/3, color = pm[1]) +
ggtitle("Data with Post. Pred.") +
coord_cartesian(xlim = c(-3, 3))
```
Now make the two subplots at the bottom.
```{r, warning = F}
p2 <-
draws %>%
mutate(Intercept = b_Intercept,
x = b_x) %>%
pivot_longer(Intercept:x) %>%
ggplot(aes(x = value, y = 0)) +
stat_wilke() +
scale_y_continuous(NULL, breaks = NULL) +
xlab(NULL) +
facet_wrap(~ name, scales = "free", ncol = 2)
```
This time we'll combine them with **patchwork**.
```{r, fig.width = 5.5, fig.height = 6}
p3 <- plot_spacer()
p1 / (p2 + p3 + plot_layout(widths = c(2, 1))) +
plot_layout(height = c(4, 1))
```
> You can see in Figure 21.5 that the estimate of the slope (and of the intercept) is more certain in the right panel than in the left panel. The $95\%$ HDI on the slope, $\beta_1$, is much wider in the left panel than in the right panel, and you can see that the logistic curves in the left panel have greater variation in steepness than the logistic curves in the right panel. The analogous statements hold true for the intercept parameter.
>
> Thus, if you are doing an experimental study and you can manipulate the $x$ values, you will want to select $x$ values that yield about equal numbers of $0$'s and $1$'s for the $y$ values overall. If you are doing an observational study, such that you cannot control any independent variables, then you should be aware that the parameter estimates may be surprisingly ambiguous if your data have only a small proportion of $0$'s or $1$'s. (pp. 631--632)
### Correlated predictors.
"Another important cause of parameter uncertainty is correlated predictors. This issue was previously discussed at length, but the context of logistic regression provides novel illustration in terms of level contours" (p. 632).
As far as I can tell, Kruschke chose about $n = 200$ for the data in this example. After messing around with correlations for a bit, it seems $\rho_{x_1, x_2} = .975$ looks about right. To my knowledge, the best way to simulate multivariate Gaussian data with a particular correlation is with the [`MASS::mvrnorm()` function](https://www.rdocumentation.org/packages/MASS/versions/7.3-51.1/topics/mvrnorm). Since we'll be using standardized $x$-variables, we'll need to specify our $n$, the desired correlation matrix, and a vector of means. Then we'll be ready to do the actual simulation with `mvrnorm()`.
```{r}
n <- 200
# correlation matrix
s <- matrix(c(1, .975,
.975, 1),
nrow = 2, ncol = 2)
# mean vector
m <- c(0, 0)
# simulate
set.seed(21)
d <-
MASS::mvrnorm(n = n, mu = m, Sigma = s) %>%
data.frame() %>%
set_names(str_c("x", 1:2))
```
Let's confirm the correlation coefficient.
```{r}
cor(d)
```
Solid. Now we'll use the $\beta$ values from page 633 to simulate the data set by including our dichotomous criterion variable, `y`.
```{r}
b0 <- 0
b1 <- 1
b2 <- 1
set.seed(21)
d <-
d %>%
mutate(mu = b0 + b1 * x1 + b2 * x2) %>%
mutate(y = rbinom(n, size = 1, prob = 1 / (1 + exp(-mu))))
```
Fit the model with the highly-correlated predictors.
```{r fit21.5}
fit21.5 <-
brm(data = d,
family = binomial,
y | trials(1) ~ 1 + x1 + x2,
prior = c(prior(normal(0, 2), class = Intercept),
prior(normal(0, 2), class = b)),
iter = 2500, warmup = 500, chains = 4, cores = 4,
seed = 21,
file = "fits/fit21.05")
```
Behold the summary.
```{r}
print(fit21.5)
```
We did a good job recapturing Kruschke's $\beta$s in terms of our posterior means, but notice how large those posterior $\textit{SD}$s are for $\beta_1$ and $\beta_2$. To get a better sense, let's look at them in a coefficient plot before continuing on with the text.
```{r, fig.width = 6, fig.height = 1, warning = F}
as_draws_df(fit21.5) %>%
pivot_longer(b_Intercept:b_x2) %>%
ggplot(aes(x = value, y = name)) +
stat_gradientinterval(point_interval = mode_hdi, .width = c(.5, .95),
color = pm[1], fill = pm[4]) +
labs(x = NULL, y = NULL) +
theme(axis.text.y = element_text(hjust = 0),
axis.ticks.y = element_blank())
```
Them are some sloppy estimates! But we digress. Here's our version of Figure 21.6.a.
```{r, fig.width = 4.25, fig.height = 4}
set.seed(21)
as_draws_df(fit21.5) %>%
slice_sample(n = 20) %>%
expand(nesting(.draw, b_Intercept, b_x1, b_x2),
x1 = c(-4, 4)) %>%
# this follows the equation near the top of p. 629
mutate(x2 = (-b_Intercept / b_x2) + (-b_x1 / b_x2) * x1) %>%
# now plot
ggplot(aes(x = x1, y = x2)) +
geom_line(aes(group = .draw),
color = pm[7], size = 2/5, alpha = 2/3) +
geom_text(data = d,
aes(label = y, color = y == 1),
size = 2.5) +
scale_color_manual(values = pm[c(4, 1)]) +
ggtitle("Data with Post. Pred.") +
coord_cartesian(xlim = c(-3, 3),
ylim = c(-3, 3)) +
theme(legend.position = "none")
```
It can be easy to under-appreciate how sensitive this plot is to the seed you set for `sample_n()`. To give a better sense of the uncertainty in the posterior for the threshold, here we show the plot for several different seeds.
```{r, fig.width = 6, fig.height = 6}
# make a custom function
different_seed <- function(i) {
set.seed(i)
as_draws_df(fit21.5) %>%
slice_sample(n = 20) %>%
expand(nesting(.draw, b_Intercept, b_x1, b_x2),
x1 = c(-4, 4)) %>%
mutate(x2 = (-b_Intercept / b_x2) + (-b_x1 / b_x2) * x1)
}
# specify your seeds
tibble(seed = 1:9) %>%
# pump those seeds into the `different_seed()` function
mutate(sim = map(seed, different_seed)) %>%
unnest(sim) %>%
mutate(seed = str_c("seed: ", seed)) %>%
# plot
ggplot(aes(x = x1, y = x2)) +
geom_line(aes(group = .draw),
color = pm[7], size = 2/5, alpha = 2/3) +
geom_text(data = d,
aes(label = y, color = y == 1),
size = 1.5) +
scale_color_manual(values = pm[c(4, 1)]) +
ggtitle("Data with Post. Pred.") +
coord_cartesian(xlim = c(-3, 3),
ylim = c(-3, 3)) +
theme(legend.position = "none") +
facet_wrap(~ seed)
```
To make our version of the pairs plots in Figure 21.6.b, we'll bring back some of our old tricks with **GGally**. First, we define our custom settings for the upper triangle, the diagonal, and lower triangle.
```{r, warning = F, message = F}
library(GGally)
my_upper <- function(data, mapping, ...) {
ggplot(data = data, mapping = mapping) +
geom_point(size = 1/2, shape = 1, alpha = 1/4, color = pm[2])
# geom_point(size = 1/4, alpha = 1/4, color = pm[2])
}
my_diag <- function(data, mapping, ...) {
ggplot(data = data, mapping = mapping) +
stat_wilke() +
scale_x_continuous(NULL, breaks = NULL) +
scale_y_continuous(NULL, breaks = NULL) +
coord_cartesian(ylim = c(-0.01, NA))
}
my_lower <- function(data, mapping, ...) {
# get the x and y data to use the other code
x <- eval_data_col(data, mapping$x)
y <- eval_data_col(data, mapping$y)
# compute the correlations
corr <- cor(x, y, method = "p", use = "pairwise")
abs_corr <- abs(corr)
# plot the cor value
ggally_text(
label = formatC(corr, digits = 2, format = "f") %>% str_replace(., "0.", "."),
mapping = aes(),
color = pm[1],
size = 4) +
scale_x_continuous(NULL, breaks = NULL) +
scale_y_continuous(NULL, breaks = NULL) +
theme(panel.background = element_rect(fill = pm[8]))
}
```
Now we wrangle and plot.
```{r, fig.width = 4, fig.height = 3.75, warning = F, message = F}