Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A little animation of Bayesian updating with a
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
You can’t perform that action at this time.