-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgrid_search.Rmd
55 lines (42 loc) · 1.29 KB
/
grid_search.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
---
title: "Grid Search in the tidyverse"
author: "Andrew"
output:
distill::distill_article:
toc: true
toc_float: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
x_obs <- rbinom(10, 6, 0.6)
x_obs
like_binom <- function(p, d = x_obs){
exp(sum(dbinom(d, size = 6, prob = p, log = TRUE)))
}
grid_searched <- tibble::tibble(
p = seq(from = 0.01, to = .99, length.out = 200),
density_p = dbeta(p, .03*20, (1-.03*20)),
likelihood = purrr::map_dbl(p, like_binom),
prior_times_likelihood = density_p * likelihood,
post = prior_times_likelihood / sum (prior_times_likelihood)
)
head(grid_searched$likelihood)
library(ggplot2)
ggplot(grid_searched, aes(x = p, y = likelihood)) +
geom_line() +
geom_line(aes(y = prior_times_likelihood), lwd = 2, col = "darkred") +
geom_line(aes(y = post), col = "blue")
ggplot(grid_searched, aes(x = p, y = post)) + geom_line() +
geom_line(aes(y = density_p))
# calculate conjugate posterior
## prior = dbeta(1, 1)
## posterior
# dbeta(x, 1 + sum(xobs), 1 + sum(6 - xobs))
ggplot(grid_searched, aes(x = p, y = post*200)) +
geom_line(col = "red") +
stat_function(fun = function(x) dbeta(x,
1 + sum(x_obs),
1 + sum(6 - x_obs)))
```