Data Science

Going Bayesian: Testing Rate Metrics

How to run an A/B test for rate metrics without p-values and confidence intervals.

Artemis N.
February 13, 20218 min read

Getting Started

Bayesian A/B Test for Rate Metrics

Photo by Brianna Santellan on Unsplash
Photo by Brianna Santellan on Unsplash

Have you ever struggled trying to explain your Frequentist test results (namely null/alternative hypothesis, p-values and confidence intervals) to a non-technical audience or... even yourself? Do you wish you could just say "there's a 95% probability group A has a better click-through rate than group B" after running an A/B test and be done with it? If yes, then you have landed on the right post, if not we have pictures of cute dogs so you might want to stay anyway!


You are working as a Data Scientist for WoofWoof, a dog toy company. The Marketing Department wants to run a new digital advertising campaign and they are trying to decide whether they should use the picture of a corgi or a pug in it. Quickly, you suggest running an A/B test, where you will present the version with the corgi to one group of people and the version with the pug to another group of people and see which one does better in terms of click-through rate. The Marketing Department agrees, and you set off to refresh your memory on how to actually analyse the data.

We will go through the theory and steps that you need to run the A/B test, the Bayes way. We will implement everything in Python.

Photo by Braydon Anderson on Unsplash
Photo by Braydon Anderson on Unsplash

You Need Bayes Theorem

The title kind of gives it away, but you need to be familiar with Bayes Theorem. Bayes Theorem gives us a way to model how our prior belief about something changes after observing new data.

text
Bayes Theorem P(A|B) = P(B|A) P(A) / P(B)
text
where A, B: events in sample space P(A|B): conditional probability of A given B P(B|A): conditional probability of B given A P(A): probability of A P(B): probability of B

The above definition is for discrete variables, for continuous variables it is defined for probability density functions.

In our example we care about the click-through rate, let's denote that by πœƒ. We will denote our prior belief about πœƒ as πœ‹(πœƒ) - this is the prior distribution on the parameter of interest. Next, after running the experiment we will observe data, 𝛸. The likelihood function f(𝛸|πœƒ) tells us how likely it is to observe the data, 𝛸, given different values of πœƒ. What we really care about is πœ‹(πœƒ|𝛸), i.e. the posterior distribution for πœƒ. This basically says how likely different values of πœƒ are after taking into account the data we have observed and our prior belief. We can get to πœ‹(πœƒ|𝛸) using Bayes Theorem.

text
πœ‹(πœƒ|𝛸) = f(𝛸|πœƒ)πœ‹(πœƒ) / f(𝛸)        ~ f(𝛸|πœƒ)πœ‹(πœƒ)
text
where  f(𝛸): probability density of 𝛸 (can think of it as a normalising constant)

In general, we have

text
posterior ~ likelihood x prior.

The Prior: Beta Distribution

The prior is meant to capture any prior knowledge we have on likely values for our click-through rate. If you have no idea, you can choose an uninformative prior, for example, that all possible values are equally likely. Whatever the case, one thing is certain: rate metrics can only take values between 0 and 1! Therefore, we need a prior distribution that reflects that, such as the Beta distribution.

The Beta distribution has two parameters you can play with, 𝛼 >0 and 𝛽>0 ( aand bin Figure 1). Let's look at some plots to get some intuition on how they affect the shape of the density function.

Figure 1. Beta distribution for different parameter values. Image by the author.
Figure 1. Beta distribution for different parameter values. Image by the author.

You may have already noticed a pattern in Figure 1. The peak of the distribution is at (𝛼-1)/(𝛼+𝛽-2) - this is actually the mode of the distribution. Also, the larger 𝛼 and 𝛽 become the more concentrated the values are around the mode (look at the diagonal in Figure 1).

In fact, you can think of 𝛼-1 as the number of successes and 𝛽-1 as the number of failures. Then, the mode (𝛼-1)/(𝛼+𝛽-2) can be thought of as successes / trials. Therefore, if we want a prior that gives more weight to values of πœƒ around 0.5 like we ran an experiment and got 20 successes (clicks) and 20 failures (no clicks), we can choose 𝛼=21 and 𝛽=21. If we want an uninformative prior we can choose 𝛼=1 and 𝛽=1 - there's obviously no mode in this case.

Bear in mind that the stronger your prior is, i.e. very big 𝛼 and 𝛽, the more data we will need to move away from it.

The Likelihood: Binomial Distribution

The likelihood tells us how likely it is to observe the data, 𝛸, given different values of πœƒ. Since we are working with rate metrics, which means we have trials (impressions of our digital ads) and successes (clicked ads), the Binomial distribution fits nicely.

As a reminder, the Binomial(𝜈, πœƒ) distribution models the probability of πœ… successes from 𝜈 trials when the probability of success is equal to πœƒ (usually the probability of success is denoted as p ).``

Image by the author.
Image by the author.

The Posterior: ?

We've chosen a Beta distribution as our prior and a Binomial distribution as our likelihood. What could our posterior possibly be hmm... (you are probably already imagining horrible math calculations).

It turns out our posterior is a Beta distribution too! This isn't an accident, of course. This Beta-Binomial prior-likelihood combo is chosen often because they are conjugate priors. Conjugate priors simply mean that when you combine them, the posterior distribution ends up being from the same distribution family as the prior.

