## Introduction

Bayesian Statistics continues to remain incomprehensible in the ignited minds of many analysts. Being amazed by the incredible power of machine learning, a lot of us have become unfaithful to statistics. Our focus has narrowed down to exploring machine learning. Isn’t it true?

We fail to understand that machine learning is only one way to solve real world problems. In several situations, it does not help us solve business problems, even though there is data involved in these problems. To say the least,Â knowledge of statistics will allow you to work onÂ complex analytical problems, irrespective of the size of data.

In 1770s, Thomas Bayes introduced ‘Bayes Theorem’. Even after centuries later, the importance of ‘Bayesian Statistics’ hasn’t faded away. In fact, today this topic is being taught in great depths in some of the world’s leading universities.

With this idea, I’ve created this beginner’s guide on Bayesian Statistics.Â I’ve tried to explain the concepts in a simplistic manner with examples. Prior knowledge of basic probability & statisticsÂ is desirable. By the end of this article, you will have a concrete understanding of Bayesian Statistics and its associated concepts.

## Table of Contents

- Frequentist Statistics
- The Inherent Flaws in Frequentist Statistics
- Bayesian Statistics
- Conditional Probability
- Bayes Theorem

- Bayesian Inference
- Bernoulli likelihood function
- Prior Belief Distribution
- Posterior belief Distribution

- Test for Significance – Frequentist vs Bayesian
- p-value
- Confidence Intervals
- Bayes Factor
- High Density Interval (HDI)

Before we actually delve in Bayesian Statistics, let us spend a few minutes understanding *Frequentist Statistics*, the more popular version of statistics most of us come across and the inherent problems in that.

## 1. Frequentist Statistics

The debate between *frequentist* and *bayesian* have haunted beginners for centuries. Therefore, it is important to understand the difference between the two and howÂ does there exists a thin line of demarcation!

ItÂ is the most widely used inferential technique in the statistical world. Infact, generally it is the first school of thought that a person entering into the statistics world comes across.

**Frequentist StatisticsÂ **tests whether an event (hypothesis) occurs or not. It calculatesÂ the probability of an event in the long run of theÂ experiment (i.e the experiment is repeated under the same conditions to obtain the outcome).

Here, theÂ sampling distributions of **fixed size** are taken. Then,Â the experiment is theoretically repeated **infinite number of times** but practically done with a stopping intention. For example, I perform an experiment with a stopping intention in mind thatÂ I will stop the experiment when it is repeated 1000 times or I see minimum 300 heads in a coin toss.

Let’s go deeper now.

Now, we’llÂ understand *frequentist statistics*Â using an example of coin toss. The objective is to estimate the fairness of the coin. Below is a table representing the frequency of heads:

We know that probability of getting a head on tossing a fair coin is 0.5. `No. of heads`

represents the actual number of heads obtained. `Difference`

is the difference between `0.5*(No. of tosses) - no. of heads`

.

An important thing is to note that, though the difference between the actual number of heads and expected number of heads( 50% of number of tosses) increases as the number of tosses are increased, the proportion of number of heads to total number of tosses approaches 0.5 (for a fair coin).

This experiment presents us with a very common flaw found in frequentist approachÂ i.e.Â *Dependence of the result of an experiment on the number of times the experiment is repeated.*

To know more aboutÂ frequentist statistical methods, you can head to this excellent courseÂ on inferential statistics.

## 2. The Inherent Flaws in Frequentist Statistics

Till here, we’ve seen just one flaw in *frequentist statistics*. Well, it’s just the beginning.

20th century saw a massive upsurge in the *frequentist statistics* being applied to numerical models to check whether one sample is different from the other, a parameter is important enough to be kept in the model and variousother Â manifestations of hypothesis testing. But *frequentist statistics* suffered some great flaws in its design and interpretation Â which posed a serious concern in all real life problems. For example:

1. `p-values`

measured against a sample (fixed size) statistic with some stopping intention changes with change in intention and sample size. i.e If two persons work on the same data and have different stopping intention, they may get two different Â `p- valuesÂ `

for the same data, which is undesirable.

For example: Person A may choose to stop tossing a coin when the total count reaches 100 while B stops at 1000. For different sample sizes, we getÂ different t-scores and different p-values. Similarly, intention to stop may change from fixed number of flips to total duration of flipping. In this case too, we are bound to get different *p-values*.

2- Confidence Interval (C.I) like `p-value`

depends heavily on the sample size. This makes theÂ stopping potential absolutely absurd since no matter how many persons perform the tests on the same data, the results should be consistent.

3- Confidence Intervals (C.I) are not probability distributions therefore they do not provideÂ the most probable value for a parameter and the most probable values.

These three reasons are enough to get you going into thinking about the drawbacks of the *frequentist approach* and why is there a need for *bayesian approach*. Let’s find it out.

From here, we’ll first understand the basics of Bayesian Statistics.

## 3. Bayesian Statistics

“Bayesian statistics is a mathematical procedure thatÂ applies probabilities to statistical problems. It provides people the tools to update their beliefs in the evidence of new data.”

You got that? Let me explain it with an example:

Suppose, out of all the 4 championship races (F1) between Niki Lauda and James hunt, Niki won 3 times while James managed only 1.

So, if you were to bet on the winner of next race, who would he be ?

I bet you would say Niki Lauda.

Here’s the twist. What if you are told that it rained once when James won and once when Niki won and it is definite that it will rain on the next date. So, who would you bet your money on now ?

By intuition, it is easy to see that chances of winning for James have increased drastically. But the question is: how much ?

To understand the problem at hand, we need to become familiar with some concepts, first of which is conditional probability (explained below).

In addition, there are certain pre-requisites:

Pre-Requisites:

- Linear Algebra : To refresh your basics, you can check out Khan’s Academy Algebra.
- Probability and Basic Statistics :Â To refresh your basics, you can check out another course by Khan Academy.

### 3.1 Conditional Probability

It is defined as the: Probability of an event A given B equals the probability of B and A happening together divided by the probability of B.”

For example: Assume two partially intersecting sets A and B as shown below.

Set A represents one set of events and Set B represents another. We wish to calculate the probability of A given B has already happened. Lets represent the happening of event B by shading it with red.

Now since B has happened, the part whichÂ now matters for A is the part shaded in blue which is interestingly . So, the probability of A given B turns out to be:

Therefore, we can write the formula for event B given A has already occurred by:

or

Now, the second equation can be rewritten as :

This is known asÂ **Conditional Probability**.

Let’s try to answer aÂ betting problem with this technique.

Suppose, B be the *event of winning of James Hunt*. A beÂ the *event of raining*. Therefore,

- P(A) =1/2, since it rained twice out of four days.
- P(B) is 1/4, since James won only one race out of four.
- P(A|B)=1, since it rained every time when James won.

Substituting the values in the conditional probability formula, we get the probability to be around 50%, which is almost the double of 25% when rain was not taken into account (Solve it at your end).

This further strengthened ourÂ belief Â of* Â *James winning in the light of new *evidence *i.e rain.Â You must be wondering that this formula bears close resemblance to something you might have heard a lot about. Think!

Probably, you guessed it right. It looks like **Bayes Theorem**.

Bayes Â theorem is built on top of conditional probability and lies in the heartÂ of Bayesian Inference. Let’s understand it in detail now.

### 3.2 Bayes Theorem

Bayes Theorem comes into effect when multiple events Â form an exhaustive set with another event B. This could be understood with the help of the below diagram.

Now, B can be written as

So, probability of B can be written as,

But

So, replacing P(B) in the equation of conditional probability we get

This is the equation ofÂ **Bayes Theorem**.

## 4. Bayesian Inference

There is no point in diving into the theoretical aspect of it. So, we’ll learn how it works! Let’s take an exampleÂ of coin tossing to understand the idea behind *bayesian inference*.

An important partÂ ofÂ *bayesian inference* is the establishment of *parameters *and* models. *

Models are the mathematical formulation of the observed events. Parameters are the factors in the models affecting the observed data. For example, in tossing aÂ coin, **fairness of coinÂ **may be defined as the parameter of coin denoted byÂ Î¸. The outcome of the events may be denoted by D.

Answer this now. What is the probability of 4 heads out of 9 tosses(D) given the fairness of coin (Î¸). i.e `P(D|Î¸)`

Wait, did I ask the right question? No.

WeÂ should beÂ more interested in knowing : Given an outcome (D) what is the probbaility of coin being fair (Î¸=0.5)

Lets represent it using Bayes Theorem:

`P(Î¸|D)=(P(D|Î¸) X P(Î¸))/P(D)`

Here, `P(Î¸)`

** Â **is the

*i.e the strength of our belief in the fairness of coin before the toss. It is perfectly okay to believe that coin can have any degree of fairness between 0 and 1.*

**priorÂ**`P(D|Î¸)`

Â is the likelihood of observing our result given our distribution forÂ Î¸. If we knew that coin was fair, this gives the probability of observing the number of heads in a particular number of flips.

`P(D)`

is the evidence. This is the probability of data as determined by summing (or integrating) across all possible values of Î¸, weighted by how strongly we believe in those particular values of Î¸.

*If we had multiple views of what the fairness of the coin is (but didn’t know for sure), then this tells us the probability of seeing a certain sequence of flips for all possibilities of our belief in the coin’s fairness.*

`P(Î¸|D)`

is the posterior belief of our parameters after observing the evidence i.e the number of heads .

From here, we’ll dive deeper into mathematical implications of this concept. Don’t worry. Once you understand them, getting to its *mathematics*Â is pretty easy.

To define our model correctly , we need two mathematical models before hand. One to represent the * likelihood function P(D|Î¸)Â * and the other for representing the distribution of

*The product of these two gives the*

**prior beliefs .Â***distribution.*

**posterior belief P(Î¸|D)**Since prior and posterior are both beliefs about the distribution of fairness of coin, intuition tells us that both should have the same mathematical form. Keep this in mind. We will come back to it again.

So, there are several functions which support the existence of bayes theorem. Knowing them is important, hence I have explained them in detail.

### 4.1. BernoulliÂ likelihood function

Lets recap what we learned about the likelihood function. So, we learned that:

* It is the probability of observing a particular number of heads in a particular number of flips for a given fairness of coin. This means our probability of observing heads/tails depends upon the fairness of coin (Î¸).*

`P(y=1|Î¸)=Â `

Â Â [If coin is fair Î¸=0.5, probability of observing heads (y=1) is 0.5]

`P(y=0|Î¸)=`

Â [If coin is fair Î¸=0.5, probability of observing tails(y=0) is 0.5]

It is worth noticing that representing 1 as heads and 0 as tails is just a mathematical notation to formulate a model.Â We can combine the above mathematical definitions into a single definition to represent the probability of both the outcomes.

P(y|Î¸)=Â

This is called the **Bernoulli Likelihood Function** and the task of coin flipping is called Bernoulli’s trials.

`y={0,1},Î¸=(0,1)`

And, when we want to see a series of heads or flips, its probability is given by:

Furthermore, if we are interested in the probability of number of heads *z* turning up in *N* number of flips then the probability is given by:

### 4.2. Prior Belief Â Distribution

This distribution is used to represent our strengths on beliefs about the parameters based on the previous experience.

But,Â what if one has no previous experience?

Don’t worry. Mathematicians have devised methods to mitigate this problem too. It is known as `uninformative priors`

*. *I would like to inform you beforehand that it is just a misnomer. Every uninformative prior always provides some information event the constant distribution prior.

Well, the mathematical function used to represent the prior beliefs is known asÂ * beta distribution .Â *It has some very nice mathematical properties which enable us to model our beliefs about a binomial distribution.

Probability density function of beta distribution is of the form :

where, our focus staysÂ on numerator. The denominator is there just to ensure that the total probability density function upon integration evaluates to 1.

`Î±`

andÂ `Î²`

are called the shape deciding parameters of the density function. HereÂ `Î±`

is analogous to number of heads in the trials andÂ `Î²`

corresponds to the number of tails. The diagrams below will help you visualize the beta distributions for different values ofÂ `Î±`

andÂ `Î²`

You too can draw the beta distribution for yourself using the following code in R:

`> library(stats)`

`> par(mfrow=c(3,2))`

`> x=seq(0,1,by=o.1)`

`> alpha=c(0,2,10,20,50,500)`

`> beta=c(0,2,8,11,27,232)`

`> for(i in 1:length(alpha)){`

`Â Â Â Â y<-dbeta(x,shape1=alpha[i],shape2=beta[i])`

`Â Â Â Â plot(x,y,type="l")`

`}`

*Note:*Â `Î±`

andÂ `Î²`

are intuitive to understand since they can be calculated by knowing the mean (Î¼) and standard deviation (Ïƒ) of the distribution. In fact, they are related as :

If mean and standard deviation of a distribution are known , then there shape parameters can be easily calculated.

**Inference drawn from graphs above:**

- When there was no toss we believed that every fairness of coin is possible as depicted by the flat line.
- When there were more number of heads than the tails, the graph showedÂ a peak shifted towards the right side, indicating higher probability of heads and that coin is not fair.
- As more tosses are done, and heads continue to come in larger proportion the peak narrows increasing our confidence in the fairness of the coin value.

### 4.3. Posterior Belief Distribution

The reason that we chose prior belief is to obtain a beta distribution. This is because when we multiply it with a likelihood function, posterior distribution yields a form similar to the prior distribution which is much easier to relate to and understand. If this much information whets your appetite, I’m sure you are ready to walk an extra mile.

Let’s calculate posterior belief using bayes theorem.

**Calculating posterior belief using Bayes Theorem**

Now,Â our posterior belief becomes,

This is interesting.Â Just knowing the mean and standard distribution of our belief about the parameterÂ `Î¸`

and by observing the number of heads in N flips, we can update our belief about the model parameter(`Î¸`

).

Lets understand this with the help of a simple example:

Suppose, you think that a coin is biased. It has a mean (Î¼) bias of around 0.6 with standard deviation ofÂ 0.1.

Then ,

`Î±= 13.8`

,Â `Î²=9.2`

i.e our distribution will be biased on the right side. Suppose, you observed 80 heads (`z=80`

) in 100 flips(`N=100`

). Let’s see howÂ our prior and posterior beliefs are going to look:

`prior = P(Î¸|Î±,Î²)=P(Î¸|13.8,9.2)`

`Posterior = P(Î¸|z+Î±,N-z+Î²)=P(Î¸|93.8,29.2)`

Lets visualize both the beliefs on a graph:

The R code for the above graph is as:

`> library(stats)`

`> x=seq(0,1,by=0.1)`

`> alpha=c(13.8,93.8)`

`> beta=c(9.2,29.2)`

>Â `for(i in 1:length(alpha)){`

`Â Â Â y<-dbeta(x,shape1=alpha[i],shape2=beta[i])`

`Â Â Â plot(x,y,type="l",xlab = "theta",ylab = "density")`

`}`

As more and more flips are made and new data is observed, our beliefs get updated. This is the real power of Bayesian Inference.

## 5. Test for Significance – Frequentist vs Bayesian

Without going into the rigorous mathematical structures, this section will provide you a quickÂ overviewÂ ofÂ different approaches of frequentist and bayesian methods to test for significance and difference between groups and which method is most reliable.

### 5.1. p-value

In this, the t-score for a particular sample from a sampling distribution of *fixed sizeÂ *is calculated. Then, p-values are predicted. We can interpret p values as (taking an example of p-value as 0.02 for a distribution of mean 100) : There is 2% probability that the sample will have mean equal to 100.

This interpretation suffers from the flaw that for sampling distributions of different sizes, one is bound to get different t-score and hence different p-value. It is completely absurd. A p-value less than 5% does not guarantee that null hypothesis is wrong nor a p-value greater than 5% ensures that null hypothesis is right.

### 5.2. Confidence Intervals

