-
Notifications
You must be signed in to change notification settings - Fork 206
/
brms_demo.Rmd
1874 lines (1507 loc) · 58.3 KB
/
brms_demo.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: "Bayesian data analysis - BRMS demos"
author: "Aki Vehtari"
date: "First version 2023-12-05. Last modified `r format(Sys.Date())`."
output:
html_document:
fig_caption: yes
toc: TRUE
toc_depth: 2
number_sections: TRUE
toc_float:
smooth_scroll: FALSE
theme: readable
code_download: true
---
# Setup {.unnumbered}
```{r setup, include=FALSE}
knitr::opts_chunk$set(cache=TRUE, message=FALSE, error=FALSE, warning=TRUE, comment=NA, out.width='95%')
```
**Load packages**
```{r}
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)
library(ggplot2)
library(bayesplot)
theme_set(bayesplot::theme_default(base_family = "sans"))
library(tidybayes)
library(ggdist)
library(patchwork)
library(RColorBrewer)
library(gt)
SEED <- 48927 # set random seed for reproducability
```
# 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_Aalto/).
# Bernoulli model
Toy data with sequence of failures (0) and successes (1). We would
like to learn about the unknown probability of success.
```{r}
data_bern <- data.frame(y = c(1, 1, 1, 0, 1, 1, 1, 0, 1, 0))
```
As usual in case of generalizd 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.
```{r}
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) prior on 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) prior on Intercept')
```
Almost uniform prior on theta could be obtained also with normal(0,1.5)
```{r}
data.frame(theta = plogis(rnorm(n=20000, mean=0, sd=1.5))) |>
mcmc_hist() +
xlim(c(0,1)) +
labs(title='normal(0, 1.5) prior on Intercept')
```
Formula `y ~ 1` corresponds to a model $\mathrm{logit}(\theta) =
```{r}
#\alpha\times 1 = \alpha$. `brms? denotes the $\alpha$ as `Intercept`.
```
```{r 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.
```{r}
fit_bern
```
Extract the posterior draws
```{r}
draws <- as_draws_df(fit_bern)
```
We can get summary information using summarise_draws()
```{r}
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
```{r}
draws <- draws |>
mutate_variables(theta=plogis(b_Intercept))
```
Summary of theta by using summarise_draws()
```{r}
draws |>
subset_draws(variable='theta') |>
summarise_draws() |>
tt(digits=2)
```
Histogram of theta
```{r}
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 line indicate low
sensitivity and wider gaps between line indicate greater sensitivity.
```{r}
theta <- draws |>
subset_draws(variable='theta')
powerscale_sequence(fit_bern, prediction = \(x, ...) theta) |>
powerscale_plot_dens(variables='theta') +
# switch rows and cols
facet_grid(rows=vars(.data$variable),
cols=vars(.data$component)) +
# cleaning
ggtitle(NULL,NULL) +
labs(x='theta', y=NULL) +
scale_y_continuous(breaks=NULL) +
theme(axis.line.y=element_blank(),
strip.text.y=element_blank()) +
xlim(c(0,1))
```
We can summarise the prior and likelihood sensitivity using
cumulative Jensen-Shannon distance.
```{r}
powerscale_sensitivity(fit_bern, prediction = \(x, ...) theta)$sensitivity |>
filter(variable=='theta') |>
tt(digits=2, caption='Powerscaling sensitivity analysis')
# mutate(across(where(is.double), ~num(.x, digits=2)))
```
# 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
```{r}
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)`
```{r 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.
```{r}
fit_bin
```
The diagnostic indicates prior-data conflict, that is, both prior
and likelihood are informative. If there is true strong prior
information that would justify the normal(0,1) prior, then this is
fine, but otherwise more thinking is required (goal is not adjust
prior to remove diagnostic warnings withoyt thinking). In this toy
example, we proceed with this prior.
Extract the posterior draws
```{r}
draws <- as_draws_df(fit_bin)
```
We can get summary information using summarise_draws()
```{r}
draws |>
subset_draws(variable='b_Intercept') |>
summarise_draws()
```
We can compute the probability of success by using plogis which is
equal to inverse-logit function
```{r}
draws <- draws |>
mutate_variables(theta=plogis(b_Intercept))
```
Summary of theta by using summarise_draws()
```{r}
draws |>
subset_draws(variable='theta') |>
summarise_draws()
```
Histogram of theta
```{r}
mcmc_hist(draws, pars='theta') +
xlab('theta') +
xlim(c(0,1))
```
Re-run the model with a new data dataset without recompiling
```{r}
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.
```{r}
fit_bin
```
Extract the posterior draws
```{r}
draws <- as_draws_df(fit_bin)
```
We can get summary information using summarise_draws()
```{r}
draws |>
subset_draws(variable='b_Intercept') |>
summarise_draws()
```
We can compute the probability of success by using plogis which is
equal to inverse-logit function
```{r}
draws <- draws |>
mutate_variables(theta=plogis(b_Intercept))
```
Summary of theta by using summarise_draws()
```{r}
draws |>
subset_draws(variable='theta') |>
summarise_draws()
```
Histogram of theta
```{r}
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, which is useful for categorical variables.
```{r}
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{treatemnt}$ is a vector with 1 for
treatemnt 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.
```{r}
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. brms is using
the first factor level `control` as the baseline and thus reports
the coefficient (population-level effect) for `treatment` (shown s
`grp2treatment`)
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`.
```{r}
fit_bin2
```
Compute theta for each group and the odds-ratio. `brms` uses
bariable names `b_grp2control` and `b_grp2treatment` for
$\beta_\mathrm{control}$ and $\beta_\mathrm{treatment}$
respectively.
```{r}
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 oddsratio
```{r}
mcmc_hist(draws_bin2, pars='oddsratio') +
scale_x_continuous(breaks=seq(0.2,1.6,by=0.2))+
geom_vline(xintercept=1, linetype='dashed')
```
Probability that the oddsratio<1
```{r}
draws_bin2 |>
mutate(poddsratio = oddsratio<1) |>
subset(variable='poddsratio') |>
summarise_draws(mean, mcse_mean)
```
oddsratio 95% posterior interval
```{r}
draws_bin2 |>
subset(variable='oddsratio') |>
summarise_draws(~quantile(.x, probs = c(0.025, 0.975)), ~mcse_quantile(.x, probs = c(0.025, 0.975)))
```
Make prior sensitivity analysis by power-scaling both prior and
likelihood. Focus on oddsratio 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).
```{r}
oddsratio <- draws_bin2 |>
subset_draws(variable='oddsratio')
```
Prior and likelihood sensitivity plot shows posterior density estimate
depending on amount of power-scaling. Overlapping line indicate low
sensitivity and wider gaps between line indicate greater sensitivity.
```{r}
powerscale_sequence(fit_bin2, prediction = \(x, ...) oddsratio) |>
powerscale_plot_dens(variables='oddsratio') +
# switch rows and cols
facet_grid(rows=vars(.data$variable),
cols=vars(.data$component)) +
# cleaning
ggtitle(NULL,NULL) +
labs(x='Odds-ratio', y=NULL) +
scale_y_continuous(breaks=NULL) +
theme(axis.line.y=element_blank(),
strip.text.y=element_blank()) +
# reference line
geom_vline(xintercept=1, linetype='dashed')
```
We can summarise the prior and likelihood sensitivity using
cumulative Jensen-Shannon distance.
```{r}
powerscale_sensitivity(fit_bin2, prediction = \(x, ...) oddsratio, num_args=list(digits=2)
)$sensitivity |>
filter(variable=='oddsratio') |>
mutate(across(where(is.double), ~num(.x, digits=2)))
```
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.
```{r}
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) prior on 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) prior on 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 probablity 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}$.
```{r results='hide'}
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 prevous
non-hierarchical models.
```{r}
fit_bin2
```
We can also look at the variable names `brms` uses internally
```{r}
as_draws_rvars(fit_bin2)
```
Although there is no difference, illustrate how to compute the
oddsratio from hierarchical model
```{r}
draws_bin2 <- as_draws_df(fit_bin2)
oddsratio <- draws_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))) |>
subset_draws(variable='oddsratio')
oddsratio |> mcmc_hist() +
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 oddsratio.
```{r}
powerscale_sensitivity(fit_bin2, prediction = \(x, ...) oddsratio, num_args=list(digits=2)
)$sensitivity |>
filter(variable=='oddsratio') |>
mutate(across(where(is.double), ~num(.x, digits=2)))
```
# Linear Gaussian model
Use the Kilpisjärvi summer month temperatures 1952--2022 data from `aaltobda` package
```{r}
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
```{r}
data_lin |>
ggplot(aes(year, temp)) +
geom_point(color=2) +
labs(x= "Year", y = 'Summer temp. @Kilpisjärvi') +
guides(linetype = "none")
```
To analyse has there 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 `temp ~
normal(b_Intercept*1 + b_year*year, sigma)`. We start with the
default priors to see some tricks that `brms` does behind the
curtain.
```{r}
fit_lin <- brm(temp ~ year, data = data_lin, family = gaussian(),
seed = SEED, refresh = 0)
```
Check the summary of the posterior and inference diagnostics.
```{r}
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 proporion of variance
explained by the model. The linear model explains 0.16=16% of the
total data variance.
```{r}
bayes_R2(fit_lin) |> round(2)
```
We can check the all the priors used.
```{r}
prior_summary(fit_lin)
```
We see that `class=b` and `coef=year` have `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` uses `temp - mean(temp) = temp - 1987` instead of original
years. This in general improves the sampling efficiency. As the
`Intercept` is now defined at the middle of the data, the default
`Intercept` prior is centered on median of the target (here target
is `year`). If we would like to set informative priors, we need to
set the informative prior on `Intercept` given the centered
covariate values. We can turn of the centering by setting argument
`center=FALSE`, and 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
casse, 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.
```{r}
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.
```{r}
fit_lin
```
Make prior sensitivity analysis by power-scaling both prior and likelihood.
```{r}
powerscale_sensitivity(fit_lin)$sensitivity |>
mutate(across(where(is.double), ~num(.x, digits=2)))
```
Our weakly informative proper prior has negligible sensitivity, and
the likelihood is informative.
Extract the posterior draws and check the summaries
```{r}
draws_lin <- as_draws_df(fit_lin)
draws_lin |> summarise_draws()
```
If one of the columns is hidden we can force printing all columns
```{r}
draws_lin |> summarise_draws() |> print(width=Inf)
```
Histogram of b_year
```{r}
draws_lin |>
mcmc_hist(pars='b_year') +
xlab('Average temperature increase per year')
```
Probability that the coefficient b_year > 0 and the corresponding MCSE
```{r}
draws_lin |>
mutate(I_b_year_gt_0 = b_year>0) |>
subset_draws(variable='I_b_year_gt_0') |>
summarise_draws(mean, mcse_mean)
```
All posterior draws have `b_year>0`, the probability gets rounded
to 1, and MCSE is not available as the obserevd posterior variance
is 0.
95% posterior interval for temperature increase per 100 years
```{r}
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)),
.num_args = list(digits = 2, notation = "dec"))
```
Plot posterior draws of the linear function values at each year.
`add_linpred_draws()` takes the years from the data and uses `fit_lin` to make
the predictions.
```{r}
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))
```
Alternativelly plot a spaghetti plot for 100 draws
```{r}
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 make the predictions.
```{r}
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
```{r}
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 is examines the calibration
of LOO predictive distributions conditonally on each year. LOO-PIT
ploty looks good.
```{r}
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).
```{r 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.
```{r}
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.
```{r}
loo_compare(loo(fit_lin), loo(fit_lin_t))
```
# Heteroskedastic linear model
Heteroskedasticity assumes that the variation around the linear
mean can also vary. We can allow sigma to depend on year, too.
Although the additional component is written as `sigma ~ year`, the
log link function is used and the model is for log(sigma). `bf()` allows
listing several formulas.
```{r 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 mosst of the ma for negative values, indicating
decrease in temperature variation around the mean.
```{r}
fit_lin_h
```
Histogram of b_year and b_sigma_year
```{r}
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 posterior predictive distribution at each year until 2030
`add_predicted_draws()` takes the years from the data and uses
`fit_lin_h` to make the predictions.
```{r}
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.
```{r}
powerscale_sensitivity(fit_lin_h)$sensitivity |>
mutate(across(where(is.double), ~num(.x, digits=2)))
```
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.
```{r}
loo_compare(loo(fit_lin), loo(fit_lin_h))
```
# Heteroskedastic non-linear model
We can test the linearity assumption by using non-linear spline
functions, by uing `s(year)` terms. Sampling is slower as the
posterior gets more complex.
```{r 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, but with this
small data, this is not an issue.
```{r}
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.
```{r}
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 make the predictions.
```{r}
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 leave-one-out cross-validation 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.
```{r}
loo_compare(loo(fit_lin), loo(fit_spline_h))
```
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.
```{r}
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
```{r}
temp_diff |>
mcmc_hist()
```
95% posterior interval for average summer temperature increase from 1952 to 2022
```{r}
temp_diff |>
summarise_draws(~quantile(.x, probs = c(0.025, 0.975)),
~mcse_quantile(.x, probs = c(0.025, 0.975)),
.num_args = list(digits = 2, notation = "dec"))
```
Make prior sensitivity analysis by power-scaling both prior and
likelihood with focus on average summer temperature increase from
1952 to 2022.
```{r}
powerscale_sensitivity(fit_spline_h, prediction = \(x, ...) temp_diff, num_args=list(digits=2)
)$sensitivity |>
filter(variable=='temp_diff') |>
mutate(across(where(is.double), ~num(.x, digits=2)))