-
Notifications
You must be signed in to change notification settings - Fork 8
/
assignment-07.Rmd
415 lines (331 loc) · 12.8 KB
/
assignment-07.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
# Assignment 7
2021-10-18
**[Assignment 7](`r paste0(CM_URL, "assignment-07.pdf")`)**
## Setup
```{r setup, warning=FALSE, message=FALSE}
knitr::opts_chunk$set(echo = TRUE, comment = "#>", dpi = 300)
for (f in list.files(here::here("src"), pattern = "R$", full.names = TRUE)) {
source(f)
}
library(rstan)
library(tidybayes)
library(magrittr)
library(tidyverse)
theme_set(theme_classic() + theme(strip.background = element_blank()))
options(mc.cores = 2)
rstan_options(auto_write = TRUE)
drowning <- aaltobda::drowning
factory <- aaltobda::factory
```
## 1. Linear model: drowning data with Stan
**The provided data `drowning` in the 'aaltobda' package contains the number of people who died from drowning each year in Finland 1980–2019.**
**A statistician is going to fit a linear model with Gaussian residual model to these data using time as the predictor and number of drownings as the target variable.**
**She has two objective questions:**
i) **What is the trend of the number of people drowning per year? (We would plot the histogram of the slope of the linear model.)**
ii) **What is the prediction for the year 2020? (We would plot the histogram of the posterior predictive distribution for the number of people drowning at $\tilde{x} = 2020$.)**
**Corresponding Stan code is provided in Listing 1.**
**However, it is not entirely correct for the problem.**
**First, there are *three mistakes*.**
**Second, there are no priors defined for the parameters.**
**In Stan, this corresponds to using uniform priors.**
**a) Find the three mistakes in the code and fix them.**
**Report the original mistakes and your fixes clearly in your report.**
**Include the full corrected Stan code in your report.**
1. Declaration of `sigma` on line 10 should be `real<lower=0>`.
2. Missing semicolon at the end of line 16.
3. On line 19, the prediction on new data does not use the new data in `xpred`. This has been changed to `real ypred = normal_rng(alpha + beta*xpred, sigma);`.
Below is a copy of the final model.
The full Stan file is at [models/assignment07-drownings.stan](`r paste0(MODELS_URL, "assignment07-drownings.stan")`).
```stan
data {
int<lower=0> N; // number of data points
vector[N] x; // observation year
vector[N] y; // observation number of drowned
real xpred; // prediction year
}
parameters {
real alpha;
real beta;
real<lower=0> sigma; // fix: 'upper' should be 'lower'
}
transformed parameters {
vector[N] mu = alpha + beta*x;
}
model {
y ~ normal(mu, sigma); // fix: missing semicolor
}
generated quantities {
real ypred = normal_rng(alpha + beta*xpred, sigma); // fix: use `xpred`
}
```
**b) Determine a suitable weakly-informative prior $\text{Normal}(0,\sigma_\beta)$ for the slope $\beta$.**
**It is very unlikely that the mean number of drownings changes more than 50 % in one year.**
**The approximate historical mean yearly number of drownings is 138.**
**Hence, set $\sigma_\beta$ so that the following holds for the prior probability for $\beta$: $Pr(−69 < \beta < 69) = 0.99$.**
**Determine suitable value for $\sigma_\beta$ and report the approximate numerical value for it.**
```{r}
x <- rnorm(1e5, 0, 26)
print(mean(-69 < x & x < 69))
plot_single_hist(x, alpha = 0.5, color = "black") + geom_vline(xintercept = c(-69, 69)) + labs(x = "beta")
```
**c) Using the obtained σβ, add the desired prior in the Stan code.**
From some trial and error, it seems that a prior of $\text{Normal}(0, 26)$ should work.
I have added this prior distribution to `beta` in the model at line 17.
```
beta ~ normal(0, 26); // prior on `beta`
```
**d) In a similar way, add a weakly informative prior for the intercept alpha and explain how you chose the prior.**
To use the year directly as the values for $x$ would lead to a massive value of $\alpha$ because the values for $x$ range from 1980 to 2019.
Thus, it would be advisable to first center the year, meaning at the prior distribution for $\alpha$ can be centered around the average of the number of drownings per year and a standard deviation near that of the actual number of drownings.
```{r}
head(drowning)
```
```{r}
print(mean(drowning$drownings))
print(sd(drowning$drownings))
```
Therefore, I add the prior $\text{Normal}(135, 50)$ to $\alpha$ on line 16.
```
alpha ~ normal(135, 50); // prior on `alpha`
```
```{r}
data <- list(
N = nrow(drowning),
x = drowning$year - mean(drowning$year),
y = drowning$drownings,
xpred = 2020 - mean(drowning$year)
)
drowning_model <- stan(
here::here("models", "assignment07-drownings.stan"),
data = data
)
```
```{r}
variable_post <- spread_draws(drowning_model, alpha, beta) %>%
pivot_longer(c(alpha, beta), names_to = "variable", values_to = "value")
head(variable_post)
```
```{r}
variable_post %>%
ggplot(aes(x = .iteration, y = value, color = factor(.chain))) +
facet_grid(rows = vars(variable), scales = "free_y") +
geom_path(alpha = 0.5) +
scale_x_continuous(expand = expansion(c(0, 0))) +
scale_y_continuous(expand = expansion(c(0.02, 0.02))) +
labs(x = "iteration", y = "value", color = "chain")
```
```{r}
variable_post %>%
ggplot(aes(x = value)) +
facet_grid(cols = vars(variable), scales = "free_x") +
geom_histogram(color = "black", alpha = 0.3, bins = 30) +
scale_x_continuous(expand = expansion(c(0.02, 0.02))) +
scale_y_continuous(expand = expansion(c(0, 0.02)))
```
```{r}
spread_draws(drowning_model, ypred) %$%
plot_single_hist(ypred, alpha = 0.3, color = "black") +
labs(x = "predicted number of drownings in 2020")
```
```{r}
red <- "#C34E51"
bayestestR::describe_posterior(drowning_model, ci = 0.89, test = c()) %>%
as_tibble() %>%
filter(str_detect(Parameter, "mu")) %>%
select(Parameter, Median, CI_low, CI_high) %>%
janitor::clean_names() %>%
mutate(idx = row_number()) %>%
left_join(drowning %>% mutate(idx = row_number()), by = "idx") %>%
ggplot(aes(x = year)) +
geom_point(aes(y = drownings), data = drowning, color = "#4C71B0") +
geom_line(aes(y = median), color = red, size = 1.2) +
geom_smooth(
aes(y = ci_low),
method = "loess",
formula = "y ~ x",
linetype = 2,
se = FALSE,
color = red,
size = 1
) +
geom_smooth(
aes(y = ci_high),
method = "loess",
formula = "y ~ x",
linetype = 2,
se = FALSE,
color = red,
size = 1
) +
labs(x = "year", y = "number of drownings (mean ± 89% CI)")
```
## 2. Hierarchical model: factory data with Stan
**The `factory` data in the 'aaltobda' package contains quality control measurements from 6 machines in a factory (units of the measurements are irrelevant here).**
**In the data file, each column contains the measurements for a single machine.**
**Quality control measurements are expensive and time-consuming, so only 5 measurements were done for each machine.**
**In addition to the existing machines, we are interested in the quality of another machine (the seventh machine).**
**For this problem, you’ll use the following Gaussian models:**
- **a separate model, in which each machine has its own model**
- **a pooled model, in which all measurements are combined and there is no distinction between machines**
- **a hierarchical model, which has a hierarchical structure as described in BDA3 Section 11.6**
**As in the model described in the book, use the same measurement standard deviation $\sigma$ for all the groups in the hierarchical model.**
**In the separate model, however, use separate measurement standard deviation $\sigma_j$ for each group $j$.**
**You should use weakly informative priors for all your models.**
**Complete the following questions for each of the three models (separate, pooled, hierarchical).**
**a) Describe the model with mathematical notation.**
**Also describe in words the difference between the three models.**
*Separate model*: The separate model is described below where each machine has its own centrality $\mu$ and dispersion $\sigma$ parameters that do not influence the parameters of the other machines.
$$
y_{ij} \sim N(\mu_j, \sigma_j) \\
\mu_j \sim N(0, 1) \\
\sigma_j \sim \text{Inv-}\chi^2(10)
$$
*Pooled model*: The pool model is described below where there is no distinction between the models but instead a single set of parameters for all of the data.
$$
y_{i} \sim N(\mu, \sigma) \\
\mu \sim N(0, 1) \\
\sigma \sim \text{Inv-}\chi^2(10)
$$
*Hierarchical model*: The hierarchical model is described below where each machine has its own centrality $\mu$ parameter which are linked through a hyper-prior distribution from which they are drawn.
The machines will all share a common dispersion paramete $\sigma$
$$
y_{ij} \sim N(\mu_j, \sigma_j) \\
\mu_j \sim N(\alpha, \tau) \\
\alpha \sim N(0, 1) \\
\tau \sim \text{HalfNormal}(2.5) \\
\sigma \sim \text{Inv-}\chi^2(10)
$$
The separate model is effectively building a different linear model for each machine where as the pooled model treats all the measurements as coming from the same model.
The hierarchical model is treating the machines as having come from a single, shared distribution.
**b) Implement the model in Stan and include the code in the report.**
**Use weakly informative priors for all your models.**
```{r}
print_model_code <- function(path) {
for (l in readLines(path)) {
cat(l, "\n")
}
}
```
*Separate model*
```{r}
separate_model_code <- here::here(
"models", "assignment07_factories_separate.stan"
)
print_model_code(separate_model_code)
```
```{r}
separate_model_data <- list(
y = factory,
N = nrow(factory),
J = ncol(factory)
)
separate_model <- rstan::stan(
separate_model_code,
data = separate_model_data,
verbose = FALSE,
refresh = 0
)
knitr::kable(
bayestestR::describe_posterior(separate_model, ci = 0.89, test = NULL),
digits = 3
)
```
*Pooled model*
```{r}
pooled_model_code <- here::here("models", "assignment07_factories_pooled.stan")
print_model_code(pooled_model_code)
```
```{r}
pooled_model_data <- list(
y = unname(unlist(factory)),
N = length(unlist(factory))
)
pooled_model <- rstan::stan(
pooled_model_code,
data = pooled_model_data,
verbose = FALSE,
refresh = 0
)
knitr::kable(
bayestestR::describe_posterior(pooled_model, ci = 0.89, test = NULL),
digits = 3
)
```
*Hierarchical model*
```{r}
hierarchical_model_code <- here::here(
"models", "assignment07_factories_hierarchical.stan"
)
print_model_code(hierarchical_model_code)
```
```{r}
hierarchical_model_data <- list(
y = factory,
N = nrow(factory),
J = ncol(factory)
)
hierarchical_model <- rstan::stan(
hierarchical_model_code,
data = hierarchical_model_data,
verbose = FALSE,
refresh = 0
)
knitr::kable(
bayestestR::describe_posterior(hierarchical_model, ci = 0.89, test = NULL),
digits = 3
)
```
**c) Using the model (with weakly informative priors) report, comment on and, if applicable, plot histograms for the following distributions:**
i) **the posterior distribution of the mean of the quality measurements of the sixth machine.**
ii) **the predictive distribution for another quality measurement of the sixth machine.**
iii) **the posterior distribution of the mean of the quality measurements of the seventh machine.**
```{r}
plot_hist_mean_of_sixth <- function(vals) {
plot_single_hist(vals, bins = 30, color = "black", alpha = 0.3) +
labs(x = "mean of 6th machine", y = "posterior density")
}
plot_hist_sixth_predictions <- function(vals) {
plot_single_hist(vals, bins = 30, color = "black", alpha = 0.3) +
labs(x = "posterior predictions for 6th machine", y = "posterior density")
}
plot_hist_mean_of_seventh <- function(vals) {
plot_single_hist(vals, bins = 30, color = "black", alpha = 0.3) +
labs(x = "mean of 7thth machine", y = "posterior density")
}
```
*Separate model*
```{r}
plot_hist_mean_of_sixth(rstan::extract(separate_model)$mu[, 6])
```
```{r}
plot_hist_sixth_predictions(rstan::extract(separate_model)$y6pred)
```
It is not possible to estimate the posterior for the mean of some new 7th machine because all machines are treated separately.
*Pooled model*
```{r}
plot_hist_mean_of_sixth(rstan::extract(pooled_model)$mu)
```
```{r}
plot_hist_sixth_predictions(rstan::extract(pooled_model)$ypred)
```
The predicted mean for a new machine is the same as the pooled mean $mu$.
```{r}
plot_hist_mean_of_seventh(rstan::extract(pooled_model)$mu)
```
*Hierarchical model*
```{r}
plot_hist_mean_of_sixth(rstan::extract(hierarchical_model)$mu[, 6])
```
```{r}
plot_hist_sixth_predictions(rstan::extract(hierarchical_model)$y6pred)
```
```{r}
plot_hist_mean_of_seventh(rstan::extract(hierarchical_model)$mu7pred)
```
**d) Report the posterior expectation for $\mu_1$ with a 90% credible interval but using a $\text{Normal}(0,10)$ prior for the $\mu$ parameter(s) and a $\text{Gamma}(1,1)$ prior for the $\sigma$ parameter(s).**
**For the hierarchical model, use the $\text{Normal}(0, 10)$ and $\text{Gamma}(1, 1)$ as hyper-priors.**
(I'm going to skip this one, but come back to it if it is needed for future assignments.)
---
```{r}
sessionInfo()
```