Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Section 5.1 — Introduction to Bayesian statistics

This notebook contains the code examples from Section 5.1 Introduction to Bayesian statistics from the No Bullshit Guide to Statistics.

Notebook setup

Note: you may need to restart the kernel to use updated packages.
<Figure size 640x480 with 0 Axes>

Definitions

Data model and likelihood function

Parameters distributions

Bayesian model

Calculating the posterior distribution

Bayesian inference results

Visualizing the posterior

<Figure size 600x250 with 1 Axes>

Point estimates

  • posterior mean

  • posterior median

  • posterior mode

Bayesian credible interval

  • (1−α)(1-\alpha) high density interval

Bayesian predictions

  • draws form the posterior predictive distribution

Bayesian hypothesis testing

TODO

Bayesian inference

TODO: add explanations and formulas

Bayesian updating of posterior probabilities

<Figure size 500x500 with 3 Axes>

Grid approximation

TODO: add explanations and formulas

TODO: add steps

Pseudocode:

prior_rv = ... # specify the prior distribtion
model = ...    # specify the data model

# 1. Define the grid of possible parameter values
thetas = [0, 0.05, 0.10, 0.15, ..., 1.0]

# 2. Evaluate the prior distribution for all thetas
prior = [prior_rv.pdf(th) for th in thetas]

# 3. Compute the likelihood of the data for all thetas
likelihood = [model(th).pdf(data) for th in thetas]

# 4. Calculate the numerator in Bayes' formula
numerator = np.multiply(likelihood, prior)

# 5. Normalize to obtain the posterior distribution
posterior = numerator / np.sum(numerator)
<Figure size 500x500 with 3 Axes>

Example 1: estimating the probability of a biased coin

Suppose we’re given a biased coin and we want to estimate the probability the coin turns up heads.

Data

We have a sample c=ctosses\mathbf{c} = \texttt{ctosses} that contains n=50n=50 observations (coin tosses) from the coin. The outcome 1 corresponds to heads, while the outcome 0 corresponds to tails.

(34, 50, 0.68)

Model

The Bayesian model for the coin tosses is describe by the Bernoulli distribution with a uniform prior on the parameter:

C∼Bernoulli(P),P∼U(0,1).C \sim \textrm{Bernoulli}(P), \qquad P \sim \mathcal{U}(0,1). \qquad

To estimate the parameter PP, we’ll use the Bayesian inference following the five-step grid approximation procedure.

Step 1: define a grid of possible parameter values

We start by defining a grid for the possible values for the parameter PP. We’ll cover the interval from 0 to 1 using a grid with 100 steps.

array([0. , 0.01, 0.02, 0.03, 0.04])

Step 2: define a flat prior distribution

array([1., 1., 1., 1., 1.])

Step 3: compute the likelihood

Next we want to compute the likelihood of the data ctosses=c=[c1,c2,…,c50]\tt{ctosses} = \mathbf{c} = [c_1,c_2,\ldots,c_{50}] according to the model fC∣P(c∣p)=pc(1−p)1−cf_{C|P}(c|p) = p^c(1-p)^{1-c}.

Recall that the likelihood function is the product of the probabilities for individual observations

Lc(p)=fC∣P(c1∣p) fC∣P(c2∣p) ⋯ fC∣P(c50∣p)=pc1(1−p)1−c1 pc2(1−p)1−c2⋯ pc50(1−p)1−c50=p∑inci(1−p)n−∑inci=py(1−p)n−y,\begin{align*} L_{\mathbf{c}}(p) &= f_{C|P}(c_1|p) \, f_{C|P}(c_2|p) \, \cdots \, f_{C|P}(c_{50}|p) \\ &= p^{c_1}(1-p)^{1-{c_1}} \, p^{c_2}(1-p)^{1-{c_2}} \cdots \, p^{c_{50}} (1-p)^{1-c_{50}} \\ &= p^{\sum_i^n c_i} (1-p)^{n-\sum_i^n c_i} \\ &= p^{y} (1-p)^{n-y}, \end{align*}

where we have defined y=∑inciy = \sum_i^n c_i the total number of heads in the data ctosses=c\tt{ctosses} = \mathbf{c}.

We can use now use this formula to calculate the likelihood of the data for all the values of the parameters PP in the grid ps.

array([0.00000000e+00, 3.39578753e-23, 8.88178420e-16, 1.31559767e-14, 0.00000000e+00])

Step 4: calculate the numerator in Bayes’ formula

Next we multiply the likelihood and the prior to obtain the numerator of the Bayes’ rule formula.

array([0.00000000e+00, 3.39578753e-23, 8.88178420e-16, 1.31559767e-14, 0.00000000e+00])

Step 5: normalize to obtain the posterior distribution

The final step is to make sure the posterior is a valid probability distribution.

array([0.00000000e+00, 8.52710007e-11, 2.23028862e-03, 3.30357328e-02, 0.00000000e+00])

We can verify that the sum of the values in the array posterior1 is 1.

1.0

Visualizing the posterior

<Figure size 500x300 with 1 Axes>

Summarize the posterior

Posterior mean

0.673076923076923

Posterior standard deviation

0.06443431329777005

Posterior median

0.68

Posterior quartiles

(0.63, 0.68, 0.72)

Posterior percentiles

(0.55, 0.79)

Posterior mode

0.68

Credible interval

[0.54, 0.76]

Visualizing the posterior updates over time

<Figure size 600x600 with 10 Axes>

Example 2: estimating the IQ score

Suppose we’re investigating the effect of a new smart drug. We give the drug to a sample of 30 individuals who are representative of the population, then make them take an IQ test.

Data

We have a sample of n=30n=30 IQ measurements from people who took the smart drug.

Model

We will use the following Bayesian model:

X∼N(M,σ=15),M∼N(μM=100,σM=40).X \sim \mathcal{N}(M, \sigma=15), \qquad M \sim \mathcal{N}(\mu_M=100,\sigma_M=40).

We place a broad prior on the mean parameter MM, by choosing a large value for the standard deviation σM\sigma_M. We assume the IQ scores come from a population with known standard deviation σ=15\sigma = 15.

Step 1: define a grid of possible values of the mean

This time we’ll use a finer grid with 1000 steps. The parameter space for the mean of a normal distribution is infinite (−∞,∞)(-\infty, \infty), so we can’t define a grid that covers the whole parameter space. Instead, we’ll define a grid that cover only the most likely values for the mean, which is a window of ±20\pm 20 around the mean of the wider population.

array([80. , 80.04, 80.08, 80.12, 80.16])

Step 2: define the prior for the unknown mean

We define a normal distribution centered at μM=100\mu_M=100 with standard deviation σM=40\sigma_M=40, then evaluate it for each point in the grid mus.

array([0.00880163, 0.00977607, 0.00992381, 0.00920675])

Step 3: compute the likelihood of the data

TODO: show formula

TODO: explain iterative calculation

array([1.23613569e-77, 1.80497559e-62, 1.20898934e-55, 3.71466415e-57])

Steps 4: calculate the numerator in Bayes’ rule formula

array([1.08800129e-79, 1.76455630e-64, 1.19977849e-57, 3.41999972e-59])

Steps 5: normalize to obtain the posterior distribution

array([2.02698373e-25, 3.28742893e-10, 2.23522850e-03, 6.37157683e-05])

Visualizing the posterior

<Figure size 500x300 with 1 Axes>

Summarize the posterior

Posterior mean

107.78678422532585

Posterior standard deviation

2.7321084402431834

Posterior median

107.8

Posterior mode

107.8

Credible interval for the mean

[103.16, 112.16]

Let’s compare the Bayesian credible interval to the frequentist confidence interval.

[102.83429390645762, 112.81237276020906]

Explanations

Grid approximation details

Choosing priors

(107.82333333333334, [102.83429390645762, 112.81237276020906])
<Figure size 650x260 with 2 Axes>
Loading...

Bayesian predictions

Predicting future coin tosses

[0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1]

Predicting IQ scores

array([ 89.64, 110.31, 112.65, 121.25, 92.55, 132.49, 98.97])

Bayesian hypothesis testing

Suppose we want to evaluate whether the IQ data measurements iqs comes from a population with a mean μ0=100\mu_0=100 or not, which corresponds to the null hypothesis (the smart drug was not effective).

Using credible intervals for decisions