Confidence Intervals also suffer from the same defect. Moreover since C.I is not a probability distribution , there is no way to know which values are most probable.

### 5.3. Bayes Factor

Bayes factor is the equivalent of p-value in the bayesian framework. Lets understand itÂ in an comprehensive manner.

The *null hypothesis* in bayesian framework assumes âˆž probability distribution only at a particular value of a parameter (say Î¸=0.5) and a zero probability else where. (M1)

The *alternative hypothesis* is that all values ofÂ Î¸ are possible, hence a flat curve representing the distribution. (M2)

Now, posterior distribution ofÂ the new data looks like below.

Bayesian statistics adjusted credibility (probability) of various values ofÂ Î¸. It can be easily seen that the probability distribution has shifted towards M2 with a value higher than M1 i.e M2 is more likely to happen.

Bayes factor does not depend upon the actual distribution values ofÂ Î¸ but the magnitude of shift in values of M1 and M2.

In panel A (shown above): left bar (M1) is the prior probability of the null hypothesis.

In panel B (shown), the left bar is the posterior probability of the null hypothesis.

Bayes factor is defined as the ratio of the posterior odds to the prior odds,

To reject a null hypothesis, a BF <1/10 is preferred.

We can see the immediate benefits of using Bayes Factor instead of p-values since they are independent of intentions and sample size.

### 5.4.Â High Density Interval (HDI)

HDI is formed from the posterior distribution after observing the new data. Since HDI is a probability, the 95% HDI gives the 95% most credible values. It is also guaranteed that 95 % values will lie in this interval unlike C.I.

Notice, how the 95% HDI in prior distribution is wider than the 95% posterior distribution. This is because our belief in HDI increases upon observation of new data.

## End Notes

The aim of this article was to get you thinking about the different type of statistical philosophies out there and how any single of them cannot be used in every situation.

It’s a high time that both the philosophies are merged to mitigate the real world problems by addressing the flaws of the other. Part II of this series will focus on the Dimensionality Reduction techniques using MCMC (Markov Chain Monte Carlo) algorithms. Part III will be based on creating a Bayesian regression model from scratch and interpreting its results in R.Â So, before I start with Part II, I would like to have your suggestions / feedback on this article.

Did you like reading this article ? As a beginner, were you able to understand the concepts? Let me know in comments.

Thx for this great explanation.

I’m a beginner in statistics and data science and I really appreciate it.

If you’re interested to see another approach, how toddler’s brain use Bayesian statistics in a natural way there is a few easy-to-understand neuroscience courses : http://www.college-de-france.fr/site/en-stanislas-dehaene/_course.htm

Hey one question `difference` -> 0.5*(No. of tosses) – no. of heads is it correct?

@Nikhil …Thanks for bringing it to the notice. It should be no.of heads – 0.5(No.of tosses).

Did you miss the index i of A in the general formula of the Bayes’ theorem on the left hand side of the equation (section 3.2)?

No, I didn’t. ðŸ™‚

Nice visual to represent Bayes theorem, thanks

Thanks Bharath…… It keeps us motivated.

I will let you know tomorrow! Because tomorrow I have to do teaching assistance in a class on Bayesian statistics. I will try to explain it your way, then I tell you how it worked out.

For me it looks perfect! Thanks!

Thorough and easy to understand synopsis. Good stuff. Thanks.

It was a really nice article, with nice flow to compare frequentist vs bayesian approach. I will look forward to next part of the tutorials.

Excellent article. I didn’t knew much about Bayesian statistics, however this article helped me improve my understanding of Bayesian statistics.

Without wanting to suggest that one approach or the other is better, I don’t think this article fulfilled its objective of communicating in “simple English”.

The communication of the ideas was fine enough, but if the focus is to be on “simple English” then I think that the terminology needs to be introduced with more care, and mathematical explanations should be limited and vigorously explained.

It’s a good article.

As a beginner I have a few difficulties with the last part (chapter 5) but the previous parts were really good

Very nice refresher. Thank you and keep them coming.

