Simple Bayesian
Jan 20, 2019 #bayesian
library(tidyverse)
library(ggthemes)
old <- theme_set(theme_tufte() + theme(text = element_text(family = "Menlo")))
# parameters:
# number of ads shown
# number of visitors & proportional clicks
n_ads_shown <- 100
n_visitors <- seq(0, 100, 1)
prop_clicks <- seq(0, 1, 0.01)
params <-
expand.grid(prop_clicks = prop_clicks, n_visitors = n_visitors) %>%
as_tibble()
# setup joint probability distribution
jpdf <- params %>%
mutate(
# assume prior uniform from 0 to 20%
prior = dunif(prop_clicks, min = 0, max = .2),
# generative model goes here
likelihood = dbinom(n_visitors, size = n_ads_shown, prob = prop_clicks),
# on Bayes theorem
probs = prior * likelihood,
probs = probs / sum(probs)
)
jpdf
## # A tibble: 10,201 x 5
## prop_clicks n_visitors prior likelihood probs
## <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 0 0 5 1 0.0476
## 2 0.01 0 5 0.366 0.0174
## 3 0.02 0 5 0.133 0.00632
## 4 0.03 0 5 0.0476 0.00226
## 5 0.04 0 5 0.0169 0.000803
## 6 0.05 0 5 0.00592 0.000282
## 7 0.06 0 5 0.00205 0.0000979
## 8 0.07 0 5 0.000705 0.0000336
## 9 0.08 0 5 0.000239 0.0000114
## 10 0.09 0 5 0.0000802 0.00000382
## # … with 10,191 more rows
# update prior based on posterior
# conditioned on x visitors
jpdf %>%
filter(n_visitors == 6) %>%
ggplot(aes(prop_clicks, probs)) +
geom_bar(stat = "identity", width = 0.005) +
labs(x = "Proportional Clicks", y = "Probability")