Created
February 1, 2019 15:49
-
-
Save jebyrnes/d08a380aa11e0c575590e751bc97eef8 to your computer and use it in GitHub Desktop.
A little animation of Bayesian updating with a
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(dplyr) | |
library(tidyr) | |
library(stringr) | |
library(ggplot2) | |
library(gganimate) | |
#make those samples! | |
set.seed(3003) | |
samps <- replicate(9, rbinom(1,1,prob = 0.3)) | |
running_samps <- cumsum(samps) | |
#make those posteriors for each trial! | |
posterior_tibble <- tibble( | |
h = seq(0, 1, length.out = 100), | |
) %>% | |
crossing(tibble(trial = 0:9, samp = c(1, running_samps) )) %>% | |
#get running likelihood * prior | |
group_by(h) %>% | |
arrange(trial) %>% | |
mutate(lik = dbinom(running_samps, prob = h[1], size = trial)) %>% | |
mutate(posterior = cumprod(lik)) %>% | |
#now throw in the p(d) denominator for each trial | |
group_by(trial) %>% | |
mutate(posterior = posterior/sum(posterior)) %>% | |
ungroup() %>% | |
#make the titles nicer | |
mutate(trial = str_c("trial ", trial), | |
trial = str_replace(trial, "trial 0", "prior")) | |
#plot with facets | |
ggplot(posterior_tibble, | |
aes(x = h, y = posterior)) + | |
geom_line() + | |
facet_wrap(~trial) | |
#plot with animation | |
ggplot(posterior_tibble, | |
aes(x = h, y = posterior)) + | |
geom_line(size = 1.2) + | |
labs(title = '{closest_state}', | |
y = "probability", | |
x = "fraction white") + | |
transition_states(trial , | |
transition_length = 2, | |
state_length = 3) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment