An Introduction to Bayesian Statistical Analysis

Before we jump in to model-building and using MCMC to do wonderful things, it is useful to understand a few of the theoretical underpinnings of the Bayesian statistical paradigm. A little theory (and I do mean a little) goes a long way towards being able to apply the methods correctly and effectively.

There are several introductory references to Bayesian statistics that go well beyond what we will cover here.

What is Bayesian Statistical Analysis?

Though many of you will have taken a statistics course or two during your undergraduate (or graduate) education, most of those who have will likely not have had a course in Bayesian statistics. Most introductory courses, particularly for non-statisticians, still do not cover Bayesian methods at all, except perhaps to derive Bayes' formula as a trivial rearrangement of the definition of conditional probability. Even today, Bayesian courses are typically tacked onto the curriculum, rather than being integrated into the program.

In fact, Bayesian statistics is not just a particular method, or even a class of methods; it is an entirely different paradigm for doing statistical analysis.

Practical methods for making inferences from data using probability models for quantities we observe and about which we wish to learn. -- Gelman et al. 2013

A Bayesian model is described by parameters, uncertainty in those parameters is described using probability distributions.

All conclusions from Bayesian statistical procedures are stated in terms of probability statements

This confers several benefits to the analyst, including:

  • ease of interpretation, summarization of uncertainty
  • can incorporate uncertainty in parent parameters
  • easy to calculate summary statistics

Bayesian vs Frequentist Statistics: What's the difference?

See the VanderPlas talk on Tuesday.

Any statistical paradigm, Bayesian or otherwise, involves at least the following:

  1. Some unknown quantities about which we are interested in learning or testing. We call these parameters.
  2. Some data which have been observed, and hopefully contain information about (1).
  3. One or more models that relate the data to the parameters, and is the instrument that is used to learn.

The Frequentist World View

  • The data that have been observed are considered random, because they are realizations of random processes, and hence will vary each time one goes to observe the system.
  • Model parameters are considered fixed. The parameters' values are unknown, but they are fixed, and so we condition on them.

In mathematical notation, this implies a (very) general model of the following form:

\\[f(y | \theta)\\]

Here, the model $f$ accepts data values $y$ as an argument, conditional on particular values of $\theta$.

Frequentist inference typically involves deriving estimators for the unknown parameters. Estimators are formulae that return estimates for particular estimands, as a function of data. They are selected based on some chosen optimality criterion, such as unbiasedness, variance minimization, or efficiency.

For example, lets say that we have collected some data on the prevalence of autism spectrum disorder (ASD) in some defined population. Our sample includes $n$ sampled children, $y$ of them having been diagnosed with autism. A frequentist estimator of the prevalence $p$ is:

\\[\hat{p} = \frac{y}{n}\\]

Why this particular function? Because it can be shown to be unbiased and minimum-variance.

It is important to note that new estimators need to be derived for every estimand that is introduced.

The Bayesian World View

  • Data are considered fixed. They used to be random, but once they were written into your lab notebook/spreadsheet/IPython notebook they do not change.
  • Model parameters themselves may not be random, but Bayesians use probability distribtutions to describe their uncertainty in parameter values, and are therefore treated as random. In some cases, it is useful to consider parameters as having been sampled from probability distributions.

This implies the following form:

\\[p(\theta | y)\\]

This formulation used to be referred to as inverse probability, because it infers from observations to parameters, or from effects to causes.

Bayesians do not seek new estimators for every estimation problem they encounter. There is only one estimator for Bayesian inference: Bayes' Formula.

Bayesian Inference, in 3 Easy Steps

Gelman et al. (2013) describe the process of conducting Bayesian statistical analysis in 3 steps.

Step 1: Specify a probability model

As was noted above, Bayesian statistics involves using probability models to solve problems. So, the first task is to completely specify the model in terms of probability distributions. This includes everything: unknown parameters, data, covariates, missing data, predictions. All must be assigned some probability density.

This step involves making choices.

  • what is the form of the sampling distribution of the data?
  • what form best describes our uncertainty in the unknown parameters?

Step 2: Calculate a posterior distribution

The mathematical form $p(\theta | y)$ that we associated with the Bayesian approach is referred to as a posterior distribution.

