_Port of Tyler Folkman's Python version to Julia_

Bayes theorem is what allows us to go from a **sampling (or likelihood) distribution** and a **prior distribution** to a **posterior distribution**.

A sampling distribution is the probability of seeing **our data (X)** given our **parameters ($\theta$).** This is written as $p(X|\theta)$.

For example, we might have data on 1,000 coin flips. Where true indicates a head. This can be represented in Julia as

In [1]:

```
using Distributions
set_default_plot_size(10inch, 5inch)
```

In [2]:

```
data_coin_flips = rand(Bool, 1000)
mean(data_coin_flips)
```

Out[2]:

A sampling distribution allows us to specify how we think these data were generated. For our coin flips, we can think of our data as being generated from a Bernoulli Distribution. This distribution takes one **parameter** p which is the probability of getting a 1 (or a head for a coin flip). It then returns a value of 1 with probablility p and a value of 0 with probablility (1-p).

You can see how this is perfect for a coin flip. With a fair coin we know our p = .5 because we are equally likely to get a 1 (head) or 0 (tail). We can create samples from this distribution like this:

In [82]:

```
binomial_distribution = Binomial()
bernoulli_flips = rand(binomial_distribution,1000)
mean(bernoulli_flips)
```

Out[82]:

Now that we have defined how we believe our data were generated, we can calculate the probability of seeing our data given our parameters $p(X|\theta)$. Since we have selected a Bernoulli distribution, we only have one parameter: p.

We can use the **probability density function (PDF)** of the Bernoulli distribution to get our desired probability for a single coin flip. The PDF takes a single observed data point and then given the parameters of the distribution (p in our case) returns the probablility of seeing that data point given those parameters.

In [39]:

```
println(pdf(binomial_distribution,0))
println(pdf(binomial_distribution,1))
```

We can now use this function to get the probability of a data point give our parameters. You probably see that with p = .5 this function always returns .5

This is nice, but what we really want to know is the probability of see all 1,000 of our data points. How do we do that? The trick here is to assume that our data are independent and identically distributed. This assumption allows us to say the probability of seeing all of our data is just the product of each individual probability: $p(x_{1}, ..., x_{n}|\beta) = p(x_{1}|\beta) * ... * p(x_{n}|\beta)$. This is easy to do:

In [46]:

```
prod(pdf(Bernoulli(),data_coin_flips))
```

Out[46]:

How does that number help us? Well by itself, it doesn't really help too much. What we need to do now is get more of a distribution for our sampling model. Currently, we have only tested our model with p = .5, but what if p = .8? or .2? What would the probablility of our data look like then? This can be done by defining a grid of values for our p. Below I will make a grid of 100 values between 0 and 1 (because p has to be between 0 and 1) and then I will calculate the probability of seeing our data given each of these values:

In [108]:

```
using Gadfly
param = linspace(0, 1, 100)
p_x = [prod(pdf(Bernoulli(p),data_coin_flips)) for p in param]
plot(x=param, y=p_x, Geom.line, Guide.xticks(ticks=[0:0.1:1]))
```

Out[108]:

Now we are getting somewhere. We can see that the probablility of seeing our data peaks at p=.5 and almost certainly is between p=.4 and p=.6. Nice. So now we have a good idea of what p value generated our data assuming it was drawn from a Bernoulli distribution. We're done, right? Not quite...

Bayes theorem says that we need to think about both our sampling distribution and our prior distribution. What do I mean by prior distribution? It is the $p(\theta)$ or the probability of seeing a specific value for our parameter. In our sampling distribution we defined 100 values from 0 to 1 for our parameter p. Now we must define the prior probability of seeing each of those values. That is the probability we would have assumed before seeing any data. Most likely, we would have assumed a fair coin, which looks like the distribution above. Lets see how we can do this:

In [107]:

```
fair_flips = bernoulli_flips = rand(Binomial(1,0.5),1000)
p_fair = [prod(pdf(Bernoulli(p),fair_flips)) for p in param]
p_fair = p_fair / sum(p_fair)
plot(x=param, y=p_fair, Geom.line, Guide.xticks(ticks=[0:0.1:1]))
```

Out[107]:

Basically we created 1,000 fair coin flips and then generated the sampling distribution like we did before (except we divided by the sum of the sampling distribution to make the values sum to 1). Now we have a "fair coin" prior on our parameters. This basically means that before we saw any data we thought coin flips were fair. And we can see that assumption in our prior distribution by the fact that our prior distribution peaks at .5 and is almost all between .4 and .6.

I know what you are thinking - this is pretty boring. The sampling and prior distributions look exactly the same. So lets mix things up. Lets keep our fair prior but change our data to be an unfair coin:

In [93]:

```
unfair_flips = bernoulli_flips = rand(Binomial(1,0.8),1000)
p_unfair = [prod(pdf(Bernoulli(p),unfair_flips)) for p in param]
p1 = plot(x=param, y=p_unfair, Geom.line, Guide.xticks(ticks=[0:0.1:1]), Guide.XLabel("Sampling Distribution"))
p2 = plot(x=param, y=p_fair, Geom.line, Guide.xticks(ticks=[0:0.1:1]), Guide.XLabel("Prior Distribution"))
vstack(p1,p2)
```

Out[93]:

Ah - now this is interesting. We have strong data evidence of an unfair coin (since we generated the data we know it is unfair with p=.8), but our prior beliefs are telling us that coins are fair. How do we deal with this?

Bayes theorem is what allows us to go from our sampling and prior distributions to our posterior distribution. The **posterior distribution is the $P(\theta|X)$**. Or in English, the probability of our parameters given our data. And if you think about it that is what we really want. We are typically given our data - from maybe a survey or web traffic - and we want to figure out what parameters are most likely given our data. So how do we get to this posterior distribution? Here comes some math (don't worry it is not too bad):

By definition, we know that (If you don't believe me, check out this page for a refresher):

- $P(A|B) = \dfrac{P(A,B)}{P(B)}$. Or in English, the probability of seeing A given B is the probability of seeing them both divided by the probability of B.
- $P(B|A) = \dfrac{P(A,B)}{P(A)}$. Or in English, the probability of seeing B given A is the probability of seeing them both divided by the probability of A.

You will notice that both of these values share the same numerator, so:

- $P(A,B) = P(A|B)*P(B)$
- $P(A,B) = P(B|A)*P(A)$

Thus:

$P(A|B)*P(B) = P(B|A)*P(A)$

Which implies:

$P(A|B) = \dfrac{P(B|A)*P(A)}{P(B)}$

And plug in $\theta$ for $A$ and $X$ for $B$:

$P(\theta|X) = \dfrac{P(X|\theta)*P(\theta)}{P(X)}$

Nice! Now we can plug in some terminology we know:

$Posterior = \dfrac{likelihood * prior}{P(X)}$

But what is the $P(X)$? Or in English, the probability of our data? That sounds wierd... Let's go back to some math and use $B$ and $A$ again:

We know that $P(B) = \sum_{A} P(A,B)$ (check out this page for a refresher)

And from our definitions above, we know that:

$P(A,B) = P(A|B)*P(A)$

Thus:

$P(B) = \sum_{A} P(A|B)*P(A)$

Plug in our $\theta$ and $X$:

$P(X) = \sum_{\theta} P(\theta|X)*P(\theta)$

Plug in our terminology:

$P(X) = \sum_{\theta} likelihood * prior$

Wow! Isn't that awesome! But what do we mean by $\sum_{\theta}$. This means to sum over all the values of our parameters. In our coin flip example, we defined 100 values for our parameter p, so we would have to calculated the likelihood * prior for each of these values and sum all those anwers. That is our denominator for Bayes Theorem. Thus our final answer for Bayes is:

$Posterior = \dfrac{likelihood * prior}{\sum_{\theta} likelihood * prior}$

That was a lot of text. Let's do some more coding and put everything together.

In [103]:

```
function bern_post(n_param=100, n_sample=100, true_p=.8, prior_p=.5, n_prior=100)
param = linspace(0, 1, n_param)
sample = rand(Binomial(1,true_p),n_sample)
likelihood = [prod(pdf(Bernoulli(p),sample)) for p in param]
prior_sample = rand(Binomial(1,prior_p),n_prior)
prior = [prod(pdf(Bernoulli(p),prior_sample)) for p in param]
prior = prior / sum(prior)
posterior = [prior[i] * likelihood[i] for i in 1:length(prior)]
posterior = posterior / sum(posterior)
p1 = plot(x=param, y=likelihood, Geom.line, Guide.xticks(ticks=[0:0.1:1]), Guide.XLabel("Sampling Distribution"))
p2 = plot(x=param, y=prior, Geom.line, Guide.xticks(ticks=[0:0.1:1]), Guide.XLabel("Prior Distribution"))
p3 = plot(x=param, y=posterior, Geom.line, Guide.xticks(ticks=[0:0.1:1]), Guide.XLabel("Posterior Distribution"))
vstack(p1,p2,p3)
end
```

Out[103]:

In [106]:

```
bern_post()
```

Out[106]:

You will notice that I set 100 as the number of observations for the prior and likelihood. This increases the variance of our distributions. More data typically decreases the spread of a distribution. Also, as you get more data to estimate your likelihood, the prior distribution matters less.

In [110]:

```
bern_post(100,1000)
```

Out[110]:

You can see that effect in the graphs above. Because we have more data to help us estimate our likelihood our posterior distribution is closer to our likelihood. Pretty cool.

There you have it. An introduction to Bayes Theorem. Now if you ever are doubting the fairness of a coin you know how to investigate that problem! Or maybe the probability of a population voting yes for a law? Or any other yes/no outcome.

- You will notice that the denominator for Bayes Theorem is just a constant. So if you only want to get the maximum posterior value, you don't even need to calculate that constant. For this reason you will often see the posterior shown as proportional (or $\propto$ in math) to the likelihood * prior.
- Frequentist statistics is focused on the likelihood. Or you could say that frequentists are bayesians with a non-informative prior (like a uniform distribution). But don't hate on frequentists too much; most of bayesian inference in applied settings relies of frequentists statistics.
- Now that you know frequentist statistics focuses on the likelihood it is much clearer why people often misinterpret frequentist confidence intervals. The likelihood is $P(X|\theta)$ - or the probability of our data given our parameters. That is a bit wierd because we are given our data, not our parameters. What most frequentists models do is take the maximum of the likelihood distribution (or Maximum Likelihood Estimation (MLE)). Basically find what parameters maximize the probability of seeing our data. The important point here is that they are treating the data as random, so what the frequentist confidence interval is saying is that if you were to keep getting new data (maybe some more surveys) and calculate confidence intervals on each of these new samples, 95% of these samples would have confidence intervals that contain the true parameter you are trying to estimate.
- Fit a distribution to our data based on Maximum Likelihood Estimation (MLE) algorithm we simply call the fit function with the distribution type

In [7]:

```
fit(Bernoulli,data_coin_flips)
```

Out[7]: