-
Notifications
You must be signed in to change notification settings - Fork 0
/
ch03_sampling.qmd
195 lines (154 loc) · 5.15 KB
/
ch03_sampling.qmd
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
# Sampling the Imaginary {#sampling}
```{r }
#| include: false
library(assertthat)
library(rethinking)
library(brms)
library(dplyr)
library(tidyr)
library(ggplot2)
library(ggdist)
library(paletteer)
library(simpr)
```
## Sampling from grid-approximation posterior
We use the example from chapter 2.
The grid of $p$ values has a grid size of $grid\_size$.
The prior is uniformly distributed and so, as discussed in Overthinking box of section 2.3.3, p. 35, $P(p)=\frac{1}{1-0}=1$.
```{r}
the_grid <- data.frame(
prob = seq(from = 0, to = 1, length.out = 1000),
prior = 1)
```
and we calculate the posterior using the data. We compute the likelihood using the grid of priors from above, then compute the average likelihood which is the sum of the likelihood.
The posterior is defined in detailed in section 2.3.4, p. 37.
$$
\text{Posterior} =
\frac{\text{Likelihood} \times \text{Prior}}
{\text{Average Likelihood}}
$$
Note the code `stopifnot(sum(d$posterior) == 1)`, it is always a good idea to
verify this.
```{r}
# the data, see page 28
data <- c("W","L","W","W","W","L","W","L","W")
n_success <- sum(data == "W")
n_trials <- length(data)
# compute the likelihood each value in the grid
the_grid <- the_grid |>
mutate(
likelihood = dbinom(x = n_success, size = n_trials, prob = prob),
posterior = likelihood * prior / sum(likelihood))
assert_that(sum(the_grid$posterior) == 1,
msg = "The total posterior prob. must equal 1.")
```
which gives the estimated posterior probability $p$ conditional on the data for
each point of a grid.
Generate and visualize `n_samples` samples from the grid with the $p$ values
with their respective posterior probability $p$ computed above.
> Note: We use `dplyr::slice_sample` because `dplyr::sample_n` is deprecated.
```{r}
set.seed(1223)
the_samples <- the_grid |>
slice_sample(n = 1e4, weight_by = posterior, replace = TRUE) |>
# this distance from the mean is used for coloring
mutate(dist = abs(prob - mean(prob)))
the_samples$id <- seq_len(nrow(the_samples))
# str(the_samples)
```
visualize the sample of water proportion
```{r}
ggplot(data = the_samples, mapping = aes(x = id, y = prob, color = dist)) +
geom_point(size = 0.75, alpha = 0.9) +
scale_color_gradientn(colors = paletteer_d(palette="Manu::Kotare")) +
theme_minimal() +
theme(legend.position = "none") +
labs(title = sprintf("%d samples", nrow(the_samples)))
```
visualize the density
```{r}
# show the p density
ggplot(data = the_samples, aes(x = prob)) +
geom_density(aes(y=..scaled..), color = "blue", size = 1, fill = "lightblue") +
theme_light() +
labs(title = sprintf("%d samples", nrow(the_samples)))
```
## Sampling to summarize
### Intervals of defined boundaries
```{r}
the_grid |>
filter(prob < 0.5) |>
summarize(sum = sum(posterior))
```
and you can obtain the same result using the sampling data by counting the rows
```{r}
the_samples |>
filter(prob < 0.5) |>
count() |>
mutate(pct = n / nrow(the_samples)) |>
identity()
```
### Intervals of defined mass
Beside the base R `quantile` function, the `mean_qi` function from the package `ggdist` will be used extensively in this project. The benefits of using this package in conjonction with `posterior`, `tidybayes` etc. will become obvious in later chapters.
```{r}
the_samples |>
ggdist::mean_qi(prob, .width = 0.8)
```
And if we redo the sampling with observing 3 $W$ in 3 tosses we have the grid
```{r}
the_grid <- data.frame(
prob = seq(from = 0, to = 1, length.out = 1000),
prior = 1) |>
mutate(
likelihood = dbinom(x = 3, size = 3, prob = prob),
posterior = likelihood * prior / sum(likelihood))
assert_that(sum(the_grid$posterior) == 1,
msg = "The total posterior prob. must equal 1.")
```
and we use it to resample
```{r}
set.seed(1223)
the_samples <- the_grid |>
slice_sample(n = 1e4, weight_by = posterior, replace = TRUE) |>
# this distance from the mean is used for coloring
mutate(dist = abs(prob - mean(prob)))
the_samples$id <- seq_len(nrow(the_samples))
```
```{r}
the_samples |>
ggdist::mean_qi(prob, .width = 0.5)
```
```{r}
the_samples |>
ggdist::mean_hdi(prob, .width = 0.5)
```
and we can illustrate the intervals with `ggdist` as follows
```{r}
qtl <- c(0.5, 0.8, 0.95, 1)
x_breaks <- ggdist::mean_qi(.data = the_samples$prob,
.width = qtl) |>
select(y, ymin, ymax) |>
pivot_longer(cols = c("y", "ymin", "ymax")) |>
distinct(value) |>
arrange(value) |>
round(digits = 2) |>
pull()
ggplot(the_samples, aes(x=prob)) +
stat_halfeye(aes(fill=stat(cut_cdf_qi(
cdf,
.width = qtl,
labels = scales::percent_format()
)))) +
scale_x_continuous(breaks = x_breaks) +
scale_fill_paletteer_d(palette = "Manu::Takahe", direction = -1,
na.translate = FALSE) +
theme_ggdist() +
theme(legend.position = c(0.1, 0.75)) +
labs(title = "Intervals of defined mass",
x = "p_grid", y = "prob of p_grid",fill = "quantiles")
```
### Point estimates (loss function)
The **linex loss function** can be very useful in business analysis.
This is to be investigated later.
## Sampling to simulate prediction
## Summary