text
If  Prior is Beta(𝛼, 𝛽)  Likelihood is Binomial(𝜈, πœƒ)Then  Posterior is Beta(𝛼 + successes, 𝛽 + failures)Where  𝜈 = successes + failures

So all we need to do is choose 𝛼 and 𝛽 for our prior, run our experiment, collect the data and then calculate our posterior, which is again a Beta distribution with parameters 𝛼+successes, 𝛽+failures. Easy!

The plan for our A/B test is to give both groups the same prior and then use Bayes theorem to calculate their posterior distributions. Once we have the posteriors we can do interesting comparisons to find and declare the winner.

Test Implementation

We are interested in the probability that Group A (Corgi Ad) is better than Group B (Pug Ad) in terms of click-through rate (CTR), i.e.

text
P(corgi CTR - pug CTR > margin)

where the margin could be 0 or some other value that we care about. This is basically answering the question "what's the probability that the CTR of the corgi ad is at least margin greater than the CTR of the pug ad"?

We are going to find the answer by sampling from the posterior distributions for each group's click-through rate. The process is the following:

text
Set N to some big number (e.g. 10000)Set differences = []
text
for i = 1 to N:   a_sample = sample a value from group's A posterior   b_sample = sample a value from group's B posterior   a_b_diff = a_sample - b_sample
text
   store a_b_diff in differences
text
P(A - B > margin) β‰ˆ % of values in differences that are greater than margin

In our implementation, we will be using a vectorised approach instead of for loops as it faster.

This may look like a lot of code but most of it is just for creating some plots. Lines 23 to 35 are the important ones, where we sample from the posteriors and calculate the distribution of differences.

There's another way you can use the posteriors to conclude your experiment which we haven't implemented here. It involves calculating the highest density interval (HDI) of the posterior distribution of differences (the shortest interval such that the probability of values in it is equal to x% ) and checking whether it overlaps a predefined region of practical equivalence (ROPE). For example, we might define ROPE to be [-0.005, 0.005], which means we consider differences between the two groups in that range to be negligible. After calculating the posterior distribution of differences, the next step is to calculate the 95% HDI (what percentage you actually use is up to you). If the HDI does not intersect our ROPE we conclude that the two groups are different.

Who is the Cutest of Them All?

Photo by Florencia Potter on Unsplash
Photo by Florencia Potter on Unsplash

The A/B test is underway and the Marketing Department is already asking you to analyse the data.

text
Corgi group  Impressions: 9760  Clicks: 3660
text
Pug group  Impressions: 9344  Clicks: 3420

Using the code from the previous section, you can simply do the following

text
GROUP_A = 'Corgi'GROUP_B = 'Pug'
text
ab_test = BetaBinomialTest(GROUP_A, GROUP_B)ab_test.update_group_data(GROUP_A, successes=3660, trials=9760)ab_test.update_group_data(GROUP_B, successes=3420, trials=9344)
text
prob, differences = ab_test.compare(GROUP_A, GROUP_B, margin=0.0)

to quickly get an answer.

Left plot: distribution of differences. Right plot: posterior distributions for click-through rates. Image by the author.
Left plot: distribution of differences. Right plot: posterior distributions for click-through rates. Image by the author.

You go back to the Marketing Department and let them know that there's about a 90% probability that the corgi version works better than the pug one. At this point, they might decide that 90% is good enough and go with corgies or decide to continue the experiment to collect more data and become more certain.

What about Other Metrics?

If you've reached this point you might be wondering what happens when you want to use a Bayesian A/B test for non-rate metrics. There are more pairs of distributions that are conjugate priors and therefore can be used easily. If those fit your data then you are in luck - the methodology will be very similar to what we saw in this article. Otherwise, you might need to use packages for Bayesian inference, like PyStan, to create an approximation of the posterior distributions for you.

Conclusion

In this article, we went through the theory of running an A/B test for rate metrics using Bayes Theorem. We have looked at how to implement the test in Python and saw that having the posterior distributions for the groups allows us to calculate probabilities for different questions (different values for margin).

We have also concluded that corgis are cuter than pugs and that this author is biased (if you haven't noticed, there are zero pictures of pugs in this article).


More from the same author.

Calculating 𝛑 Using Monte-Carlo SimulationsAn _intro to Monte-Carlo simulations with Python code.me_dium.com

Multi-Armed Bandits: Epsilon-Greedy Algorithm with Python Code


References

[1] "Bayes' theorem," Wikipedia. [Online]. Available: https://en.wikipedia.org/wiki/Bayes%27_theorem. [Accessed: 07-Feb-2021]

[2] Baye's Theorem. [Online]. Available: http://galton.uchicago.edu/~eichler/stat24600/Handouts/l06.pdf. [Accessed: 07-Feb-2021]

[3] A. Kim, "Conjugate Prior Explained," Medium, 16-Jan-2020. [Online]. Available: https://towardsdatascience.com/conjugate-prior-explained-75957dc80bfb. [Accessed: 13-Feb-2021]

[4] John K. Kruschke. 2010. Doing Bayesian Data Analysis: A Tutorial with R and BUGS (1st. ed.). Academic Press, Inc., USA.

Related Articles