Consider the null hypothesis H0:μ=100H_0: \mu=100. We can informally reject this hypothesis, since the value μ=100\mu=100 is outside the 90% credible interval.

[102.32, 113.03999999999999]

Region of practical equivalence

We can also compute the total probability of in the posterior that falls within the region of practical equivalence (ROPE) [97,103][97,103].

0.040481237454239115

Hypothesis test

We see the probability of μ=100\mu=100 or smaller is around 0.21%0.21\%, which gives us reason to reject H0H_0.

This conclusion is consistent with the conclusion of the frequentist one-sample tt-test, which leads us to reject H0H_0.

(2.664408108831371, 0.006232014580899188)

Bayesian model comparison

In Bayesian model comparison, we want compare the posterior probability distributions of two models:

The null hypothesis is H0:μ=μ0=100H_0: \mu = \mu_0 = 100 while the alternative hypothesis H1:μ≠100H_1: \mu \neq 100. Actually, we need to be more specific and show the full Bayesian model under each distribution:

Under H0

...

Under H1

...

Bayes factors

TODO: show formulas

Test 1: using a point null and Cauchy on effect size

5.415023175654286e-57

We’ll set a prior on the effect size Δ=μ/σ\Delta = \mu / \sigma, using the Cauchy distribution (very fat tails).

<Figure size 500x300 with 1 Axes>
3.647361365721922e-56
6.7356338974139645
3.649465841847485e-56
6.739520263284058

Test 2: using the default Jeffrey-Zellner-Siow (JZS) prior

H0:μ=100,HA:μ−100σ∼Cauchy(r),σ∼JeffreysH_0: \mu = 100, \qquad H_A: \frac{\mu - 100}{\sigma} \sim \textrm{Cauchy}(r), \sigma \sim \textrm{Jeffreys}
Bayes Factor (BF_A0): 3.720150734157743
'3.74'
3.7397058298821895
TtestResult(statistic=2.664408108831371, pvalue=0.012464029161798377, df=29)

Discussion

Maximum a posteriori estimates

Comparing Bayesian and frequentist approaches to statistical inference

Strengths and weaknesses of Bayesian approach

Sampling from the posterior (BONUS TOPIC)

We’ll now show how to analyze the Bayesian analysis when the posterior distribution is available in the form of samples. This will be the form of analysis in all the future sections of the chapter, so I thought I can give you a little preview.

We start by generating some samples from the posterior distribution we obtained in Example 2.

<Figure size 500x300 with 1 Axes>

Posterior mean

To compute the mean of the posterior, we compute the mean of the samples.

107.73182

In the next seciton, we’ll also learn about the ArviZ library, which is a Swiss Army knife for for summarizing, visualizing, and plotting the Bayesian analysis results. For example, we can obtain the mean using the summary function from the ArviZ library.

Loading...

The summary also includes the posterior standard deviation and the limits of a “94% high density interval” that contains 94% of the posterior probability density.

Posterior standard deviation

To compute the standard deviation of the posterior, we compute the standard deviation of the samples.

2.712109726320084

Posterior median

To compute the median of the posterior, we compute the median of the samples.

107.72

We can also obtain median using the ArviZ summary function, if we specify the stat_focus option.

Loading...

Credible interval

[103.28, 112.16]
Loading...

Exercises

Exercise 1: campaign conversions

See explorations/bayesianprobabilitiesworkshop/Exercise%201.ipynb

TODO: check this

Exercise 2: apply Bayes rule for a diagnostic test

You have designed a new test for detecting lung cancer that has the following characteristics:

  • Test gives a positive result 98%98\% of the time when lung cancer is present.

  • Test gives a negative result 96%96\% of the time when no lung cancer is present.

You also know that that in the general population, there is approximately one case of lung cancer per 1000 individuals.

Use Bayes rule to calculate the probability that a person who gets a positive test result has cancer, and interpret the result.

0.02393746946751343
0.9760625305324866

The above calculation tells us 97.6% of people who test positive don’t actually have cancer. We shouldn’t be screening to the whole population, since that would lead to too many people getting scared for nothing. See the visualization tool at https://sophieehill.shinyapps.io/base-rate-viz/ to learn more about the base rate fallacy.

Exercise: algae

see assignment2 from the BDA course

TODO