-
Notifications
You must be signed in to change notification settings - Fork 206
/
brms_demo.R
1539 lines (1378 loc) · 60.4 KB
/
brms_demo.R
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: "Bayesian data analysis - BRMS demos"
#' author: "Aki Vehtari"
#' date: 2023-12-05
#' date-modified: today
#' date-format: iso
#' format:
#' html:
#' toc: true
#' toc-location: left
#' toc-depth: 2
#' number-sections: true
#' smooth-scroll: true
#' theme: readable
#' code-copy: true
#' code-download: true
#' code-tools: true
#' embed-resources: true
#' anchor-sections: true
#' html-math-method: katex
#' ---
#' # Introduction
#'
#' This notebook contains several examples of how to use [Stan](https://mc-stan.org) in R with [__brms__](https://paul-buerkner.github.io/brms/). This notebook assumes basic knowledge of Bayesian inference and MCMC. The examples are related to [Bayesian data analysis course](https://avehtari.github.io/BDA_course_Aa/lto/).
#'
#+ setup, include=FALSE
knitr::opts_chunk$set(cache=FALSE, message=FALSE, error=FALSE, warning=TRUE, comment=NA, out.width='95%')
#' **Load packages**
#| code-fold: true
#| cache: FALSE
library(tidyr)
library(dplyr)
library(tibble)
library(pillar)
library(stringr)
library(brms)
options(brms.backend = "cmdstanr", mc.cores = 2)
library(posterior)
options(posterior.num_args=list(digits=2))
options(pillar.negative = FALSE)
library(loo)
library(priorsense)
#options(priorsense.use_plot_theme=FALSE)
library(ggplot2)
library(bayesplot)
theme_set(bayesplot::theme_default(base_family = "sans", base_size=14))
library(tidybayes)
library(ggdist)
library(patchwork)
library(RColorBrewer)
library(tinytable)
options(tinytable_format_num_fmt = "significant_cell", tinytable_format_digits = 2, tinytable_tt_digits=2)
SEED <- 48927 # set random seed for reproducibility
#' # Bernoulli model
#'
#' Toy data with sequence of failures (0) and successes (1). We would
#' like to learn about the unknown probability of success. brms wants
#' the data in a data frame format (tibble which is a variant of data
#' frame can be used, too).
data_bern <- data.frame(y = c(1, 1, 1, 0, 1, 1, 1, 0, 1, 0))
#' As usual in case of generalized linear models, (GLMs) brms defines
#' the priors on the latent model parameters. With Bernoulli the
#' default link function is logit, and thus the prior is set on
#' logit(theta). As there are no covariates logit(theta)=Intercept.
#' The brms default prior for Intercept is `student_t(3, 0, 2.5)`, but
#' we use `student_t(7, 0, 1.5)` which is close to logistic
#' distribution, and thus makes the prior near-uniform for theta.
#' We can simulate from these priors to check the implied prior on theta.
#' We next compare the result to using `normal(0, 1)` prior on logit
#' probability. We visualize the implied priors by sampling from the priors.
#'
#' `plogis` is the cumulative density function for logistic
#' distribution, which is equal to inverse-logit transformation.
#' Base-R's Student's t-distribution does not have `mu` and `sigma`
#' arguments, and thus we use a function from `ggdist` package.
data.frame(theta = plogis(ggdist::rstudent_t(n=20000, df=3, mu=0, sigma=2.5))) |>
mcmc_hist() +
xlim(c(0,1)) +
labs(title='Default brms student_t(3, 0, 2.5) for Intercept')
data.frame(theta = plogis(ggdist::rstudent_t(n=20000, df=7, mu=0, sigma=1.5))) |>
mcmc_hist() +
xlim(c(0,1)) +
labs(title='student_t(7, 0, 1.5) for Intercept')
#' Almost uniform prior on theta could be obtained also with normal(0,1.5)
data.frame(theta = plogis(rnorm(n=20000, mean=0, sd=1.5))) |>
mcmc_hist() +
xlim(c(0,1)) +
labs(title='normal(0, 1.5) for Intercept')
#' Formula `y ~ 1` corresponds to a model $\mathrm{logit}(\theta) = \alpha\times 1 = \alpha$.
#' `brms` denotes the $\alpha$ as `Intercept`.
#| results: hide
fit_bern <- brm(y ~ 1, family = bernoulli(), data = data_bern,
prior = prior(student_t(7, 0, 1.5), class='Intercept'),
seed = SEED, refresh = 0)
#' Check the summary of the posterior and inference diagnostics.
fit_bern
#' Extract the posterior draws in data frame (df) format
draws <- as_draws_df(fit_bern)
#' We can select subset of stored variables with `subset_draws()`
#' and get summary information using `summarise_draws()`
draws |>
subset_draws(variable='b_Intercept') |>
summarise_draws()
#' We get a prettier table using `tinytable::tt()`. Earlier we had
#' defined options
#' ```r
#' options(tinytable_format_num_fmt = "significant_cell",
#' tinytable_format_digits = 2,
#' tinytable_tt_digits=2)
#' ```
#' which makes the table to show only 2 significant digits for each value,
#' which is sufficient accuracy and having fewer digits makes the table
#' easier to read.
draws |>
subset_draws(variable='b_Intercept') |>
summarise_draws() |>
tt()
#' We can compute the probability of success by using `plogis` which is
#' equal to inverse-logit function
draws <- draws |>
mutate_variables(theta=plogis(b_Intercept))
#' Summary of `theta`
draws |>
subset_draws(variable='theta') |>
summarise_draws() |>
tt()
#' Histogram of `theta` using `bayesplot::mcmc_hist()`
mcmc_hist(draws, pars='theta') +
xlab('theta') +
xlim(c(0,1))
#' Prior and likelihood sensitivity plot shows posterior density estimate
#' depending on amount of power-scaling. Overlapping lines indicate low
#' sensitivity and wider gaps between lines indicate greater sensitivity.
#| warning: false
powerscale_plot_dens(draws, fit=fit_bern, variable='theta',
help_text=FALSE) +
xlim(c(0,1))
#' We can summarise the prior and likelihood sensitivity using
#' cumulative Jensen-Shannon distance.
powerscale_sensitivity(draws, fit=fit_bern, variable="theta") |>
tt()
#'
#' # Binomial model
#'
#' Instead of sequence of 0's and 1's, we can summarize the data with
#' the number of trials and the number successes and use Binomial
#' model. The prior is specified in the 'latent space'. The actual
#' probability of success, theta = plogis(alpha), where plogis is the
#' inverse of the logistic function.
#'
#' Binomial model with the same data and prior
data_bin <- data.frame(N = c(10), y = c(7))
#' Formula `y | trials(N) ~ 1` corresponds to a model
#' $\mathrm{logit}(\theta) = \alpha$, and the number of trials for
#' each observation is provided by `| trials(N)`
#| results: hide
fit_bin <- brm(y | trials(N) ~ 1, family = binomial(), data = data_bin,
prior = prior(student_t(7, 0,1.5), class='Intercept'),
seed = SEED, refresh = 0)
#' Check the summary of the posterior and inference diagnostics.
fit_bin
#' Extract the posterior draws in data frame format
draws <- as_draws_df(fit_bin)
#' Summary of latent intercept
draws |>
subset_draws(variable='b_Intercept') |>
summarise_draws() |>
tt()
#' We can compute the probability of success by using `plogis()` which is
#' equal to inverse-logit function
draws <- draws |>
mutate_variables(theta=plogis(b_Intercept))
#' Summary of theta
draws |>
subset_draws(variable='theta') |>
summarise_draws() |>
tt(digits=2)
#' Histogram of `theta`
mcmc_hist(draws, pars='theta') +
xlab('theta') +
xlim(c(0,1))
#' Re-run the model with a new data dataset without recompiling using
#' argument `newdata`.
#| results: hide
#| cache: true
data_bin <- data.frame(N = c(5), y = c(4))
fit_bin <- update(fit_bin, newdata = data_bin)
#' Check the summary of the posterior and inference diagnostics.
fit_bin
#' Extract the posterior draws in data frame format
draws <- as_draws_df(fit_bin)
#' Summary of latent intercept
draws |>
subset_draws(variable='b_Intercept') |>
summarise_draws() |>
tt(digits=2)
#' We can compute the probability of success by using `plogis()` which is
#' equal to inverse-logit function
draws <- draws |>
mutate_variables(theta=plogis(b_Intercept))
#' Summary of `theta`
draws |>
subset_draws(variable='theta') |>
summarise_draws() |>
tt(digits=2)
#' Histogram of `theta`
mcmc_hist(draws, pars='theta') +
xlab('theta') +
xlim(c(0,1))
#' # Comparison of two groups with Binomial
#'
#' An experiment was performed to estimate the effect of beta-blockers
#' on mortality of cardiac patients. A group of patients were randomly
#' assigned to treatment and control groups:
#'
#' - out of 674 patients receiving the control, 39 died
#' - out of 680 receiving the treatment, 22 died
#'
#' Data, where `grp2` is an indicator variable defined as a factor
#' type (using `factor()` function), which is useful for categorical
#' variables.
data_bin2 <- data.frame(N = c(674, 680),
y = c(39,22),
grp2 = factor(c('control','treatment')))
#' To analyse whether the treatment is useful, we can use Binomial
#' model for both groups and compute odds-ratio. To recreate the model
#' as two independent (separate) binomial models, we use formula `y |
#' trials(N) ~ 0 + grp2`, which corresponds to a model
#' $\mathrm{logit}(\theta) = \alpha \times 0 +
#' \beta_\mathrm{control}\times x_\mathrm{control} +
#' \beta_\mathrm{treatment}\times x_\mathrm{treatment} =
#' \beta_\mathrm{control}\times x_\mathrm{control} +
#' \beta_\mathrm{treatment}\times x_\mathrm{treatment}$, where
#' $x_\mathrm{control}$ is a vector with 1 for control and 0 for
#' treatment, and $x_\mathrm{treatment}$ is a vector with 1 for
#' treatment and 0 for control. As only of the vectors have 1, this
#' corresponds to separate models
#' $\mathrm{logit}(\theta_\mathrm{control}) = \beta_\mathrm{control}$
#' and $\mathrm{logit}(\theta_\mathrm{treatment}) =
#' \beta_\mathrm{treatment}$. We can provide the same prior for all
#' $\beta$'s by setting the prior with `class='b'`. With prior
#' `student_t(7, 0,1.5)`, both $\beta$'s are shrunk towards 0, but
#' independently.
#| results: hide
fit_bin2 <- brm(y | trials(N) ~ 0 + grp2, family = binomial(),
data = data_bin2,
prior = prior(student_t(7, 0,1.5), class='b'),
seed = SEED, refresh = 0)
#' Check the summary of the posterior and inference diagnostics. With `~ 0 +
#' grp2` there is no `Intercept` and \beta_\mathrm{control} and
#' \beta_\mathrm{treatment} are presented as `grp2control` and
#' `grp2treatment`.
fit_bin2
#' Compute theta for each group and the odds-ratio. `brms` uses
#' variable names `b_grp2control` and `b_grp2treatment` for
#' $\beta_\mathrm{control}$ and $\beta_\mathrm{treatment}$
#' respectively.
draws_bin2 <- as_draws_df(fit_bin2) |>
mutate(theta_control = plogis(b_grp2control),
theta_treatment = plogis(b_grp2treatment),
oddsratio = (theta_treatment/(1-theta_treatment))/(theta_control/(1-theta_control)))
#' Plot histogram of odds-ratio
mcmc_hist(draws_bin2, pars='oddsratio') +
scale_x_continuous(breaks=seq(0.2,1.6,by=0.2))+
geom_vline(xintercept=1, linetype='dashed')
#' Compute probability that the oddsratio<1 and associated Monte Carlo
#' standard error (MCSE). To compute the probability we use comparison
#' `oddsratio<1` to find out for which posterior draws this is true,
#' and when we compute mean over TRUE and FALSE values, these values
#' are converted to 1 and 0, and the `mean()` is then equal to the
#' proportion of 1's. The usual MCSE estimate for mean can be use to
#' get the MCSE for this proportion.
draws_bin2 |>
mutate(poddsratio = oddsratio<1) |>
subset(variable='poddsratio') |>
summarise_draws(mean, mcse_mean) |>
tt()
#' Compute odds-ratio 95% posterior interval, and associated MCSEs
draws_bin2 |>
subset(variable='oddsratio') |>
summarise_draws(~quantile(.x, probs = c(0.025, 0.975)), ~mcse_quantile(.x, probs = c(0.025, 0.975))) |>
tt()
#' Make prior sensitivity analysis by power-scaling both prior and
#' likelihood. Focus on odds-ratio which is the quantity of
#' interest. We see that the likelihood is much more informative than
#' the prior, and we would expect to see a different posterior only
#' with a highly informative prior (possibly based on previous similar
#' experiments).
#' Prior and likelihood sensitivity plot shows posterior density estimate
#' depending on amount of power-scaling. Overlapping lines indicate low
#' sensitivity and wider gaps between lines indicate greater sensitivity.
#| warning: false
powerscale_plot_dens(draws_bin2, fit=fit_bin2, variable='oddsratio',
help_text=FALSE) +
labs(x='Odds-ratio', y=NULL) +
scale_x_continuous(breaks=seq(0.2,1.4,by=0.2))+
# reference line
geom_vline(xintercept=1, linetype='dashed')
#' We can summarise the prior and likelihood sensitivity using
#' cumulative Jensen-Shannon distance. Here we prefer to show
#' 2 decimal digits (instead of the 2 significant digits we used before)
powerscale_sensitivity(draws_bin2, fit=fit_bin2, variable='oddsratio') |>
tt() |>
format_tt(num_fmt="decimal")
#' Above we used formula `y | trials(N) ~ 0 + grp2` to have separate
#' model for control and treatment group. An alternative model `y |
#' trials(N) ~ grp2` which is equal to `y | trials(N) ~ 1 + grp2`,
#' would correspond to a model $\mathrm{logit}(\theta) = \alpha \times
#' 1 + \beta_\mathrm{treatment}\times x_\mathrm{treatment} = \alpha +
#' \beta_\mathrm{treatment}\times x_\mathrm{treatment}$. Now $\alpha$
#' models the probability of death (via logistic link) in the control
#' group and $\alpha + \beta_\mathrm{treatment}$ models the
#' probability of death (via logistic link) in the treatment
#' group. Now the models for the groups are connected. Furthermore, if
#' we set independent `student_t(7, 0, 1.5)` priors on $\alpha$ and
#' $\beta_\mathrm{treatment}$, the implied priors on
#' $\theta_\mathrm{control}$ and $\theta_\mathrm{treatment}$ are
#' different. We can verify this with a prior simulation.
#'
data.frame(theta_control = plogis(ggdist::rstudent_t(n=20000, df=7, mu=0, sigma=1.5))) |>
mcmc_hist() +
xlim(c(0,1)) +
labs(title='student_t(7, 0, 1.5) for Intercept') +
data.frame(theta_treatment = plogis(ggdist::rstudent_t(n=20000, df=7, mu=0, sigma=1.5))+
plogis(ggdist::rstudent_t(n=20000, df=7, mu=0, sigma=1.5))) |>
mcmc_hist() +
xlim(c(0,1)) +
labs(title='student_t(7, 0, 1.5) for Intercept and b_grp2treatment')
#' In this case, with relatively big treatment and control group, the
#' likelihood is informative, and the difference between using `y |
#' trials(N) ~ 0 + grp2` or `y | trials(N) ~ grp2` is negligible.
#'
#' Third option would be a hierarchical model with formula `y |
#' trials(N) ~ 1 + (1 | grp2)`, which is equivalent to `y | trials(N)
#' ~ 1 + (1 | grp2)`, and corresponds to a model
#' $\mathrm{logit}(\theta) = \alpha \times 1 +
#' \beta_\mathrm{control}\times x_\mathrm{control} +
#' \beta_\mathrm{treatment}\times x_\mathrm{treatment}$, but now the
#' prior on $\beta_\mathrm{control}$ and $\beta_\mathrm{treatment}$ is
#' $\mathrm{normal}(0, \sigma_\mathrm{grp})$. The default `brms` prior
#' for $\sigma_\mathrm{grp}$ is `student_t(3, 0, 2.5)`. Now $\alpha$
#' models the overall probability of death (via logistic link), and
#' $\beta_\mathrm{control}$ and $\beta_\mathrm{treatment}$ model the
#' difference from that having the same prior. Prior for
#' $\beta_\mathrm{control}$ and $\beta_\mathrm{treatment}$ includes
#' unknown scale $\sigma_\mathrm{grp}$. If the there is not difference
#' between control and treatment groups, the posterior of
#' $\sigma_\mathrm{grp}$ has more mass near 0, and bigger the
#' difference between control and treatment groups are, more mass
#' there is away from 0. With just two groups, there is not much
#' information about $\sigma_\mathrm{grp}$, and unless there is a
#' informative prior on $\sigma_\mathrm{grp}$, two group hierarchical
#' model is not that useful. Hierarchical models are more useful with
#' more than two groups. In the following, we use the previously used
#' `student_t(7, 0,1.5)` prior on intercept and the default `brms`
#' prior `student_t(3, 0, 2.5)` on $\sigma_\mathrm{grp}$.
#| results: hide
#| cache: true
fit_bin2 <- brm(y | trials(N) ~ 1 + (1 | grp2), family = binomial(),
data = data_bin2,
prior = prior(student_t(7, 0,1.5), class='Intercept'),
seed = SEED, refresh = 0, control=list(adapt_delta=0.99))
#' Check the summary of the posterior and inference diagnostics. The summary
#' reports that there are Group-Level Effects: `~grp2` with 2 levels
#' (control and treatment), with `sd(Intercept)` denoting
#' $\sigma_\mathrm{grp}$. In addition, the summary lists
#' `Population-Level Effects: Intercept` ($\alpha$) as in the previous
#' non-hierarchical models.
fit_bin2
#' We can also look at the variable names `brms` uses internally.
#' We exclude variables `lprior` (log prior density) and `lp__`
#' (log posterior density).
as_draws_rvars(fit_bin2) |>
subset_draws(variable=c('lprior','lp__'), exclude=TRUE) |>
summarise_draws() |>
tt()
#' Although there is no difference, illustrate how to compute the
#' oddsratio from a hierarchical model.
draws_bin2 <- as_draws_df(fit_bin2) |>
mutate_variables(theta_control = plogis(b_Intercept + `r_grp2[control,Intercept]`),
theta_treatment = plogis(b_Intercept + `r_grp2[treatment,Intercept]`),
oddsratio = (theta_treatment/(1-theta_treatment))/(theta_control/(1-theta_control)))
draws_bin2 |> mcmc_hist(pars="oddsratio") +
scale_x_continuous(breaks=seq(0.2,1.6,by=0.2))+
geom_vline(xintercept=1, linetype='dashed')
#' Make also prior sensitivity analysis with focus on odds-ratio.
powerscale_sensitivity(draws_bin2, fit=fit_bin2, variable='oddsratio') |>
tt() |>
format_tt(num_fmt="decimal")
#' # Linear Gaussian model
#'
#' Use the Kilpisjärvi summer month temperatures 1952--2022 data from `aaltobda` package. We can read data directly from a URL.
load(url('https://github.com/avehtari/BDA_course_Aalto/raw/master/rpackage/data/kilpisjarvi2022.rda'))
data_lin <- data.frame(year = kilpisjarvi2022$year,
temp = kilpisjarvi2022$temp.summer)
#' Plot the data
data_lin |>
ggplot(aes(year, temp)) +
geom_point(color=2) +
labs(x= "Year", y = 'Summer temp. @Kilpisjärvi') +
guides(linetype = "none")
#' To analyse whether there has been change in the average summer month
#' temperature we use a linear model with Gaussian model for the
#' unexplained variation. By default brms uses uniform prior for the
#' coefficients.
#'
#' Formula `temp ~ year` corresponds to model $\mathrm{temp} ~
#' \mathrm{normal}(\alpha + \beta \times \mathrm{temp}, \sigma)$. The
#' model could also be defined as `temp ~ 1 + year` which explicitly
#' shows the intercept ($\alpha$) part. Using the variable names
#' `brms` uses the model can be written also as
#' $$
#' \mathrm{temp} \sim \mathrm{normal}(\mathrm{b\_Intercept}*1 + \mathrm{b\_year}*\mathrm{year}, \mathrm{sigma})
#' $$
#' We start with the default priors to see some tricks that `brms`
#' does behind the curtain.
#| results: hide
fit_lin <- brm(temp ~ year, data = data_lin, family = gaussian(),
seed = SEED, refresh = 0)
#' Check the summary of the posterior and inference diagnostics.
fit_lin
#' Convergence diagnostics look good. We see that posterior mean of
#' `Intercept` is -34.7, which may sound strange, but that is the
#' intercept at year 0, that is, very far from the data range, and
#' thus doesn't have meaningful interpretation directly. The posterior
#' mean of `year` coefficient is 0.02, that is, we estimate that the
#' summer temperature is increasing 0.02°C per year (which would make
#' 1°C in 50 years).
#'
#' We can check $R^2$ which corresponds to the proportion of variance
#' explained by the model. The linear model explains 0.16=16% of the
#' total data variance.
bayes_R2(fit_lin) |>
as_tibble() |>
tt()
#' We can check the all the priors used with `prior_summary()`
prior_summary(fit_lin) |>
tt()
#' We see that `class=b` and `coef=year` have prior `flat`, that is,
#' improper uniform prior, `Intercept` has `student_t(3, 9.5, 2.5)`,
#' and `sigma` has `student_t(3, 0, 2.5)` prior. In general it is
#' good to use proper priors, but sometimes flat priors are fine and
#' produce proper posterior (like in this case). Important part here
#' is that by default, `brms` sets the prior on Intercept after
#' centering the covariate values (design matrix). In this case,
#' `brms` centers the covariate `year` by subracting the mean year (1987),
#' and does the regression on centered covariate `year-1987`.
#' This in general improves the sampling efficiency. The
#' `Intercept` is now defined at the mean year, and by default
#' `brms` uses a weak proper prior on `Intercept` centered on median
#' of the target (`year`). If we would like to set informative priors,
#' we need to set the informative prior on `Intercept` given the
#' centered covariate values.
#'
#' Sometimes we prefer to turn of the automatic centering, and we can
#' do that by replacing the formula with `bf(temp ~ year, center=FALSE)`.
#' Or we can set the prior on original intercept by
#' using a formula `temp ~ 0 + Intercept + year`.
#'
#' In this case, we are
#' happy with the default prior for the intercept. In this specific
#' case, the flat prior on coefficient is also fine, but we add an
#' weakly informative prior just for the illustration. Let's assume we
#' expect the temperature to change less than 1°C in 10 years. With
#' `student_t(3, 0, 0.03)` about 95% prior mass has less than 0.1°C
#' change in year, and with low degrees of freedom (3) we have thick
#' tails making the likelihood dominate in case of prior-data
#' conflict. In real life, we do have much more information about the
#' temperature change, and naturally a hierarchical spatio-temporal
#' model with all temperature measurement locations would be even
#' better.
#| results: hide
fit_lin <- brm(temp ~ year, data = data_lin, family = gaussian(),
prior = prior(student_t(3, 0, 0.03), class='b'),
seed = SEED, refresh = 0)
#' Check the summary of the posterior and inference diagnostics.
fit_lin
#' Make prior sensitivity analysis by power-scaling both prior and likelihood.
powerscale_sensitivity(fit_lin) |>
tt() |>
format_tt(num_fmt="decimal")
#' Our weakly informative proper prior has negligible sensitivity, and
#' the likelihood is informative.
#' Extract the posterior draws and check the summaries. We exclude
#' variables `lprior` (log prior density) and `lp__` (log posterior
#' density).
draws_lin <- as_draws_df(fit_lin)
draws_lin |>
subset_draws(variable=c('lprior','lp__'), exclude=TRUE) |>
summarise_draws() |>
tt()
#' Histogram of `b_year`
draws_lin |>
mcmc_hist(pars='b_year') +
xlab('Average temperature increase per year')
#' Compute the probability that the coefficient `b_year` > 0 and the
#' corresponding MCSE.
draws_lin |>
mutate(I_b_year_gt_0 = b_year>0) |>
subset_draws(variable='I_b_year_gt_0') |>
summarise_draws(mean, mcse_mean) |>
tt(digits=2)
#' All posterior draws have `b_year>0`, the probability gets rounded
#' to 1, and MCSE is not available as the observed posterior variance
#' is 0.
#'
#' 95% posterior interval for temperature increase per 100 years and
#' associated MCSEs.
draws_lin |>
mutate(b_year_100 = b_year*100) |>
subset_draws(variable='b_year_100') |>
summarise_draws(~quantile(.x, probs = c(0.025, 0.975)),
~mcse_quantile(.x, probs = c(0.025, 0.975))) |>
tt() |>
format_tt(num_fmt="decimal")
#' Plot posterior draws of the linear function values at each year.
#' `add_linpred_draws()` takes the years from the data passed via
#' pipe, and uses `fit_lin` to make the linear model predictions.
#' `add_linpred_draws()` corresponds to `brms::posterior_linpred()`
data_lin |>
add_linpred_draws(fit_lin) |>
# plot data
ggplot(aes(x=year, y=temp)) +
geom_point(color=2) +
# plot lineribbon for the linear model
stat_lineribbon(aes(y = .linpred), .width = c(.95), alpha = 1/2, color=brewer.pal(5, "Blues")[[5]]) +
# decoration
scale_fill_brewer()+
labs(x= "Year", y = 'Summer temp. @Kilpisjärvi') +
theme(legend.position="none")+
scale_x_continuous(breaks=seq(1950,2020,by=10))
#' Plot a spaghetti plot for 100 posterior draws.
data_lin |>
add_linpred_draws(fit_lin, ndraws=100) |>
# plot data
ggplot(aes(x=year, y=temp)) +
geom_point(color=2) +
# plot a line for each posterior draw
geom_line(aes(y=.linpred, group=.draw), alpha = 1/2, color = brewer.pal(5, "Blues")[[3]])+
# decoration
scale_fill_brewer()+
labs(x= "Year", y = 'Summer temp. @Kilpisjärvi') +
theme(legend.position="none")+
scale_x_continuous(breaks=seq(1950,2020,by=10))
#' Plot posterior predictive distribution at each year until 2030.
#' `add_predicted_draws()` takes the years from the data and uses
#' `fit_lin` to draw from the posterior predictive distribution.
#' `add_predicted_draws()` corresponds to `brms::posterior_predict()`.
data_lin |>
add_row(year=2023:2030) |>
add_predicted_draws(fit_lin) |>
# plot data
ggplot(aes(x=year, y=temp)) +
geom_point(color=2) +
# plot lineribbon for the linear model
stat_lineribbon(aes(y = .prediction), .width = c(.95), alpha = 1/2, color=brewer.pal(5, "Blues")[[5]]) +
# decoration
scale_fill_brewer()+
labs(x= "Year", y = 'Summer temp. @Kilpisjärvi') +
theme(legend.position="none")+
scale_x_continuous(breaks=seq(1950,2030,by=10))
#' Posterior predictive check with density overlays examines the whole
#' temperature distribution. We generate replicate data using 20 different
#' posterior draws (with argument `ndraws`).
pp_check(fit_lin, type='dens_overlay', ndraws=20)
#' LOO-PIT check is good for checking whether the normal distribution
#' is well describing the variation as it examines the calibration
#' of LOO predictive distributions conditionally on each year. LOO-PIT
#' plot looks good. We use all posterior draws to estimate LOO predictive
#' distributions.
pp_check(fit_lin, type='loo_pit_qq', ndraws=4000)
#' # Linear Student's $t$ model
#'
#' The temperatures used in the above analyses are averages over three
#' months, which makes it more likely that they are normally
#' distributed, but there can be extreme events in the feather and we
#' can check whether more robust Student's $t$ observation model would
#' give different results (although LOO-PIT check did already indicate
#' that the normal would be good).
#'
#+ results='hide'
fit_lin_t <- brm(temp ~ year, data = data_lin,
family = student(),
prior = prior(student_t(3, 0, 0.03), class='b'),
seed = SEED, refresh = 0)
#' Check the summary of the posterior and inference diagnostics. The
#' `b_year` posterior looks similar as before and the posterior for
#' degrees of freedom `nu` has most of the posterior mass for quite
#' large values indicating there is no strong support for thick tailed
#' variation in average summer temperatures.
fit_lin_t
#' # Pareto-smoothed importance-sampling leave-one-out cross-validation (PSIS-LOO)
#'
#' We can use leave-one-out cross-validation to compare the expected
#' predictive performance.
#'
#' LOO comparison shows normal and Student's $t$ model have similar
#' performance. As `loo_compare()` returns it's own specific object
#' type, we need to do some manipulation to change it to a data frame
#' suitable for `tt()`.
loo_compare(loo(fit_lin), loo(fit_lin_t)) |>
as.data.frame() |>
rownames_to_column("model") |>
select(model, elpd_diff, se_diff) |>
tt()
#' # Heteroskedastic linear model
#'
#' Heteroscedasticity assumes that the variation around the linear
#' mean can also vary. We can allow sigma to depend on year, too.
#' `brms` supports multiple models using `bf()` function, and `sigma`
#' is a special keyword for the residual standard deviation.
#' Although the additional component is written as `sigma ~ year`, the
#' log link function is used and the model is for log(sigma).
#+ results='hide'
fit_lin_h <- brm(bf(temp ~ year,
sigma ~ year),
data = data_lin, family = gaussian(),
prior = prior(student_t(3, 0, 0.03), class='b'),
seed = SEED, refresh = 0)
#' Check the summary of the posterior and inference diagnostics. The `b_year`
#' posterior looks similar as before. The posterior for `sigma_year`
#' looks like having most of the mass for negative values, indicating
#' decrease in temperature variation around the mean.
fit_lin_h
#' Histograms of `b_year` and `b_sigma_year`
as_draws_df(fit_lin_h) |>
mcmc_areas(pars=c('b_year', 'b_sigma_year'))
#' As $log(x)$ is almost linear when $x$ is close to zero, we can see
#' that the `sigma` is decreasing about 1% per year (95% interval from
#' 0% to 2%).
#'
#' Plot the posterior predictive distribution at each year until 2030
#' `add_predicted_draws()` takes the years from the data and uses
#' `fit_lin_h` to draw from the posterior predictive distribution.
data_lin |>
add_row(year=2023:2030) |>
add_predicted_draws(fit_lin_h) |>
# plot data
ggplot(aes(x=year, y=temp)) +
geom_point(color=2) +
# plot lineribbon for the linear model
stat_lineribbon(aes(y = .prediction), .width = c(.95), alpha = 1/2, color=brewer.pal(5, "Blues")[[5]]) +
# decoration
scale_fill_brewer()+
labs(x= "Year", y = 'Summer temp. @Kilpisjärvi') +
theme(legend.position="none")+
scale_x_continuous(breaks=seq(1950,2030,by=10))
#' Make prior sensitivity analysis by power-scaling both prior and likelihood.
powerscale_sensitivity(fit_lin_h) |>
tt() |>
format_tt(num_fmt="decimal")
#' We can use leave-one-out cross-validation to compare the expected
#' predictive performance.
#'
#' LOO comparison shows homoskedastic normal and heteroskedastic
#' normal models have similar performances.
loo_compare(loo(fit_lin), loo(fit_lin_h)) |>
as.data.frame() |>
rownames_to_column("model") |>
select(model, elpd_diff, se_diff) |>
tt()
#' # Heteroskedastic non-linear model
#'
#' We can test the linearity assumption by using non-linear spline
#' functions, by using `s(year)` terms. Sampling is slower as the
#' posterior gets more complex.
#'
#+ results='hide'
fit_spline_h <- brm(bf(temp ~ s(year),
sigma ~ s(year)),
data = data_lin, family = gaussian(),
seed = SEED, refresh = 0)
#' We get warnings about divergences, and try rerunning with higher
#' adapt_delta, which leads to using smaller step sizes. Often
#' `adapt_delta=0.999` leads to very slow sampling and is not
#' generally recommended, but with this small data, this is not an
#' issue.
#| results: hide
#| cache: true
fit_spline_h <- update(fit_spline_h, control = list(adapt_delta=0.999))
#' Check the summary of the posterior and inference diagnostics. We're not
#' anymore able to make interpretation of the temperature increase
#' based on this summary. For splines, we see prior scales `sds` for
#' the spline coefficients.
fit_spline_h
#' We can still plot posterior predictive distribution at each year
#' until 2030 `add_predicted_draws()` takes the years from the data
#' and uses `fit_lin_h` to draw from the posterior predictive distribution.
data_lin |>
add_row(year=2023:2030) |>
add_predicted_draws(fit_spline_h) |>
# plot data
ggplot(aes(x=year, y=temp)) +
geom_point(color=2) +
# plot lineribbon for the linear model
stat_lineribbon(aes(y = .prediction), .width = c(.95), alpha = 1/2, color=brewer.pal(5, "Blues")[[5]]) +
# decoration
scale_fill_brewer()+
labs(x= "Year", y = 'Summer temp. @Kilpisjärvi') +
theme(legend.position="none")+
scale_x_continuous(breaks=seq(1950,2030,by=10))
#' And we can use LOO-CV to compare the
#' expected predictive performance.
#' LOO comparison shows homoskedastic normal linear and
#' heteroskedastic normal spline models have similar
#' performances. There are not enough observations to make clear
#' difference between the models.
loo_compare(loo(fit_lin), loo(fit_spline_h)) |>
as.data.frame() |>
rownames_to_column("model") |>
select(model, elpd_diff, se_diff) |>
tt()
#' For spline and other non-parametric models, we can use predictive
#' estimates and predictions to get interpretable quantities. Let's
#' examine the difference of estimated average temperature in years
#' 1952 and 2022.
temp_diff <- posterior_epred(fit_spline_h, newdata=filter(data_lin,year==1952|year==2022)) |>
rvar() |>
diff() |>
as_draws_df() |>
set_variables('temp_diff')
temp_diff <- data_lin |>
filter(year==1952|year==2022) |>
add_epred_draws(fit_spline_h) |>
pivot_wider(id_cols=.draw, names_from = year, values_from = .epred) |>
mutate(temp_diff = `2022`-`1952`,
.chain = (.draw - 1) %/% 1000 + 1,
.iteration = (.draw - 1) %% 1000 + 1) |>
as_draws_df() |>
subset_draws(variable='temp_diff')
#' Posterior distribution for average summer temperature increase from 1952 to 2022
temp_diff |>
mcmc_hist()
#' 95% posterior interval for average summer temperature increase from 1952 to 2022
temp_diff |>
summarise_draws(~quantile(.x, probs = c(0.025, 0.975)),
~mcse_quantile(.x, probs = c(0.025, 0.975))) |>
tt() |>
format_tt(num_fmt="decimal")
#' Make prior sensitivity analysis by power-scaling both prior and
#' likelihood with focus on average summer temperature increase from
#' 1952 to 2022.
powerscale_sensitivity(temp_diff, fit=fit_spline_h, variable='temp_diff') |>
tt() |>
format_tt(num_fmt="decimal")
#' Probability that the average summer temperature has increased from
#' 1952 to 2022 is 99.5%.
temp_diff |>
mutate(I_temp_diff_gt_0 = temp_diff>0,
temp_diff = NULL) |>
subset_draws(variable='I_temp_diff_gt_0') |>
summarise_draws(mean, mcse_mean) |>
tt(digits=2)
#'
#' # Comparison of k groups with hierarchical normal models
#'
#' Load factory data, which contain 5 quality measurements for each of
#' 6 machines. We're interested in analysing are the quality differences
#' between the machines.
factory <- read.table(url('https://raw.githubusercontent.com/avehtari/BDA_course_Aalto/master/rpackage/data-raw/factory.txt'))
colnames(factory) <- 1:6
factory
#' We pivot the data to long format
factory <- factory |>
pivot_longer(cols = everything(),
names_to = 'machine',
values_to = 'quality')
factory
#' ## Pooled model
#'
#' As comparison make also pooled model
#| results: hide
#| cache: true
fit_pooled <- brm(quality ~ 1, data = factory, refresh=0)
#' Check the summary of the posterior and inference diagnostics.
fit_pooled
#' ## Separate model
#'
#' As comparison make also separate model. To make it completely
#' separate we need to have different sigma for each machine, too.
#| results: hide
#| cache: true
fit_separate <- brm(bf(quality ~ 0 + machine,
sigma ~ 0 + machine),
data = factory, refresh=0)
#' Check the summary of the posterior and inference diagnostics.
fit_separate
#' # Common variance hierarchical model (ANOVA)
#| results: hide
#| cache: true
fit_hier <- brm(quality ~ 1 + (1 | machine),
data = factory, refresh = 0)
#' Check the summary of the posterior and inference diagnostics.
fit_hier
#' LOO comparison shows the hierarchical model is the best. The
#' differences are small as the number of observations is small and
#' there is a considerable prediction (aleatoric) uncertainty.
loo_compare(loo(fit_pooled), loo(fit_separate), loo(fit_hier)) |>
as.data.frame() |>
rownames_to_column("model") |>
select(model, elpd_diff, se_diff) |>
tt()
#' Different model posterior distributions for the mean
#' quality. Pooled model ignores the variation between
#' machines. Separate model doesn't take benefit from the similarity of
#' the machines and has higher uncertainty.
ph <- fit_hier |>
spread_rvars(b_Intercept, r_machine[machine,]) |>
mutate(machine_mean = b_Intercept + r_machine) |>
ggplot(aes(xdist=machine_mean, y=machine)) +
stat_halfeye() +
scale_y_continuous(breaks=1:6) +
labs(x='Quality', y='Machine', title='Hierarchical')
ps <- fit_separate |>
as_draws_df() |>
subset_draws(variable='b_machine', regex=TRUE) |>
set_variables(paste0('b_machine[', 1:6, ']')) |>
as_draws_rvars() |>
spread_rvars(b_machine[machine]) |>
mutate(machine_mean = b_machine) |>
ggplot(aes(xdist=machine_mean, y=machine)) +
stat_halfeye() +
scale_y_continuous(breaks=1:6) +
labs(x='Quality', y='Machine', title='Separate')
pp <- fit_pooled |>
spread_rvars(b_Intercept) |>
mutate(machine_mean = b_Intercept) |>
ggplot(aes(xdist=machine_mean, y=0)) +
stat_halfeye() +
scale_y_continuous(breaks=NULL) +
labs(x='Quality', y='All machines', title='Pooled')
(pp / ps / ph) * xlim(c(50,140))
#' Make prior sensitivity analysis by power-scaling both prior and
#' likelihood with focus on mean quality of each machine. We see no
#' prior sensitivity.
machine_mean <- fit_hier |>
as_draws_df() |>
mutate(across(matches('r_machine'), ~ .x - b_Intercept)) |>
subset_draws(variable='r_machine', regex=TRUE) |>
set_variables(paste0('machine_mean[', 1:6, ']'))
powerscale_sensitivity(machine_mean, fit=fit_hier, variable='machine_mean') |>
tt() |>
format_tt(num_fmt="decimal")
#'
#' # Hierarchical binomial model
#'
#' [Sorafenib Toxicity Dataset in `metadat` R package](https://wviechtb.github.io/metadat/reference/dat.ursino2021.html)
#' includes results from 13 studies investigating the occurrence of
#' dose limiting toxicities (DLTs) at different doses of Sorafenib.
#'
#' Load data
load(url('https://github.com/wviechtb/metadat/raw/master/data/dat.ursino2021.rda'))
head(dat.ursino2021)
#' Number of patients per study
dat.ursino2021 |>
group_by(study) |>
summarise(N = sum(total)) |>
ggplot(aes(x=N, y=study)) +
geom_col(fill=4) +
labs(x='Number of patients per study', y='Study')
#' Distribution of doses
dat.ursino2021 |>
ggplot(aes(x=dose)) +
geom_histogram(breaks=seq(50,1050,by=100), fill=4, colour=1) +
labs(x='Dose (mg)', y='Count') +
scale_x_continuous(breaks=seq(100,1000,by=100))
#' Each study is using 2--6 different dose levels. Three studies that
#' include only two dose levels (200 and 400) are likely to provide
#' weak information on slope.
crosstab <- with(dat.ursino2021,table(dose,study))
crosstab |>
as_tibble() |>
ggplot(aes(x=study, y=as.numeric(dose), fill=as.factor(n))) +
geom_tile() +
scale_fill_manual(name = "", values = c("white",4)) +
scale_y_continuous(breaks=c(100,300,200,400,600,800,1000)) +
labs(x="Study", y="Dose") +
theme(legend.position='none',
axis.text.x = element_text(angle = 45, hjust=1, vjust=1))
#' Pooled model assumes all studies have the same dose effect
#' (reminder: `~ dose` is equivalent to `~ 1 + dose`).
#' We use similar priors as in earlier binomial models.
#| results: hide
#| cache: true
fit_pooled <- brm(events | trials(total) ~ dose,
prior = c(prior(student_t(7, 0, 1.5), class='Intercept'),
prior(normal(0, 1), class='b')),
family=binomial(), data=dat.ursino2021)
#' Check the summary of the posterior and inference diagnostics.
fit_pooled
#' Dose coefficient seems to be very small. Looking at the posterior,
#' we see that it is positive with high probability.
fit_pooled |>
as_draws() |>
subset_draws(variable='b_dose') |>
summarise_draws(~quantile(.x, probs = c(0.025, 0.975)), ~mcse_quantile(.x, probs = c(0.025, 0.975))) |>
tt()