Skip to main content

7. Introduction to Bayesian inference

Bayesian inference makes direct probability statements about unknown parameters: given the data, how probable are the different possible values? In frequentist statistics, we instead construct an estimator and describe how it would vary if we repeated the sampling, which leads to hypothesis tests. A Bayesian analysis can state how probable a hypothesis is, without a binary decision to reject or keep it. Its basis is Bayes’ rule, which follows directly from conditional probabilities. In this lab, we first derive it and then apply it, step by step, to estimate a population parameter from a sample, and compare the result with a frequentist estimate.

This lab builds on the basics of probability, in particular on conditional probabilities and the product rule, and on probability distributions, including how to work with probability distributions in R. Make sure you are familiar with these before you start.

From conditional probability to Bayes’ rule

Recall the definition of conditional probability. For two events \(A\) and \(B\), we can write it in both directions:

\[P(A|B) = \frac{P(A \cap B)}{P(B)} \qquad P(B|A) = \frac{P(A \cap B)}{P(A)}\]

Both contain the same joint probability \(P(A \cap B)\). Solving each for it gives the product rule in its two forms:

\[P(A \cap B) = P(A|B) \cdot P(B) = P(B|A) \cdot P(A)\]

Setting the two expressions equal and dividing by \(P(B)\) gives

\[P(A|B) = \frac{P(B|A) \cdot P(A)}{P(B)}\]

This is Bayes’ rule. It allows us to calculate a conditional probability in one direction from the conditional probability in the opposite direction, together with the marginal probabilities.

Suppose we know \(P(A)\) and \(P(B|A)\) and want the reverse conditional probability \(P(A|B)\). Then we also need \(P(B)\). We can calculate it by considering all the possible events \(A_1,\ldots,A_k\) that can occur together with \(B\). Suppose that \(A\) is one of these events, that they are mutually exclusive, and that one of them must occur. Then, whenever \(B\) occurs, exactly one of the events \(A_1,\ldots,A_k\) occurs as well. We can therefore calculate \(P(B)\) by adding the probabilities of the joint events \(B\cap A_1,\ldots,B\cap A_k\). Using the product rule, we write each of them as \(P(B|A_i) \cdot P(A_i)\):

\[P(B) = \sum_{i=1}^{k} P(B \cap A_i) = \sum_{i=1}^{k} P(B|A_i) \cdot P(A_i)\]

This is the total probability of \(B\). Putting it into the denominator gives Bayes’ rule in its general (discrete) form:

\[P(A_j|B) = \frac{P(B|A_j) \cdot P(A_j)}{\sum_{i=1}^{k} P(B|A_i) \cdot P(A_i)}\]

Notice the difference between the numerator and the denominator: the numerator considers only the particular event \(A_j\), whose probability we want to determine, whereas the denominator sums over all possible events \(A_1,\ldots,A_k\).

Bayes’ rule

So far, \(A\) and \(B\) were simply two events, and we could condition either one on the other. In Bayesian inference, this is not the case. Here, Bayes’ rule relates hypotheses \(H_1, \dots, H_k\) to data \(D\), and the two play different roles. A hypothesis is a possible answer to a question about something we cannot observe directly, such as the value of a population parameter. The data, by contrast, are what we observe.

This distinction creates an asymmetry. Given a hypothesis, we can describe how probable the observed data would be under that hypothesis: \(P(D|H)\). What we ultimately want to determine, however, is the reverse conditional probability, \(P(H|D)\): how probable the hypothesis is given the observed data. Since we cannot directly observe which hypothesis is true, we cannot simply count how often it occurs among observations. Bayes’ rule provides the link between these two conditional probabilities, allowing us to update the probability of a hypothesis in light of the observed data.

In terms of hypotheses and data, Bayes’ rule reads:

\[P(H_j|D)=\frac{P(D|H_j)\cdot P(H_j)}{\sum_{i=1}^{k}P(D|H_i)\cdot P(H_i)}\]

  • \(P(H_j|D)\) is the posterior probability, i.e., the probability of hypothesis \(H_j\) given the data (evidence) \(D\) at hand.

  • \(P(H_j)\) is the prior probability, i.e., the probability of hypothesis \(H_j\) before we have seen any data.

  • \(P(D|H_j)\) is called the likelihood: the probability of the data \(D\) given hypothesis \(H_j\). This is our model of the data generation process under the hypothesis. The likelihood updates the prior to the posterior.

  • \(P(D) = \sum_{i=1}^{k}P(D|H_i)\cdot P(H_i)\) is the total probability of the data, summing over all \(k\) hypotheses. It serves to normalize the numerator in Bayes’ rule so that the posterior distribution over all hypotheses sums to \(1\) and is thus a probability distribution. For a continuous unknown, e.g., a proportion, the sum becomes an integral. Such integrals can be solved exactly only in a few special cases. In practice, we therefore approximate the integral, e.g., by a sum over a grid of possible values.

Applying Bayes’ rule