Thank you, NSS for this wonderful introduction to Bayesian statistics. The visualizations were just perfect to establish the concepts discussed. Although I lost my way a little towards the end(Bayesian factor), appreciate your effort!

this ‘stopping intention’ is not a regular thing in frequentist statistics. In fact I only hear about it today. It sort of distracts me from the bayesian thing that is the real topic of this post. Perhaps you never worked with frequentist statistics?

@Roel

Irregularities is what we care about ? Isn’t it ? and well, stopping intentions do play a role. What if as a simple example: person A performs hypothesis testing for coin toss based on total flips and person B based on time duration . Do we expect to see the same result in both the cases ?

Some small notes, but let me make this clear: I think bayesian statistics makes often much more sense, but I would love it if you at least make the description of the frequentist statistics correct. Also let’s not make this a debate about which is better, it’s as useless as the python vs r debate, there is none.

“In this, the t-score for a particular sample from a sampling distribution of fixed size is calculated. Then, p-values are predicted. We can interpret p values as (taking an example of p-value as 0.02 for a distribution of mean 100) : There is 2% probability that the sample will have mean equal to 100.”

This is incorrect. a p-value says something about the population. You inference about the population based on a sample. If mean 100 in the sample has p-value 0.02 this means the probability to see this value in the population under the nul-hypothesis is .02. Which makes it more likely that your alternative hypothesis is true.

“sampling distributions of different sizes, one is bound to get different t-score and hence different p-value. It is completely absurd.”

correct it is an estimation, and you correct for the uncertainty in

I know it makes no sense, we test for an effect by looking at the probabilty of a score when there is no effect. if that is a small change we say that the alternative is more likely.

@Roel

I agree this post isn’t about the debate on which is better- Bayesian or Frequentist.

And I quote again- “The aim of this article was to get you thinking about the different type of statistical philosophies out there and how any single of them cannot be used in every situation”.

Regarding p-value , what you said is correct- Given your hypothesis, the probability……….

But generally, what people infer is – the probability of your hypothesis,given the p-value…..

But, still p-value is not the robust mean to validate hypothesis, I feel.

I would like to hear more.

Thanks for commenting. ðŸ™‚

This is a really good post! Thanks for share this information in a simple way!

I have some questions that I would like to ask!

1) I didn’t understand very well why the C.I. “do not provide the most probable value for a parameter and the most probable values”. Before to read this post I was thinking in this way: the real mean of population is between the range given by the CI with a, for example, 95%)

2) I read a recent paper which states that rejecting the null hypothesis by bayes factor at <1/10 could be equivalent as assuming a p value <0.001 for reject the null hypothesis (actually, I don't remember very well the exact values, but the idea of makeing this equivalence is correct? could be good to apply this equivalence in research?)

3) For making bayesian statistics, is better to use R or Phyton? or it depends on each person? Now I m learning Phyton because I want to apply it to my research (I m biologist!)

Thanks in advance and sorry for my not so good english!

Jose Avila

Hi NSS,

A quick question about section 4.2: If alpha = no. of heads and beta = no. of tail

Why the alpha value = the number of trails in the R code:

> alpha=c(0,2,10,20,50,500) # it looks like the total number of trails, instead of number of heads….

> beta=c(0,2,8,11,27,232)

I plotted the graphs and the second one looks different from yours…

Thanks,

Shane

How can I know when the other posts in this series are released?

Thank you for this Blog. I like it and I understand about concept Bayesian. I can practice in R and I can see something.

I think, you should write the next guide on Bayesian in the next time.

I will wait.

HI…

Good post and keep it up … very useful…

Hi NSS

Thanks for the much needed comprehensive article. Please tell me a thing :-

“Since HDI is a probability, the 95% HDI gives the 95% most credible values. It is also guaranteed that 95 % values will lie in this interval unlike C.I.”

How is this unlike CI? As far as I know CI is the exact same thing.

@Nishtha …. CI is the probability of the intervals containing the population parameter i.e 95% CI would mean 95% of intervals would contain the population parameter whereas in HDI it is the presence of a population parameter in an interval with 95% probability. Both are different things. Hope this helps.