-
Notifications
You must be signed in to change notification settings - Fork 23
/
chapter14.Rmd
546 lines (442 loc) · 12.5 KB
/
chapter14.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
---
title: "Chapter 14"
author: "Scott Spencer"
date: "9/6/2018"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,
warning = FALSE, message = FALSE, error = FALSE)
library(dplyr); library(tidyr); library(rstan); library(skimr); library(ggplot2); library(ggthemes)
theme_set(theme_tufte(base_family = 'sans'))
```
The code below is meant as a directly-in-Stan translation of the examples in Chapter 14 of McElreath's *Statistical Rethinking*.
## 14.1 Measurement error
load the data.
```{r}
data('WaffleDivorce', package = 'rethinking')
d <- WaffleDivorce; rm(WaffleDivorce)
```
Figure 14.1
```{r}
p1 <- ggplot(d) + theme_tufte(base_family = 'sans') +
geom_segment(aes(x = MedianAgeMarriage, xend = MedianAgeMarriage,
y = Divorce + Divorce.SE, yend = Divorce - Divorce.SE)) +
geom_point(aes(MedianAgeMarriage, Divorce), shape = 21, fill = 'white') +
theme(plot.margin=unit(c(0,1,0,1),"cm")) +
labs(x = 'Median age marriage', y = 'Divorce rate')
p2 <- ggplot(d) + theme_tufte(base_family = 'sans') +
geom_segment(aes(x = log(Population), xend = log(Population),
y = Divorce + Divorce.SE, yend = Divorce - Divorce.SE)) +
geom_point(aes(log(Population), Divorce), shape = 21, fill = 'white') +
theme(plot.margin=unit(c(0,0,0,1),"cm")) +
labs(x = 'Log population', y = 'Divorce rate')
library(gridExtra)
grid.arrange(p1, p2, nrow = 1)
```
### 14.1.1 Error on the outcome
Code model in Stan.
```{stan output.var="m14_1"}
data {
int N;
vector[N] A;
vector[N] R;
vector[N] Dobs;
vector[N] Dsd;
}
parameters {
real a;
real ba;
real br;
real<lower=0> sigma;
vector[N] Dest;
}
model {
vector[N] mu;
// priors
target += normal_lpdf(a | 0, 10);
target += normal_lpdf(ba | 0, 10);
target += normal_lpdf(br | 0, 10);
target += cauchy_lpdf(sigma | 0, 2.5);
// linear model
mu = a + ba * A + br * R;
// likelihood
target += normal_lpdf(Dest | mu, sigma);
// prior for estimates
target += normal_lpdf(Dobs | Dest, Dsd);
}
generated quantities {
vector[N] log_lik;
{
vector[N] mu;
mu = a + ba * A + br * R;
for(i in 1:N) log_lik[i] = normal_lpdf(Dest[i] | mu[i], sigma);
}
}
```
Organize data and sample from model.
```{r}
dat <- list(
N = NROW(d),
A = d$MedianAgeMarriage,
R = d$Marriage,
Dobs = d$Divorce,
Dsd = d$Divorce.SE
)
fit14_1 <- sampling(m14_1, data = dat, iter = 1000, chains = 2, cores = 2)
```
Figure 14.2 left side
Show effects of shrinkage from the model.
```{r}
Dest14_1 <- as.matrix(fit14_1, pars = 'Dest')
d <- d %>% mutate(Dest_mean = apply(Dest14_1, 2, mean),
Dest_sd = apply(Dest14_1, 2, sd))
ggplot(d) + theme_tufte(base_family = 'sans') +
geom_point(aes(x = Divorce.SE, y = Dest_mean - Divorce)) +
geom_hline(yintercept = 0, linetype = 'dashed') +
labs(x = 'Divorce observed standard error',
y = 'Divorce estimated - divorce observed')
```
Figure 14.2 right side
```{r}
ggplot(d) + theme_tufte(base_family = 'sans') +
geom_segment(aes(x = MedianAgeMarriage, xend = MedianAgeMarriage,
y = Dest_mean - Dest_sd, yend = Dest_mean + Dest_sd)) +
geom_point(aes(x = MedianAgeMarriage, y = Dest_mean), shape = 21, fill = 'white') +
geom_smooth(aes(x = MedianAgeMarriage, y = Divorce), method='lm',formula=y~x, alpha = .1, linetype = 'dashed', color = 'black', lwd = .5) +
geom_smooth(aes(x = MedianAgeMarriage, y = Dest_mean), method='lm',formula=y~x, alpha = .2, lwd = .5)
# TODO: THIS DOESN'T MATCH BOOK
```
### 14.1.2 Error on both outcome and predictor
Code model in Stan.
```{stan output.var="m14_2"}
data {
int N;
vector[N] A;
vector[N] Dobs;
vector[N] Dsd;
vector[N] Robs;
vector[N] Rsd;
}
parameters {
real a;
real ba;
real br;
real<lower=0> sigma;
vector[N] Dest;
vector[N] Rest;
}
model {
vector[N] mu;
// priors
target += normal_lpdf(a | 0, 10);
target += normal_lpdf(ba | 0, 10);
target += normal_lpdf(br | 0, 10);
target += cauchy_lpdf(sigma | 0, 2.5);
// linear model
mu = a + ba * A + br * Rest;
// likelihood
target += normal_lpdf(Dest | mu, sigma);
// prior for estimates
target += normal_lpdf(Dobs | Dest, Dsd);
target += normal_lpdf(Robs | Rest, Rsd);
}
generated quantities {
vector[N] log_lik;
{
vector[N] mu;
mu = a + ba * A + br * Rest;
for(i in 1:N) log_lik[i] = normal_lpdf(Dest[i] | mu[i], sigma);
}
}
```
Organize data and sample from model.
```{r}
dat <- list(
N = NROW(d),
A = d$MedianAgeMarriage,
Robs = d$Marriage,
Rsd = d$Marriage.SE,
Dobs = d$Divorce,
Dsd = d$Divorce.SE
)
fit14_2 <- sampling(m14_2, data = dat, iter = 1000, chains = 2, cores = 2)
```
Summarise the model
```{r}
print(fit14_2)
```
Figure 14.3 left side
```{r}
Rest14_2 <- as.matrix(fit14_2, pars = 'Rest')
d <- d %>% mutate(Rest_mean = apply(Rest14_2, 2, mean),
Rest_sd = apply(Rest14_2, 2, sd))
ggplot(d) + theme_tufte(base_family = 'sans') +
geom_point(aes(x = Marriage.SE, y = Rest_mean - Marriage)) +
geom_hline(yintercept = 0, linetype = 'dashed') +
labs(x = 'Marriage observed standard error',
y = 'Marriage estimated - Marriage observed')
```
Figure 14.3 right side
```{r}
ggplot(d) + theme_tufte(base_family = 'sans') +
geom_segment(aes(x = Marriage, xend = Rest_mean,
y = Divorce, yend = Dest_mean)) +
geom_point(aes(x = Marriage, y = Divorce), color = 'dodgerblue') +
geom_point(aes(x = Rest_mean, y = Dest_mean), shape = 21, fill = 'white') +
labs(x = 'Marriage rate (posterior)', y = 'Divorce rate (posterior)')
```
## 14.2 Missing data
### 14.2.1 Imputing neocortex
Load the data.
```{r}
data('milk', package = 'rethinking')
d <- milk; rm(milk)
d <- d %>%
mutate(neocortex.prop = neocortex.perc / 100,
logMass = log(mass),
miss_idx = is.na(neocortex.perc) * cumsum(is.na(neocortex.perc)) )
```
Code the MCAR model in Stan.
```{stan output.var="m14_3"}
data {
int N;
vector[N] NCobs;
int N_miss;
int<lower=0,upper=N_miss> miss_idx[N];
vector[N] logMass;
vector[N] k;
}
parameters {
real a;
real bn;
real bm;
real<lower=0> sigma;
real mu_nc;
real<lower=0> sigma_nc;
vector[N_miss] nc_impute;
}
model {
vector[N] mu;
vector[N] NC;
int j = 1;
// priors
target += normal_lpdf(a | 0, 100);
target += normal_lpdf(bn | 0, 10);
target += normal_lpdf(bm | 0, 10);
target += cauchy_lpdf(sigma | 0, 1);
target += normal_lpdf(mu_nc | 0.5, 1);
target += cauchy_lpdf(sigma_nc | 0, 1);
// combine observed and estimates for missing
NC = NCobs;
for(i in 1:N) if(miss_idx[i] > 0) NC[i] = nc_impute[miss_idx[i]];
// impute missing
target += normal_lpdf(NC | mu_nc, sigma_nc);
// linear model
mu = a + bn * NC + bm * logMass;
// likelihood
target += normal_lpdf(k | mu, sigma);
}
```
Organize data and sample from the model.
```{r}
dat <- list(
N = NROW(d),
NCobs = ifelse(is.na(d$neocortex.prop), -1, d$neocortex.prop),
N_miss = sum(is.na(d$neocortex.perc)),
miss_idx = d$miss_idx,
logMass = d$logMass,
k = d$kcal.per.g
)
fit14_3 <- sampling(m14_3, data = dat, iter = 10000, chains = 2, cores = 2)
```
Summarise model.
```{r}
print(fit14_3, probs = c(.1, .5, .9))
```
Compare above model to one using only complete cases.
```{stan output.var="m14_4"}
data {
int N;
vector[N] NC;
vector[N] logMass;
vector[N] k;
}
parameters {
real a;
real bn;
real bm;
real<lower=0> sigma;
}
model {
vector[N] mu;
// priors
target += normal_lpdf(a | 0, 100);
target += normal_lpdf(bn | 0, 10);
target += normal_lpdf(bm | 0, 10);
target += cauchy_lpdf(sigma | 0, 1);
// linear model
mu = a + bn * NC + bm * logMass;
// likelihood
target += normal_lpdf(k | mu, sigma);
}
```
Organize data and sample from model
```{r}
dcc <- filter(d, complete.cases(d))
dat <- list(
N = NROW(dcc),
NC = dcc$neocortex.prop,
logMass = dcc$logMass,
k = dcc$kcal.per.g
)
fit14_4 <- sampling(m14_4, data = dat, iter = 10000, chains = 2, cores = 2)
```
Summarise model
```{r}
print(fit14_4, probs = c(.1, .5, .9))
```
Figure 14.4 left side
```{r}
imputed14_3 <-
as.data.frame(fit14_3, pars = c('nc_impute')) %>%
gather %>%
group_by(key) %>%
summarise(nc_imp_mean = mean(value),
nc_pi_l = rethinking::PI(value)[1],
nc_pi_h = rethinking::PI(value)[2]) %>%
ungroup() %>%
mutate(obs = as.integer(gsub('[^0-9]', '', key))) %>%
arrange(obs) %>%
mutate(kcal.per.g = d[!complete.cases(d),]$kcal.per.g,
logMass = d[!complete.cases(d),]$logMass)
# d$obsest <- d$neocortex.prop
# d[!complete.cases(d),]$obsest <- imputed14_3$nc_imp_mean
# TODO: regression line doesn't match book
ggplot() +
# stat_smooth(data = d,
# aes(x = obsest, y = kcal.per.g),
# method = lm, alpha = .2) +
geom_segment(data = imputed14_3,
aes(x = nc_pi_l, xend = nc_pi_h,
y = kcal.per.g, yend = kcal.per.g)) +
geom_point(data = imputed14_3,
aes(x = nc_imp_mean, y = kcal.per.g), shape = 21, fill = 'white') +
geom_point(data = d,
aes(x = neocortex.prop,
y = kcal.per.g), color = 'dodgerblue') +
labs(x = 'neocortex proportion', y = 'kcal per gram')
```
Figure 14.4 right side
```{r}
ggplot() +
geom_point(data = d,
aes(x = logMass, y = neocortex.prop), color = 'dodgerblue') +
geom_segment(data = imputed14_3,
aes(x = logMass, xend = logMass,
y = nc_pi_l, yend = nc_pi_h)) +
geom_point(data = imputed14_3,
aes(x = logMass, y = nc_imp_mean), shape = 21, fill = 'white') +
scale_x_continuous(breaks = seq(-2, 4))
```
### 14.2.2 Improving the imputation model
Code improved model in Stan.
```{stan output.var="m14_5"}
data {
int N;
vector[N] nc_obs;
int N_missing;
int<lower=0, upper=N_missing> missing[N];
vector[N] k;
vector[N] logmass;
}
parameters {
vector[N_missing] nc_imp;
real a;
real bn;
real bm;
real gm;
real a_nc;
real<lower=0> sigma_nc;
real<lower=0> sigma;
}
model {
vector[N] mu;
vector[N] mu_nc;
vector[N] nc;
// priors
target += normal_lpdf(a | 0, 100);
target += normal_lpdf(bn | 0, 10);
target += normal_lpdf(bm | 0, 10);
target += normal_lpdf(gm| 0, 10);
target += normal_lpdf(a_nc | 0.5 , 1);
target += cauchy_lpdf(sigma_nc | 0, 1);
target += cauchy_lpdf(sigma | 0, 1);
// imputation
nc = nc_obs;
for(i in 1:N) if (missing[i] > 0) nc[i] = nc_imp[missing[i]];
mu_nc = a_nc + gm * logmass;
target += normal_lpdf(nc | mu_nc, sigma_nc);
// linear model
mu = a + bn * nc + bm * logmass;
// likelihood
target += normal_lpdf(k | mu, sigma);
}
```
Organize data and sample from the model.
```{r}
dat <- list(
N = NROW(d),
nc_obs = ifelse(is.na(d$neocortex.prop), -1, d$neocortex.prop),
N_missing = sum(is.na(d$neocortex.perc)),
missing = d$miss_idx,
logmass = d$logMass,
k = d$kcal.per.g
)
fit14_5 <- sampling(m14_5, data = dat, iter = 10000, chains = 2, cores = 2)
```
Summarise model.
```{r}
print(fit14_5, probs = c(.1, .5, .9))
```
Figure 14.5 left side
```{r}
imputed14_5 <-
as.data.frame(fit14_5, pars = c('nc_imp')) %>%
gather %>%
group_by(key) %>%
summarise(nc_imp_mean = mean(value),
nc_pi_l = rethinking::PI(value)[1],
nc_pi_h = rethinking::PI(value)[2]) %>%
ungroup() %>%
mutate(obs = as.integer(gsub('[^0-9]', '', key))) %>%
arrange(obs) %>%
mutate(kcal.per.g = d[!complete.cases(d),]$kcal.per.g,
logMass = d[!complete.cases(d),]$logMass)
# TODO: regression line doesn't match book
ggplot() + theme_tufte(base_family = 'sans') +
# stat_smooth(data = d,
# aes(x = neocortex.prop, y = kcal.per.g),
# method = lm, alpha = .2) +
geom_segment(data = imputed14_5,
aes(x = nc_pi_l, xend = nc_pi_h,
y = kcal.per.g, yend = kcal.per.g)) +
geom_point(data = imputed14_5,
aes(x = nc_imp_mean, y = kcal.per.g), shape = 21, fill = 'white') +
geom_point(data = d,
aes(x = neocortex.prop,
y = kcal.per.g), color = 'dodgerblue') +
labs(x = 'neocortex proportion', y = 'kcal per gram')
```
Figure 14.5 right side
```{r}
ggplot() + theme_tufte(base_family = 'sans') +
geom_point(data = d,
aes(x = logMass, y = neocortex.prop), color = 'dodgerblue') +
geom_segment(data = imputed14_5,
aes(x = logMass, xend = logMass,
y = nc_pi_l, yend = nc_pi_h)) +
geom_point(data = imputed14_5,
aes(x = logMass, y = nc_imp_mean), shape = 21, fill = 'white') +
scale_x_continuous(breaks = seq(-2, 4))
```