Consider a large forest, in which some trees may be infested by bark beetles. Checking a tree for infestation is laborious, so we can only inspect a sample of trees, e.g., 30 randomly chosen trees. What proportion of the trees in the forest is infested? This we cannot count, because we never inspect the whole forest. We can only infer it from the inspected trees, using Bayes’ rule.

Applying Bayes’ rule involves five steps:

  1. Hypotheses \(H_j\): the possible values of the unknown quantity. Here: the possible proportions of infested trees in the forest, from 0 to 1.
  2. Prior \(P(H_j)\): the probability of each hypothesis before seeing the data. Here: how plausible we consider each proportion before inspecting any trees, e.g., based on earlier surveys.
  3. Likelihood \(P(D|H_j)\): the probability of the observed data given each hypothesis. Here: if we observe 6 infested trees among 30 inspected trees, how likely is this observation if the proportion in the forest were 0.1, 0.2, and so on?
  4. Total probability \(P(D) = \sum_{i=1}^{k}P(D|H_i)\cdot P(H_i)\): the probability of the observed data, regardless of which hypothesis is true. Since the hypotheses are mutually exclusive and one of them must be true, it is the sum of prior times likelihood over all hypotheses. Here: the probability of finding 6 infested trees among 30, averaged over all possible proportions, weighted by the prior.
  5. Posterior \(P(H_j|D)\): prior times likelihood, divided by the total probability. Here: given that we found 6 infested trees among 30 inspected trees, how probable is a proportion of 0.1, 0.2, and so on in the forest?

Hypotheses

In our example, the proportion of infested trees can be any value between 0 and 1. Each value is a hypothesis: “a proportion \(h\) of the trees is infested”. Since there are infinitely many such values, we can only consider a selection of them, e.g., every value from 0 to 1 in steps of 0.01. The function seq() creates such a vector as a sequence of numbers between two bounds (from and to) with a fixed increment (by):

h <- seq(from = 0, to = 1, by = 0.01)
h
  [1] 0.00 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.10 0.11 0.12 0.13 0.14 0.15 0.16 0.17 0.18
 [20] 0.19 0.20 0.21 0.22 0.23 0.24 0.25 0.26 0.27 0.28 0.29 0.30 0.31 0.32 0.33 0.34 0.35 0.36 0.37
 [39] 0.38 0.39 0.40 0.41 0.42 0.43 0.44 0.45 0.46 0.47 0.48 0.49 0.50 0.51 0.52 0.53 0.54 0.55 0.56
 [58] 0.57 0.58 0.59 0.60 0.61 0.62 0.63 0.64 0.65 0.66 0.67 0.68 0.69 0.70 0.71 0.72 0.73 0.74 0.75
 [77] 0.76 0.77 0.78 0.79 0.80 0.81 0.82 0.83 0.84 0.85 0.86 0.87 0.88 0.89 0.90 0.91 0.92 0.93 0.94
 [96] 0.95 0.96 0.97 0.98 0.99 1.00

Such a set of evenly spaced values is called a grid, and calculating the posterior for each of its values is called grid approximation. The finer the grid, the closer we get to the continuous range of possible proportions, but the more values we have to calculate.

Prior

The prior assigns a probability to each hypothesis. We can derive it from a probability distribution, using the d* functions. They return the probability (discrete distributions) or the probability density (continuous distributions) at each value of a vector. All distributions in R work the same way (see Probability distributions and Probability distributions in R).

A uniform distribution assigns the same density to every value between min and max. As a prior, it expresses that we consider every proportion of infested trees equally likely:

du <- dunif(h, min = 0, max = 1)
plot(h, du)

A normal distribution with mean 0.2 and standard deviation 0.1, \(N(0.2, 0.1)\), assigns the highest density to values around 0.2 and lower densities further away. As a prior, it expresses that we expect about 20% of the trees to be infested, e.g., from earlier surveys, but do not rule out other proportions. Note that we write the normal distribution as \(N(\text{mean}, \text{sd})\), matching the arguments of dnorm(). Some texts write \(N(\mu, \sigma^2)\) with the variance instead.

dn <- dnorm(h, mean = 0.2, sd = 0.1)
plot(h, dn)

Densities are not probabilities, and their sum depends on the spacing of the grid. For example, the uniform density is 1 at each of the 101 values of h, so it sums to 101. To use the densities as probabilities over our hypotheses, we divide them by their sum, so that they add up to 1, e.g., du / sum(du) or dn / sum(dn).

Likelihood

The likelihood is the probability of the observed data given each hypothesis (proportion of infested trees in the forest). In our example, the data are the number of infested trees among the inspected trees. If a proportion \(h\) of the trees is infested, each randomly chosen tree is infested with probability \(h\). Because the forest is large, inspecting a few trees does not change this probability for the next tree, so the inspected trees are independent of each other. If many trees in the forest are infested, finding an infested tree is likely; if none are, it is impossible. Since the likelihood is a probability, R’s d* functions are a good place to start. Think about which of the probability distributions describes your data: Are they counts or measurements? Is there a fixed number of inspected trees? Which parameter of the distribution follows from the hypothesis? Like the prior, the likelihood is calculated for each hypothesis in h.