posterior /pos·ter·i·or/ (pos-tēr´e-er) later in time; subsequent.

Why posterior? Because it tells us what we know about the unknown $\theta$ after having observed $y$.

This posterior distribution is formulated as a function of the probability model that was specified in Step 1. Usually, we can write it down but we cannot calculate it analytically. In fact, the difficulty inherent in calculating the posterior distribution for most models of interest is perhaps the major contributing factor for the lack of widespread adoption of Bayesian methods for data analysis. Various strategies for doing so comprise this tutorial.

But, once the posterior distribution is calculated, you get a lot for free:

  • point estimates
  • credible intervals
  • quantiles
  • predictions

Step 3: Check your model

Though frequently ignored in practice, it is critical that the model and its outputs be assessed before using the outputs for inference. Models are specified based on assumptions that are largely unverifiable, so the least we can do is examine the output in detail, relative to the specified model and the data that were used to fit the model.

Specifically, we must ask:

  • does the model fit data?
  • are the conclusions reasonable?
  • are the outputs sensitive to changes in model structure?

Why be Bayesian?

At this point, it is worth addressing the question of why one might consider an alternative statistical paradigm to the classical/frequentist statistical approach. After all, it is not always easy to specify a full probabilistic model, nor to obtain output from the model once it is specified. So, why bother?

... the Bayesian approach is attractive because it is useful. Its usefulness derives in large measure from its simplicity. Its simplicity allows the investigation of far more complex models than can be handled by the tools in the classical toolbox.
-- Link and Barker 2010

We already noted that there is just one estimator in Bayesian inference, which lends to its simplicity. Moreover, Bayes affords a conceptually simple way of coping with multiple parameters; the use of probabilistic models allows very complex models to be assembled in a modular fashion, by factoring a large joint model into the product of several conditional probabilities.

Bayesian statistics is also attractive for its coherence. All unknown quantities for a particular problem are treated as random variables, to be estimated in the same way. Existing knowledge is given precise mathematical expression, allowing it to be integrated with information from the study dataset, and there is formal mechanism for incorporating new information into an existing analysis.

Finally, Bayesian statistics confers an advantage in the iterpretability of analytic outputs. Because models are expressed probabilistically, results can be interpreted probabilistically. Probabilities are easy for users (particularly non-technical users) to understand and apply.

Example: confidence vs. credible intervals

A commonly-used measure of uncertainty for a statistical point estimate in classical statistics is the confidence interval. Most scientists were introduced to the confidence interval during their introductory statistics course(s) in college. Yet, a large number of users mis-interpret the confidence interval.

Here is the mathematical definition of a 95% confidence interval for some unknown scalar quantity that we will here call $\theta$:

\\[Pr(a(Y) < \theta < b(Y) | \theta) = 0.95\\]

how the endpoints of this interval are calculated varies according to the sampling distribution of $Y$, but for as an example, the confidence interval for the population mean when $Y$ is normally distributed is calculated by:

$$Pr(\bar{Y} - 1.96\frac{\sigma}{\sqrt{n}}< \theta < \bar{Y} + 1.96\frac{\sigma}{\sqrt{n}}) = 0.95$$

It would be tempting to use this definition to conclude that there is a 95% chance $\theta$ is between $a(Y)$ and $b(Y)$, but that would be a mistake.

Recall that for frequentists, unknown parameters are fixed, which means there is no probability associated with them being any value except what they are fixed to. Here, the interval itself, and not $\theta$ is the random variable. The actual interval calculated from the data is just one possible realization of a random process, and it must be strictly interpreted only in relation to an infinite sequence of identical trials that might be (but never are) conducted in practice.

A valid interpretation of the above would be:

If the experiment were repeated an infinite number of times, 95% of the calculated intervals would contain $\theta$.

This is what the statistical notion of "confidence" entails, and this sets it apart from probability intervals.

Since they regard unknown parameters as random variables, Bayesians can and do use probability intervals to describe what is known about the value of an unknown quantity. These intervals are commonly known as credible intervals.

The definition of a 95% credible interval is:

\\[Pr(a(y) < \theta < b(y) | Y=y) = 0.95\\]

Notice that we condition here on the data $y$ instead of the unknown $\theta$. Thus, the endpoints are fixed and the variable is random.

We are allowed to interpret this interval as:

There is a 95% chance $\theta$ is between $a$ and $b$.

Hence, the credible interval is a statement of what we know about the value of $\theta$ based on the observed data.

Probability

Misunderstanding of probability may be the greatest of all impediments to scientific literacy. — Stephen Jay Gould

Because of its reliance on probabilty models, its worth talking a little bit about probability. There are three different ways to define probability, depending on how it is being used.

1. Classical probability

\\[Pr(X=x) = \frac{\text{# x outcomes}}{\text{# possible outcomes}}\\]

Classical probability is an assessment of possible outcomes of elementary events. Elementary events are assumed to be equally likely.

2. Frequentist probability

\\[Pr(X=x) = \lim_{n \rightarrow \infty} \frac{\text{# times x has occurred}}{\text{# independent and identical trials}}\\]

Unlike classical probability, frequentist probability is an EMPIRICAL definition. It is an objective statement desribing events that have occurred.

3. Subjective probability

\\[Pr(X=x)\\]

Subjective probability is a measure of one's uncertainty in the value of $X$. It characterizes the state of knowledge regarding some unknown quantity using probability.

It is not associated with long-term frequencies nor with equal-probability events.

For example:

  • X = the true prevalence of diabetes in Austin is < 15%
  • X = the blood type of the person sitting next to you is type A
  • X = the Nashville Predators will win next year's Stanley Cup
  • X = it is raining in Nashville

Probability distributions

Bayesian inference uses probability distributions as building blocks for specifying models. They are used to assign uncertainty to unknown parameters, or sampling distributions to data.

Probability distributions assign probabilities to each possible outcome or value of a particular variable. Probabilities must be positive, and the sum (or integral) of the probabilities of all possible values must be 1.

There are two distinct classes of distributions, determined by whether the variable being described is discrete or continuous.

Discrete Probability Distributions

$$X = \{0,1\}$$$$Y = \{\ldots,-2,-1,0,1,2,\ldots\}$$

Probability Mass Function:

For discrete $X$,

$$Pr(X=x) = f(x|\theta)$$

e.g. Poisson distribution

The Poisson distribution models unbounded counts:

$$Pr(X=x)=\frac{e^{-\lambda}\lambda^x}{x!}$$
  • $X=\{0,1,2,\ldots\}$
  • $\lambda > 0$
$$E(X) = \text{Var}(X) = \lambda$$

In [1]:
%matplotlib inline
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt

theta = 3
x = np.random.poisson(theta, size=1000)
x.mean(), x.var()


Out[1]:
(2.9500000000000002, 3.1594999999999929)

In [2]:
_ = plt.hist(x, bins=30)



In [3]:
y = stats.poisson.pmf(range(10), theta)
plt.plot(y, 'ro')


Out[3]:
[<matplotlib.lines.Line2D at 0x112dd3b90>]

Continuous Random Variables

$$X \in [0,1]$$$$Y \in (-\infty, \infty)$$

Probability Density Function:

For continuous $X$,

$$Pr(x \le X \le x + dx) = f(x|\theta)dx \, \text{ as } \, dx \rightarrow 0$$

e.g. normal distribution

$$f(x) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp\left[-\frac{(x-\mu)^2}{2\sigma^2}\right]$$
  • $X \in \mathbf{R}$
  • $\mu \in \mathbf{R}$
  • $\sigma>0$
$$\begin{align}E(X) &= \mu \cr \text{Var}(X) &= \sigma^2 \end{align}$$

In [4]:
mu, sig = 10, 3

x = np.random.normal(mu, sig, 1000)
x.mean(), x.std()


Out[4]:
(9.9980174423479724, 2.990905875326102)

In [5]:
_ = plt.hist(x, bins=30)



In [6]:
xvals = np.linspace(-10, 30)
y = stats.norm.pdf(xvals, mu, sig)
plt.plot(xvals, y, 'ro')


Out[6]:
[<matplotlib.lines.Line2D at 0x112e65fd0>]

As a reference, the PyMC provides a description of most of the commonly-encountered probability distibutions used in statistical analysis.


In [1]:
from IPython.display import HTML
HTML('<iframe src=http://pymc-devs.github.io/pymc/distributions.html width=900 height=350></iframe>')


Out[1]:

Bayes' Formula

Now that we have some probability under our belt, we turn to Bayes' formula. This, as you recall, is the engine that allows us to obtain estimates of unknown quantities that we care about, using information retained by the data we observe. It turns out to be quite simple to derive Bayes' formula directly from the definition of conditional probability.

Again, the goal in Bayesian inference is to calculate the posterior distribution of our unknowns:

\\[Pr(\theta|Y=y)\\]

This expression is a conditional probability. It is the probability of $\theta$ given the observed values of $Y=y$.

In general, the conditional probability of A given B is defined as follows:

$$Pr(B|A) = \frac{Pr(A \cap B)}{Pr(A)}$$

To gain an intuition for this, it is helpful to use a Venn diagram:

Notice from this diagram that the following conditional probability is also true:

$$Pr(A|B) = \frac{Pr(A \cap B)}{Pr(B)}$$

These can both be rearranged to be expressions of the joint probability of A and B. Setting these equal to one another:

$$Pr(B|A)Pr(A) = Pr(A|B)Pr(B)$$

Then rearranging:

$$Pr(B|A) = \frac{Pr(A|B)Pr(B)}{Pr(A)}$$

This is Bayes' formula. Replacing the generic A and B with things we care about reveals why Bayes' formula is so important:

The equation expresses how our belief about the value of $\theta$, as expressed by the prior distribution $P(\theta)$ is reallocated following the observation of the data $y$, as expressed by the posterior distribution the posterior distribution.

The innocuous denominator $P(y)$ cannot be calculated directly, and is actually the expression in the numerator, integrated over all $\theta$:

\\[Pr(\theta|y) = \frac{Pr(y|\theta)Pr(\theta)}{\int Pr(y|\theta)Pr(\theta) d\theta}\\]

The intractability of this integral is one of the factors that has contributed to the under-utilization of Bayesian methods by statisticians.

Priors

Once considered a controversial aspect of Bayesian analysis, the prior distribution characterizes what is known about an unknown quantity before observing the data from the present study. Thus, it represents the information state of that parameter. It can be used to reflect the information obtained in previous studies, to constrain the parameter to plausible values, or to represent the population of possible parameter values, of which the current study's parameter value can be considered a sample.

Likelihood functions

The likelihood represents the information in the observed data, and is used to update prior distributions to posterior distributions. This updating of belief is justified becuase of the likelihood principle, which states:

Following observation of $y$, the likelihood $L(\theta|y)$ contains all experimental information from $y$ about the unknown $\theta$.

Bayesian analysis satisfies the likelihood principle because the posterior distribution's dependence on the data is only through the likelihood. In comparison, most frequentist inference procedures violate the likelihood principle, because inference will depend on the design of the trial or experiment.

What is a likelihood function? It is closely related to the probability density (or mass) function. Taking a common example, consider some data that are binomially distributed (that is, they describe the outcomes of $n$ binary events). Here is the binomial sampling distribution:

$$p(Y|\theta) = {n \choose y} \theta^{y} (1-\theta)^{n-y}$$

We can code this easily in Python:


In [8]:
from scipy.misc import comb

pbinom = lambda y, n, p: comb(n, y) * p**y * (1-p)**(n-y)

This function returns the probability of observing $y$ events from $n$ trials, where events occur independently with probability $p$.


In [9]:
pbinom(3, 10, 0.5)


Out[9]:
0.1171875

In [10]:
pbinom(1, 25, 0.5)


Out[10]:
7.4505805969238281e-07

In [11]:
yvals = range(10+1)
plt.plot(yvals, [pbinom(y, 10, 0.5) for y in yvals], 'ro')


Out[11]:
[<matplotlib.lines.Line2D at 0x112db1f90>]

What about the likelihood function?

The likelihood function is the exact same form as the sampling distribution, except that we are now interested in varying the parameter for a given dataset.


In [12]:
pvals = np.linspace(0, 1)
y = 4
plt.plot(pvals, [pbinom(y, 10, p) for p in pvals])


Out[12]:
[<matplotlib.lines.Line2D at 0x112da8b50>]

So, though we are dealing with the same equation, these are entirely different functions; the distribution is discrete, while the likelihood is continuous; the distribtion's range is from 0 to 10, while the likelihood's is 0 to 1; the distribution integrates (sums) to one, while the likelhood does not.

Example: Genetic probabilities

Let's put Bayesian inference into action using a very simple example. I've chosen this example because it is one of the rare occasions where the posterior can be calculated by hand. We will show how data can be used to update our belief in competing hypotheses.

Hemophilia is a rare genetic disorder that impairs the ability for the body's clotting factors to coagualate the blood in response to broken blood vessels. The disease is an x-linked recessive trait, meaning that there is only one copy of the gene in males but two in males, and the trait can be masked by the dominant allele of the gene.

This implies that males with 1 gene are affected, while females with 1 gene are unaffected, but carriers of the disease. Having 2 copies of the disease is fatal, so this genotype does not exist in the population.

In this example, consider a woman whose mother is a carrier (because her brother is affected) and who marries an unaffected man. Let's now observe some data: the woman has two consecutive (non-twin) sons who are unaffected. We are interested in determining if the woman is a carrier.

To set up this problem, we need to set up our probability model. The unknown quantity of interest is simply an indicator variable $W$ that equals 1 if the woman is affected, and zero if she is not. We are interested in the probability that the variable equals one, given what we have observed:

$$Pr(W=1 | s_1=0, s_2=0)$$

Our prior information is based on what we know about the woman's ancestry: her mother was a carrier. Hence, the prior is $Pr(W=1) = 0.5$. Another way of expressing this is in terms of the prior odds, or:

$$O(W=1) = \frac{Pr(W=1)}{Pr(W=0)} = 1$$

Now for the likelihood: The form of this function is:

$$L(W | s_1=0, s_2=0)$$

This can be calculated as the probability of observing the data for any passed value for the parameter. For this simple problem, the likelihood takes only two possible values:

$$\begin{aligned} L(W=1 &| s_1=0, s_2=0) = (0.5)(0.5) = 0.25 \cr L(W=0 &| s_1=0, s_2=0) = (1)(1) = 1 \end{aligned}$$

With all the pieces in place, we can now apply Bayes' formula to calculate the posterior probability that the woman is a carrier:

$$\begin{aligned} Pr(W=1 | s_1=0, s_2=0) &= \frac{L(W=1 | s_1=0, s_2=0) Pr(W=1)}{L(W=1 | s_1=0, s_2=0) Pr(W=1) + L(W=0 | s_1=0, s_2=0) Pr(W=0)} \cr &= \frac{(0.25)(0.5)}{(0.25)(0.5) + (1)(0.5)} \cr &= 0.2 \end{aligned}$$

Hence, there is a 0.2 probability of the woman being a carrier.

Its a bit trivial, but we can code this in Python:


In [13]:
prior = 0.5
p = 0.5

L = lambda w, s: np.prod([(1-i, p**i * (1-p)**(1-i))[w] for i in s])

In [14]:
s = [0,0]

post = L(1, s) * prior / (L(1, s) * prior + L(0, s) * (1 - prior))
post


Out[14]:
0.20000000000000001

Now, what happens if the woman has a third unaffected child? What is our estimate of her probability of being a carrier then?

Bayes' formula makes it easy to update analyses with new information, in a sequential fashion. We simply assign the posterior from the previous analysis to be the prior for the new analysis, and proceed as before:


In [15]:
L(1, [0])


Out[15]:
0.5

In [16]:
s = [0]
prior = post

L(1, s) * prior / (L(1, s) * prior + L(0, s) * (1 - prior))


Out[16]:
0.11111111111111112

Thus, observing a third unaffected child has further reduced our belief that the mother is a carrier.


References

Gelman A, Carlin JB, Stern HS, Dunson DB, Vehtari A, Rubin DB. Bayesian Data Analysis, Third Edition. CRC Press; 2013.


In [17]:
from IPython.core.display import HTML
def css_styling():
    styles = open("styles/custom.css", "r").read()
    return HTML(styles)
css_styling()


Out[17]: