Personal code snippets of @tmasjc

Site powered by Hugo

Image by Mads Schmidt Rasmussen from unsplash.com

Minimal Bootstrap Theme by Zachary Betz

Simple Bayesian

Jan 20, 2019 #bayesian

library(tidyverse)
library(ggthemes)

# set plot theme
old <- theme_set(theme_tufte() + theme(text = element_text(family = "Menlo")))

# number of ads shown
n_ads_shown <- 100

# parameters: number of visitors & proportional clicks
n_visitors <- seq(0, 100, 1)
prop_clicks <- seq(0, 1, 0.01)
pars <- expand.grid(prop_clicks = prop_clicks, 
                    n_visitors = n_visitors) %>% 
  sample_frac(1L) %>% 
  as_tibble()

# setup joint probability distribution
pars <- pars %>% 
  # assume an uniform distribution
  mutate(prior = dunif(prop_clicks, min = 0, max = .2),
         # calc the likelihood of getting x number of visitors given props click
         likelihood = dbinom(n_visitors, size = n_ads_shown, prob = prop_clicks),
         # probability is thus prior * likelihood
         probs = prior * likelihood, probs = probs / sum(probs))
pars
## # A tibble: 10,201 x 5
##    prop_clicks n_visitors prior likelihood probs
##          <dbl>      <dbl> <dbl>      <dbl> <dbl>
##  1        0.35         52     0   1.91e- 4     0
##  2        0.22         13     0   8.23e- 3     0
##  3        0.62         28     0   4.27e-12     0
##  4        0.31         45     0   1.09e- 3     0
##  5        0.26         73     0   1.11e-22     0
##  6        0.47         89     0   8.61e-19     0
##  7        0.91         49     0   4.51e-27     0
##  8        0.71         33     0   3.48e-15     0
##  9        0.55         87     0   5.69e-12     0
## 10        0.52         35     0   2.40e- 4     0
## # … with 10,191 more rows
# update prior based on posterior
pars %>% 
    filter(n_visitors == 6) %>% 
    ggplot(aes(prop_clicks, probs)) + 
    geom_bar(stat = "identity", width = 0.005) + 
    labs(x = "Proportional Clicks", y = "Probability")