Total probability

The total probability is the denominator of Bayes’ rule. Multiply prior and likelihood element by element and sum the products. The result is a single number. Because our grid covers only a selection of the possible proportions, it only approximates \(P(D)\), the probability of the data. If the prior is not divided by its sum (see Prior), the result is not \(P(D)\), but the posterior is still correct, because the scaling cancels out.

Posterior

The posterior follows from Bayes’ rule: divide the products of prior and likelihood by the total probability. The posterior thus sums to 1 over all hypotheses. Plot it against h and compare it with the prior to see how the data have changed our belief about the proportion of infested trees. To summarize it, e.g., by its mean or an interval, we draw samples from it (see Sampling from the posterior).

Sampling from the posterior

On a grid, we could summarize the posterior directly, e.g., its mean as the sum of the hypotheses weighted by their posterior probabilities. Instead, we will draw samples from it, for three reasons. First, summaries become simple: the mean of the samples estimates the posterior mean, their quantiles give an interval, and the share of samples above a threshold gives the probability of exceeding it. Second, samples make predictions easy. To predict the number of infested trees among the next 30 inspected trees, we simulate inspections for each sampled proportion. The predictions then reflect both our uncertainty about the proportion of infested trees and the randomness of choosing trees. Third, for problems with many unknown quantities, a grid becomes too large, and most Bayesian methods in practice only provide samples from the posterior. Working with samples now prepares you for these methods. The price is a small random error: summaries change slightly every time we sample, but less so the more samples we draw.

The function sample() draws elements from a vector. With replace = TRUE, each element can be drawn more than once, and the argument prob sets the probability of drawing each element. In the exercise, you will sample from the posterior. Here, we draw 1000 values from h, using the normal prior as weights (sample() normalizes them internally):

s <- sample(h, size = 1000, replace = TRUE, prob = dn)
hist(s, breaks = seq(min(h) - 0.005, max(h) + 0.005, by = 0.01))

The histogram of the samples approximates the distribution we sampled from. The breaks place each bar centrally over one value of h.

Updating with new data

The posterior summarizes what we know about the proportion of infested trees after inspecting 30 trees. If we inspect more trees later, we do not have to start from scratch: the current posterior becomes the prior, and the new data update it to a new posterior. The result is the same as if we had analyzed all inspected trees at once with the original prior. Bayesian inference thus accumulates knowledge step by step, e.g., across repeated surveys of the same forest. This is also where an informative prior can come from: it can be the posterior of an earlier survey.

Frequentist and Bayesian estimates

How does the Bayesian estimate differ from the frequentist estimates you know from previous labs? Suppose 6 of the 30 inspected trees are infested.

Frequentist. The true proportion is a fixed, unknown number. It is not random and has no probability distribution. We estimate it by the observed proportion, \(\hat{p} = \frac{6}{30} = 0.2\), and describe the uncertainty with a 95% confidence interval, here about \([0.06, 0.34]\). This means that if we repeated the sampling many times, 95% of the intervals calculated this way would contain the true proportion. It does not mean that the true proportion lies in this particular interval with a probability of 95%.

Bayesian. The true proportion is also a fixed number, but we are uncertain about it, and we describe this uncertainty with a probability distribution: the prior before seeing the data, the posterior after. With a uniform prior, the 95% interval of the posterior is about \([0.10, 0.37]\). This interval, called a credible interval, can be read directly: given the data and the prior, the true proportion lies in it with a probability of 95%.

The two approaches are closely related. With a uniform prior, the posterior has the same shape as the likelihood, and its peak lies at 0.2, the frequentist estimate. The two intervals are also about equally wide, but the credible interval lies a bit higher. The confidence interval above is symmetric around 0.2, because it approximates the uncertainty with a normal distribution. The posterior is skewed: a proportion cannot be smaller than 0, so the posterior is squeezed on the left and has a longer tail on the right. The more data we have, the less the prior matters, and the closer the two approaches get. They differ most when data are scarce: then the prior has a strong influence on the posterior, which is useful if it contains real prior knowledge, e.g., from earlier surveys.

TipKey points
  • Bayes’ rule: the posterior probability of a hypothesis is its prior probability times the likelihood of the data, divided by the total probability of the data.
  • The likelihood is a probability of the data, not of the hypotheses.
  • In R, we apply Bayes’ rule to a grid of hypotheses: prior, likelihood, and posterior are calculated for each hypothesis at once.
  • Samples from the posterior make it simple to summarize it and to make predictions.
  • A 95% credible interval contains the parameter with a probability of 95%, given the data and the prior. A 95% confidence interval does not: it refers to how often intervals calculated this way would contain the true value if we repeated the sampling.
  • The posterior from one analysis can serve as the prior for the next, so estimates can be updated when new data arrive.