-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter2.R
64 lines (46 loc) · 1.62 KB
/
chapter2.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
calc_posterior <- function(samples, p_grid, prior) {
water <- sum(samples == "W")
likelihood <- dbinom(water, length(samples), prob = p_grid)
posterior <- likelihood * prior
posterior <- posterior / sum(posterior)
data.frame(x = p_grid, posterior = posterior)
}
plot_it <- function(data) {
ggplot2::ggplot(data, ggplot2::aes(x, posterior)) +
ggplot2::geom_point(ggplot2::aes(shape = ".", alpha = 0.1)) +
ggplot2::geom_line() +
ggplot2::xlab("Probability of water") +
ggplot2::ylab("Posterior probability")
}
## Q 2M1.
p_grid <- seq(0, 1, length.out = grid_points)
prior <- rep(1, length(p_grid))
sample_1 <- c("W", "W", "W")
posterior <- calc_posterior(sample_1, p_grid, prior)
plot_it(posterior)
sample_2 <- c("W", "W", "W", "L")
posterior <- calc_posterior(sample_2, p_grid, prior)
plot_it(posterior)
sample_3 <- c("L", "W", "W", "L", "W", "W", "W")
posterior <- calc_posterior(sample_3, p_grid, prior)
plot_it(posterior)
## Q 2M2
calc_new_prior <- function(p_grid) {
prior <- rep(1, length(p_grid))
prior[p_grid < 0.5] = 0
prior
}
prior <- calc_new_prior(p_grid)
posterior <- calc_posterior(sample_1, p_grid, prior)
plot_it(posterior)
posterior <- calc_posterior(sample_2, p_grid, prior)
plot_it(posterior)
posterior <- calc_posterior(sample_3, p_grid, prior)
plot_it(posterior)
## Q 2M3
# Assume equal chance of Earth or Mars globe being tossed, given that
# we have observed land, what is the probability we tossed the Earth globe?
# P(E|l) = P(l|E)*P(E) / P(l) by Bayes theorem
# P(l|E) is 0.3, P(E) is 0.5, P(L) is P(l|E) + P(l|M) = 0.5 * 0.3 + 0.5
# gives
prob = (0.3 * 0.5) / (0.5 * 0.3 + 0.5)