About these notes
These notes accompany the lecture slides and recordings for the Bayesian statistics half of Bayesian Statistics and Decision Theory. The slides are deliberately brief. They serve as an outline, and much of the explanation is given aloud in the lectures. The notes are meant to supply that explanation in written form, so that the argument can be followed at your own pace and returned to when revising.
The notes follow the order of the slides. Where the slides state a result, the notes usually derive it, and where the lectures pause for a calculation, the notes give the calculation in full. Along the way they try to say not only what is true but why it is worth knowing, and how one idea leads to the next.
The notes are not a substitute for a textbook. Much of the material follows Hoff, A First Course in Bayesian Statistical Methods (2009), and references to Hoff’s sections are given where they help. Bernardo and Smith, Bayesian Theory, gives a more thorough account of the foundations, particularly of exchangeability and the justification of probability as a measure of belief. Gelman, Carlin, Stern and Rubin, Bayesian Data Analysis (abbreviated GCSR), is the source of several of the data sets and is the best general reference for applied work.
Each chapter ends with a few exercises. Each exercise is followed by its solution, hidden until you open it. It is worth making a genuine attempt at each exercise before opening its solution. Much of the understanding comes from the attempt, including the attempts that fail.
0.0.0.0.1 Notation.
We write for a probability density or mass function, and let its argument indicate which distribution is meant: is the prior, the sampling model, the posterior. This is an abuse of notation, since the three are different functions, but it is universal in Bayesian work and causes little confusion in practice. When we need to name a distribution explicitly we write, for example, for the density evaluated at . The Gamma distribution is parameterised throughout by its shape and rate , so that its mean is .
1 The idea
This chapter sets out the central idea of the course: that probability can be used to represent what a person knows, and that Bayes’ theorem then tells us how that knowledge should change in the light of data. The rest of the course develops this idea for particular models and shows how to carry out the necessary calculations.
1.1 What is a random variable?
Before we can speak of Bayesian inference we need to be clear about what a probability is meant to describe. There are two common answers, and the difference between them is the root of most of what distinguishes Bayesian statistics from the methods you may have met before.
In the frequentist view, a random variable is the outcome of an experiment or game that could, at least in principle, be repeated indefinitely under the same conditions. The probability of an outcome is the long-run proportion of repetitions in which it occurs. This is how Fermat and Pascal thought about games of dice in the seventeenth century, and it remains a natural way to think about coins, cards and many physical processes. On this view a probability is a property of the system being studied, in the same way that its mass or length is.
In the Bayesian view, a random variable is any quantity whose value is unknown to us, and its probability distribution describes our uncertainty about it. A probability is then a property of a person, or more precisely of a person’s state of information, rather than of the system alone. Two people with different information may quite reasonably assign different probabilities to the same event.
The Bayesian view is the wider of the two. The number of heads in ten tosses of a coin is a random variable on either view. But consider the proportion of voters in Scotland who favoured independence in September 2014, the speed of light, or whether a particular patient has a particular disease. Each of these has a definite value. Nothing about them is repeatable, and on the frequentist view it makes no sense to give them probability distributions. We are nonetheless uncertain about them, and the Bayesian is content to describe that uncertainty by a probability distribution. This is what allows a Bayesian to make statements such as ‘the probability that the disease is present is 0.05’ or ‘there is a 95% probability that the true value lies in this interval’, which have no direct frequentist meaning.
1.2 Learning with Bayes’ theorem
Bayesian inference is the process of learning from data by means of Bayes’ theorem. Schematically, In most statistical problems the beliefs in question concern the values of parameters that describe a population or a process: the mean height of people in York, say, or the rate at which a machine fails. The new information usually takes the form of a sample of observations whose distribution depends on those parameters. Beliefs, both before and after the data are seen, are expressed as probability distributions over the possible values of the parameters.
We shall use the following notation throughout.
denotes the parameter of interest, and the set of its possible values, called the parameter space. The parameter may be a single number or a vector.
denotes the observed data, and the set of possible observations, called the sample space.
is the prior distribution. It describes our beliefs about before the data are seen.
is the sampling model. For each possible value of it gives the probability (or probability density) of observing the data if were the true value. When we fix at the value actually observed and regard as a function of , we call it the likelihood.
is the posterior distribution. It describes our beliefs about after the data have been seen.
The prior and the sampling model together specify a joint distribution for and , namely . The posterior is the conditional distribution of given under this joint distribution. Bayes’ theorem is simply the rule for computing it: (If is discrete, the integral is replaced by a sum.)
The denominator deserves a comment. It is obtained by averaging the probability of the observed data over all possible values of the parameter, weighted by the prior. It is therefore the probability of what was actually observed, computed before the data were seen, and it is called the marginal likelihood or prior predictive probability of the data. It does not depend on , and this is what matters for calculation. Its only role in (1.1) is to make the posterior integrate to one. For this reason we often write Bayes’ theorem as a proportionality, or, in words, posterior is proportional to likelihood times prior. The prior and the information from the data combine by multiplication, and the product is then rescaled to integrate to one. A value of is favoured by the posterior if it was plausible beforehand and if it makes the observed data probable; a value that fails on either count is discounted.
The marginal likelihood will play little part in this half of the module, but it becomes important when competing models are to be compared, since it measures how well each model predicted the data before they were seen.
This gives us the central idea of the course. Bayesian statistics describes how an idealised agent ought to learn from data, provided two conditions hold. First, the agent’s knowledge must be expressible, at least approximately, as a probability distribution. Second, the agent must be able to carry out the necessary calculations, and in particular to evaluate the integral in (1.1). Neither condition is trivial. The first raises questions about where priors come from, which we take up in Chapter 10. The second is a matter of computation, and a large part of the course, from Chapter 8 onwards, is concerned with it.
1.3 A diagnostic test
The following example is simple, but it displays in miniature most of what Bayesian reasoning involves, and it shows how easily intuition can go astray without it.
A doctor is concerned that a patient may have a rare but serious disease. Let if the patient has the disease and otherwise, and let if a diagnostic test returns a positive result and otherwise. Here both the parameter and the data are binary.
1.3.0.0.1 The prior.
The doctor knows that about one person in a thousand in the relevant population has the disease. Before any test is done, and in the absence of other information about this patient, the doctor’s prior is therefore
1.3.0.0.2 The sampling model.
The test has been evaluated in the laboratory. When the disease is present it returns a positive result 95% of the time; when the disease is absent it returns a (false) positive 2% of the time: The first of these numbers is called the sensitivity of the test, and one minus the second, , is its specificity. Both look reassuringly high.
1.3.0.0.3 The posterior.
The test comes back positive. By Bayes’ theorem, The numerator is and the denominator is , so Despite the positive result, the patient probably does not have the disease.
Most people find this surprising at first, and it is worth seeing why the answer is right. Imagine testing a thousand people drawn from the population. About one of them has the disease, and that person will very probably test positive. Of the 999 who do not have the disease, about 2%, or roughly twenty, will also test positive. A positive result therefore places our patient in a group of about twenty-one people, only one of whom is ill. The test has done something: it has raised the probability of disease from one in a thousand to about one in twenty-two, an increase by a factor of more than forty. But it began from so low a base that the disease remains unlikely.
The example shows the two ingredients of Bayesian reasoning working together. The prior, which reflects the rarity of the disease, and the likelihood, which reflects the behaviour of the test, both matter, and neither alone determines the conclusion. A doctor who looked only at the test’s accuracy, ignoring the prior, would badly overstate the chance of disease. The error is common enough to have a name, the base rate fallacy.
It also suggests what the doctor should do next. A single positive result is not conclusive, so a sensible course is to repeat the test, or to use a different and more specific one. Exercise 1.1 shows how much a second positive result would change matters.
1.4 Objections to Bayesian inference
For much of the twentieth century there was a divide, at times a hostile one, between frequentist and Bayesian statisticians. It is worth knowing the main lines of the argument, both because they clarify what Bayesian methods claim to do and because you will meet them in practice.
The principal frequentist objection is that Bayesian inference is not objective. Science, on this view, is meant to reach conclusions that any competent investigator would reach from the same evidence. If the conclusions of an analysis depend on the prior beliefs of the analyst, then two scientists looking at the same data may disagree, and the conclusions seem to say as much about the scientists as about the world.
The Bayesian reply comes in several parts. The first is that data acquire meaning only by changing what we believe; a set of numbers without any context about what they measure or what was expected tells us nothing. The second is that frequentist methods also rest on choices and assumptions (of model, of test statistic, of significance level, of stopping rule) and that these play a role similar to that of a prior, though less openly. Some Bayesians go further and argue that frequentist procedures, where they are sensible, are Bayesian procedures with an unstated prior.
A Bayesian may respond to the charge of subjectivity in either of two ways. One is to accept it. On this view Bayesian inference is a tool for an individual, with genuinely held beliefs, to learn from data and to make decisions, and there is nothing to apologise for in that. The Decision Theory half of the module develops this view further. The other is to make statements that do not depend on any one person’s beliefs. For example, one can say: these data are sufficient to move anyone who held a prior of such a form to a posterior of such a form. The information in the data is then measured by its capacity to change the minds of a range of hypothetical people. Reporting how conclusions vary as the prior is varied, known as a sensitivity analysis, is a practical form of the same idea. And, as we shall see repeatedly, when the data are plentiful the posterior depends very little on the prior, so that people who begin with different beliefs are brought into agreement by the evidence.
Exercises
Exercise 1.1
The doctor repeats the test and both results are positive. The two results are independent given the patient’s disease status. Find the posterior probability that the patient has the disease. Check that you get the same answer whether you use both results at once or update the prior with one result and then update the resulting posterior with the other.
Show solutionHide solution
Let . By conditional independence, and . So Updating in two stages gives the same answer. After the first test the posterior probability of disease is . Using this as the prior for the second test, The second positive result is much more persuasive than the first, not because the test has changed but because it is now applied to a patient who is already under suspicion.
Exercise 1.2
Repeat Exercise 1.1 using the odds form of Bayes’ theorem (Section 2.3.1). What does each positive result do to the odds of disease?
Show solutionHide solution
The prior odds of disease are . Each positive result has Bayes factor . After one test the odds are , a probability of . After two they are , a probability of . Each positive result multiplies the odds by . With independent tests, evidence accumulates additively on the log-odds scale.
2 A review of probability
This chapter reviews the parts of probability theory that we shall use. Most of it will be familiar. The emphasis, however, is slightly different from that of a first course: we are interested in probability as a description of uncertain knowledge, and so we pay particular attention to conditional probability, which is the mathematical form of learning.
2.1 Sample spaces, events and probabilities
A sample space is a set of possible outcomes, or states of the world. One can think of it as an ‘atomic’ description: each outcome specifies everything that is relevant to the problem at hand. For a single roll of a die, . For a patient undergoing a test, might consist of the four combinations of disease status and test result.
An event is a set of outcomes, and we say that occurs if the outcome that is realised belongs to it. For the die, ‘an even number is rolled’ is the event . An event space is a collection of events to which probabilities will be assigned. One can think of it as describing what we are able to observe or ask about. (For technical reasons, when is uncountable, it is not always possible to assign probabilities consistently to every subset, and must be restricted to a suitable collection called a -algebra. We shall not need these details.)
A probability function assigns a number to each event in .
2.2 Axioms
Kolmogorov, in 1933, gave the axioms that now form the standard basis of probability theory. A triple is called a probability space if
for all ;
;
whenever the events are pairwise disjoint, that is, for .
Here is the event that or (or both) occurs, the event that both occur, and the empty set. In Kolmogorov’s system, conditional probability is then defined by
Kolmogorov’s axioms say nothing about what probability means. They are equally at home with frequencies and with degrees of belief. Bayesians have therefore asked a different question: what properties ought a person’s degrees of belief to have if they are to be coherent? Hoff, following de Finetti and most Bayesian authors, lists the following:
for all ;
if ;
.
In this system conditional probability is a primitive notion. is the degree of belief one would have in on learning that is true, and Axiom P3 is a requirement that such conditional beliefs fit together consistently with unconditional ones. The conclusion is that degrees of belief should obey the same rules as Kolmogorov’s probabilities, so that the whole of probability theory is available to describe them. (The one difference, that de Finetti’s system requires additivity only for finitely many events rather than countably many, will not concern us.)
Why should degrees of belief satisfy these rules? One well-known argument, due to de Finetti, uses betting. Suppose your degree of belief in an event is the price at which you would be willing either to buy or to sell a ticket that pays £1 if occurs and nothing otherwise. If your prices violate the axioms, then an opponent can construct a collection of bets, each of which you regard as fair, that together lose you money whatever happens. Such a collection is called a Dutch book. For example, if you set and , violating P2 (since and its complement are disjoint with union ), the opponent sells you both tickets for £1.20; exactly one of them pays out, so you receive £1 and lose 20 pence for certain. Beliefs that cannot be exploited in this way are called coherent, and it can be shown that coherence is equivalent to satisfying the axioms. Arguments of this kind are developed further in the Decision Theory half of the module.
2.3 Partitions and Bayes’ rule
Many calculations involve dividing the sample space into a number of mutually exclusive possibilities.
Definition 2.1. A collection of sets is a partition of a set if
the sets are disjoint, for , and
their union is , that is, .
In other words, exactly one of the is true whenever is. In the diagnostic example, the events ‘disease present’ and ‘disease absent’ form a partition of .
Suppose that is a partition of , so that , and let be any event with . Two results follow directly from the axioms.
The law of total probability, or marginal probability rule: The first equality holds because the events partition ; the second is Axiom P3 applied to each term. In words, the probability of is a weighted average of its conditional probabilities under each hypothesis, weighted by the probabilities of the hypotheses.
Bayes’ rule: This follows by writing in two ways using Axiom P3, , and then using the law of total probability for the denominator.
The statistical reading of Bayes’ rule is the one we met in Chapter 1. Think of the as competing hypotheses about the state of the world, perhaps corresponding to different values of a parameter, and of as the event that an experiment produces a particular result. Bayes’ rule converts the probabilities of the result under each hypothesis, which are usually what a scientific model provides, into the probabilities of the hypotheses given the result, which are what we actually want to know.
2.3.1 Odds and Bayes factors
When attention is on just two hypotheses, and , it is often convenient to work with the ratio of their probabilities. Writing Bayes’ rule for each and dividing, the denominator cancels: The ratio on the left is the posterior odds of against , and the second ratio on the right is the prior odds. The first ratio on the right, which depends only on how probable the data are under each hypothesis, is called the Bayes factor. So This form separates cleanly the contribution of the data from that of prior belief. In the diagnostic example, the Bayes factor for disease against no disease after a positive test is . Whatever one’s prior odds, a positive result multiplies them by . The prior odds of about become posterior odds of about , corresponding to the probability found earlier. If there are only two hypotheses, a posterior odds of corresponds to a posterior probability of .
2.4 Independence and conditional independence
Events and are independent if and they are conditionally independent given if Axiom P3, applied conditionally on , gives . Comparing this with the definition shows that, provided , conditional independence of and given is equivalent to This is the more intuitive form: if we already know that is true, then learning that is also true does not change our belief about .
Independence and conditional independence are different properties, and neither implies the other. The distinction is central to this course, and the diagnostic example illustrates it well. Suppose the test is applied twice, and let and be the events that the first and second results are positive. Given the patient’s disease status, the two results are independent, since each depends only on the behaviour of the test. But before we know the disease status, they are not independent. A positive first result makes disease more likely, and so makes a positive second result more likely too. Indeed, using the numbers from Chapter 1, so learning roughly triples the probability of . The dependence arises entirely through the unknown disease status.
Almost every model in this course has this structure. The observations are modelled as independent given the value of a parameter, but since the parameter is unknown the observations are not independent unconditionally. It is precisely this dependence that allows us to learn: each observation tells us something about the parameter, and so something about the observations yet to come. Chapter 3 makes this idea precise.
2.5 Random variables
To a Bayesian, any unknown quantity may be treated as a random variable, and its probability distribution describes our uncertainty about it. We distinguish two main kinds.
2.5.1 Discrete random variables
A random variable is discrete if the set of its possible values is countable (finite, or listable as a sequence). Its distribution is described by a probability mass function which satisfies for all , , and The Bernoulli, binomial and Poisson distributions are examples.
Often is a set of integers, which have a natural ordering. We can then define the cumulative distribution function (CDF), It is non-decreasing, tends to as and to as , and satisfies . For a discrete random variable, a plot of is a staircase, jumping upwards at each point of by an amount equal to the probability of that point.
2.5.2 Continuous random variables
A random variable is (absolutely) continuous if its CDF is an (absolutely) continuous function. It then has a probability density function , related to the CDF by so that wherever the derivative exists, and more generally The exponential and normal distributions are examples, and is usually an interval of the real line.
We use the same symbol for densities as for mass functions, because the two play the same role in almost every formula we shall write, with sums replaced by integrals. But the two are not the same kind of object, and it is important not to confuse them. A density is not a probability. For a continuous random variable, for every single value , and the density at a point may be larger than one. What the density does tell us is the probability of a small interval: So a density measures probability per unit length, much as physical density measures mass per unit volume. This is why densities change when the variable is rescaled or transformed, as we see in Section 2.6.
2.5.3 Summaries of a distribution
A distribution is a complete description of uncertainty about a quantity, but it is often useful to summarise it by a few numbers describing its location and spread.
The mean, or expectation, of is It is the centre of mass of the distribution. Two other measures of location are the mode, the most probable value (for a continuous variable, the value at which the density is greatest), and the median, which divides the distribution into two halves of equal probability. For a symmetric distribution with a single peak the three coincide. For a skewed distribution they may differ considerably, and the choice between them is not merely technical: as the Decision Theory half of the module will show, each is the best single guess under a different notion of what it means for a guess to be good.
The variance of is the expected squared distance from the mean, and its square root is the standard deviation. The variance is often easier to compute from the formula which follows by expanding the square and using linearity of expectation.
Other measures of spread are based on quantiles. If is continuous and strictly increasing, the -quantile of is the value such that The median is . Two commonly used intervals are the interquartile range, the length of the interval that contains the middle half of the distribution, and the 95% central interval , which leaves probability in each tail. When the distribution in question is a posterior, this last interval is called a 95% central posterior interval or credible interval, and it will be our main way of reporting uncertainty about a parameter.
2.5.4 Conditional expectation
Two identities for conditional expectations will be used many times, particularly when we come to prediction. For random variables and , The first, sometimes called the tower property, says that the overall mean of can be found by first computing the mean of for each value of and then averaging these over the distribution of . It is the analogue for expectations of the law of total probability.
The second, the law of total variance, says that the variability of has two sources: the variability of about its conditional mean for fixed , averaged over ; and the variability of the conditional mean itself as varies. To prove it, write . Then , so by (2.1) and adding these gives .
2.6 Transformations
We shall often need the distribution of a function of a random variable: of when we know the distribution of , for example. For discrete variables this is a matter of adding up probabilities. For continuous variables the densities must be adjusted.
Let be continuous with density , and let , where is one-to-one and continuously differentiable. Then has density where . To see why, suppose is increasing. Then , and differentiating with respect to by the chain rule gives the formula. If is decreasing, the same argument gives the formula with a minus sign, which the absolute value takes care of. The factor records how the transformation stretches or compresses the axis: a small interval of length in corresponds to an interval of length about in , and the two intervals must carry the same probability.
The same reasoning extends to random vectors. If with one-to-one and differentiable, then where is the Jacobian matrix of the inverse transformation, with entries . The absolute determinant plays the part of , measuring how the transformation changes small volumes.
These formulae have a consequence that will matter when we discuss the choice of prior. A density on , and the density it induces on a transformed parameter , do not in general have the same shape. In particular, a prior that is flat (uniform) in is not flat in or in . So the statement ‘I have no preference among the possible values of the parameter’ is ambiguous until we say which parameterisation we mean. We return to this in Chapter 10.
Exercises
Exercise 2.1
Let and . Find the density of .
Show solutionHide solution
is one-to-one on , with inverse and . So
Exercise 2.2
Let and be independent, with . Let and . Find the joint density of . What do you notice?
Show solutionHide solution
The inverse is , , with and . The Jacobian matrix is So The density factorises. and , and they are independent. This gives a way to simulate Beta variables from Gamma variables.
3 Exchangeability
This chapter follows Hoff §2.7. It addresses a question that is easy to pass over: why do statistical models take the form they do? Almost every model in this course, and in statistics generally, supposes that the observations are independent and identically distributed given some parameter, and that the parameter has a prior distribution. The idea of exchangeability, together with a remarkable theorem of de Finetti, shows that this structure is not an arbitrary assumption but follows from a simple and natural judgement about the observations themselves.
3.1 Motivation
Roll a fair die times, and let if the th roll shows a six and otherwise. The rolls are independent, and each shows a six with probability , so the probability of any particular sequence of results is This probability depends only on the number of sixes, , and the number of other results, . Every sequence with the same number of sixes has the same probability, whatever the order in which the sixes appear. The sequence is exactly as probable as .
This symmetry under reordering turns out to be the essential property, and it holds much more widely than for independent rolls of a fair die.
3.2 Definition
Definition 3.1. Random variables are exchangeable if their joint distribution is unchanged by any permutation of their labels: for every permutation of . An infinite sequence is exchangeable if are exchangeable for every .
To judge a set of quantities exchangeable is to judge that their labels carry no information: knowing which observation is which would not change your beliefs about the collection. This is often a reasonable judgement. If the are measurements on individuals drawn at random from a population, and there is nothing else to distinguish one individual from another, then we have no reason to expect the first measurement to differ systematically from the fifth. It is not always reasonable. Measurements taken in time order, where later values may depend on earlier ones, are not usually exchangeable. Nor are measurements on individuals known to belong to different groups, such as patients given different treatments, though they may be exchangeable within each group.
Independent and identically distributed (i.i.d.) random variables are exchangeable, since the middle equality holding because a product does not depend on the order of its factors. The same applies to infinite i.i.d. sequences.
The converse is false: exchangeable variables need not be independent. The next theorem shows the most important way in which exchangeable but dependent variables arise.
Theorem 3.2. Suppose that are conditionally i.i.d. given , with , and that . Then, marginally (that is, without conditioning on ), are exchangeable.
Proof. The marginal distribution is obtained by averaging over : The second equality uses conditional independence and the third the commutativity of multiplication. ◻
Such variables are, however, not independent marginally, for the reason explained in the previous chapter. Observing changes our beliefs about , and hence about . It is exactly this dependence that makes learning possible. If the observations were marginally independent, no number of them would tell us anything about the next.
3.3 De Finetti’s theorem
Theorem 3.2 says that the familiar model structure, conditionally i.i.d. observations with a prior on the parameter, always produces exchangeable observations. The converse also holds, provided the sequence can be extended indefinitely.
Theorem 3.3 (de Finetti). Let be an infinite sequence of random variables with a common sample space, and suppose that are exchangeable for every . Then there exist a parameter , a prior distribution and a sampling model such that, for every ,
Combining the two theorems,
We do not prove the theorem here. For binary sequences a fairly elementary proof is given in Bernardo and Smith, §4.3. The binary case also shows what the parameter is. If is an exchangeable sequence of zeros and ones, then the proportion of ones among the first , , converges as , and the limit is the parameter . The prior is therefore our belief about the long-run proportion of ones in the sequence, and given that proportion the observations behave like independent Bernoulli trials with that probability of success.
It is worth pausing on why this matters. A person who judges only that the labels on a sequence of observations are irrelevant, and who is willing to imagine the sequence continuing indefinitely, is thereby committed to modelling the observations as if they were i.i.d. given some parameter, with a prior distribution on that parameter. The parameter and its prior are not extra assumptions laid on top of the data. They arise from a judgement of symmetry about quantities that can actually be observed. De Finetti held that probability statements should ultimately concern observable quantities, and his theorem explains how parameters, which are not directly observable, nonetheless earn their place in a model. For a modern account that places prediction at the centre of Bayesian modelling, see Fortini and Petrone (2025), Statistical Science 40, 40–67.
The theorem does not tell us which sampling model or prior to use. That remains a matter of judgement, informed by what we know of the problem. It tells us only the form the model must take.
3.4 Finite populations
De Finetti’s theorem requires an infinite exchangeable sequence, and the requirement is not a technicality. Suppose we draw individuals at random, without replacement, from a finite population of size . The resulting observations are exchangeable, since the order of drawing is irrelevant, but they are not in general conditionally i.i.d. given any parameter. Exercise 3.1 gives an extreme example. The reason is that drawing without replacement induces negative dependence (drawing one individual with a property makes the next less likely to have it), whereas conditionally i.i.d. observations can only be positively dependent or independent.
When the sample size is small compared with the population size , however, the effect of not replacing is negligible, and we may treat the observations as approximately conditionally i.i.d. This is the situation in most applications, and it is the justification for the models used in the rest of the course. Most of the models we consider assume that the data are conditionally i.i.d. given some parameter , which may be a vector.
Exercises
Exercise 3.1
An urn contains two balls, one marked and one marked . Two balls are drawn without replacement, and is the mark on the th ball drawn.
Show that are exchangeable.
Show that there is no distribution on under which are i.i.d. Bernoulli.
Show solutionHide solution
(a) The possible sequences are and , each with probability , and and , each with probability . The joint distribution is unchanged by swapping the two coordinates.
(b) Suppose such a existed. Then , and by Jensen’s inequality, or because . But . Contradiction. More generally, conditionally i.i.d. variables cannot be negatively correlated, while draws without replacement are.
4 Binomial data
References: Hoff §3.1; GCSR §2.1–2.4.
We now apply the general machinery to the simplest useful model. Binomial data are common in their own right, and the model is simple enough that every step of a Bayesian analysis can be carried out by hand. Most of the ideas introduced here (conjugacy, the interpretation of the prior as imaginary data, the posterior mean as a compromise, the predictive distribution) recur in every later chapter.
4.1 Setting
A familiar kind of question runs as follows. We draw individuals at random from a population and find that some of them have a certain property. What does this tell us about the proportion of the whole population that has the property? Some examples:
In a clinical trial of a new treatment for psoriasis, 12 of 15 patients showed a marked improvement compared with the standard treatment. What is the probability that a future patient will improve?
On 5 September 2014, a YouGov poll of 1084 voters on the Scottish independence referendum found 51% for Yes and 49% for No, excluding those who would not vote or did not know. What is the probability that Yes was ahead in the population?
Of 12 lecturers in a small department at a UK university, 3 are foreign nationals.
Of 25 items selected from a day’s production for quality control, none is defective. Does that mean the production process makes no defective items?
To set up a model, label the individuals in the population and let The quantity of interest is the population proportion . We observe for a sample of individuals, usually with much smaller than , and ask how these observations should change our beliefs about .
If we have no information that distinguishes one sampled individual from another, it is natural to judge exchangeable. Since is large compared with , the discussion of Chapter 3 then justifies the model in which each observation is a one with probability , independently of the others, given .
4.2 Likelihood and sufficiency
Under this model the probability of the observed sequence is Notice that the likelihood depends on the data only through , the total number of ones. Two samples of the same size with the same number of ones give exactly the same likelihood function, and so, whatever the prior, the same posterior. We express this by saying that is a sufficient statistic for : once we know , the individual values , and in particular the order in which the ones and zeros occurred, carry no further information about .
The total has a binomial distribution, This differs from the likelihood of the full sequence only by the factor , which does not involve . Since Bayes’ theorem determines the posterior only up to a constant factor, it makes no difference whether we work with the sequence or with the total. We shall move freely between the two.
4.3 A uniform prior
Next we need a prior. Suppose, to begin with, that we have no particular information about , and that we regard all values between and as equally plausible. This suggests the uniform prior , with density under which any two intervals of the same length have the same prior probability. (We shall see in Chapter 10 that ‘equally plausible’ is less straightforward than it sounds, but the uniform prior is a sensible starting point.)
The posterior is then As a function of , this has the form of the density of a Beta distribution, with its normalising constant omitted.
Definition 4.1. A random variable has a distribution, where and , if its density is Its mean, mode and variance are
The Beta family is very flexible on the interval . With it is uniform. With it is symmetric about and peaked, more sharply as and increase. With it is skewed towards one, and with towards zero. With or below one the density is unbounded at the corresponding end of the interval. The form of the variance shows that, for a fixed mean, the distribution becomes more concentrated as increases.
Comparing the posterior with the Beta density, we conclude that For the psoriasis trial, with and , the posterior is . Its mean is , and the posterior probability that more than half of future patients would improve is .
4.4 The kernel method
The step we have just taken will recur throughout the course, and it is worth setting it out explicitly.
Write down the posterior up to a constant, . At each stage, discard any factor that does not involve .
Recognise the result as the kernel of a known distribution, that is, as its density with the normalising constant removed.
Conclude that the posterior is that distribution.
The argument is valid because a probability density is determined by its kernel. If two densities are proportional to one another, then, since both integrate to one, the constant of proportionality must be one and the densities are equal. The practical benefit is considerable. It spares us the integral in the denominator of Bayes’ theorem, which is the hardest part of the calculation, and it gives us the posterior in a form whose properties (mean, variance, quantiles) are already known.
4.5 Prediction
Often the most useful thing a posterior distribution can do is predict future observations. What should we expect of the next individual we sample? By the tower property (2.1), conditioning on , Given , the new observation is independent of the old ones and has mean , so , and Since takes only the values and , this is also the probability that the next individual has the property. The prediction does not use any single ‘best’ value of . It averages over all values of , weighted by their posterior probability.
4.5.0.0.1 The rule of succession.
Suppose every one of observations so far has been a one. The predictive probability that the next is also a one is then . This result is known as Laplace’s rule of succession. Laplace is said to have used it to assess the probability that the sun will rise tomorrow, given that it has risen on every day of recorded history. The example is not to be taken too seriously, since our knowledge of the sun is not well described by exchangeable Bernoulli trials, but the formula makes a reasonable point. However long a run of successes, the predictive probability of success never reaches one, and the probability of a failure, , decreases gradually as the evidence accumulates.
4.6 Beta priors
The uniform distribution is the special case of the Beta family. We now show that the calculation of the previous sections goes through for any Beta prior. Suppose and . Then and so, by the kernel method, The updating rule is simple: add the number of successes to , and the number of failures to .
This suggests a useful way to think about the prior. The prior behaves exactly as though we had begun with a uniform prior and had already observed successes and failures. Alternatively, and more commonly, one says that the prior carries the information of a sample of size in which the proportion of successes is . The quantity is often called the prior sample size. This interpretation helps in choosing a prior: we can set the prior mean to our best guess for , and then choose to reflect how many observations we think our prior knowledge is worth.
4.6.1 The posterior mean as a compromise
The posterior mean shows clearly how prior information and data combine: It is a weighted average of the prior mean and the sample proportion , and the weights are proportional to the prior sample size and the actual sample size . When is small compared with , the posterior mean stays close to the prior mean. As grows, the weight on the data increases and the posterior mean approaches the sample proportion. Similarly, the posterior variance, decreases roughly in proportion to as data accumulate. With plenty of data, then, the posterior is concentrated near the sample proportion whatever (reasonable) prior we began with. This is the precise sense in which the influence of the prior diminishes as evidence accumulates, and in which people with different priors are brought into agreement.
4.6.2 Sequential updating
Suppose the observations arrive one at a time. We may update after each, using the posterior from the first observations as the prior for the th. Starting from , each success adds one to the first parameter and each failure one to the second, so after all observations we arrive at , exactly as if we had processed the data all at once. This is a general property of Bayesian updating with conditionally independent observations, not a peculiarity of the Beta distribution (see Exercise 7.2). Today’s posterior is tomorrow’s prior.
4.6.3 Interpreting a posterior interval
A 95% central posterior interval for is an interval between the and quantiles of the posterior. Its interpretation is direct: given the model, the prior and the data, the probability that lies in the interval is . This is the statement that people often wish to make about a frequentist confidence interval, but cannot, since in the frequentist framework is fixed and the probability refers to the procedure’s behaviour over repeated samples, not to the particular interval computed. The two kinds of interval are often numerically similar, particularly with large samples and vague priors, but they answer different questions.
4.7 Conjugacy
We have seen that a Beta prior combined with binomial data yields a Beta posterior. This property has a name.
Definition 4.2. A class of prior distributions for is conjugate for a sampling model if
The class of Beta distributions is thus conjugate for binomial data. Conjugate priors have obvious advantages. Computing the posterior amounts to updating a few parameters, and the properties of the posterior are those of a familiar distribution. They also make the contribution of the prior easy to interpret, as with the prior sample size above.
Their disadvantage is that a conjugate family may not be flexible enough to represent what we actually believe. A Beta density has at most one mode, for example, and cannot express the belief that is probably either near or near . A useful compromise is a mixture of conjugate priors. If the prior is a mixture of Beta distributions, , then the posterior is also a mixture of Beta distributions, each component updated in the usual way, with the mixture weights themselves updated in proportion to how well each component predicted the data. Any continuous prior on can be approximated arbitrarily well by such a mixture.
In Chapter 10 we shall see that conjugate priors exist for a whole class of models, the exponential families, of which the binomial, Poisson, exponential and normal models are all members.
Exercises
Exercise 4.1
Of 25 items inspected, none is defective. Let be the proportion of defective items in the day’s production, and give a uniform prior.
Find the posterior distribution of .
Find in closed form.
Find the probability that the next item inspected is defective.
Show solutionHide solution
(a) With , and a prior, , with density .
(b) .
(c) . Note that the maximum likelihood estimate, , would say defects are impossible.
Exercise 4.2
Suppose and . Show that the posterior variance of is smaller than the prior variance whenever the observed proportion equals the prior mean . Is the posterior variance always smaller than the prior variance?
Show solutionHide solution
Write . The prior variance is . If , then , so the posterior mean is also and the posterior variance is , which is smaller.
The posterior variance is not always smaller. Take , , and observe one success in one trial. The prior variance is . The posterior is , with variance . A surprising observation can increase uncertainty. On average, however, it cannot: by (2.2), .
5 Poisson data
Reference: Hoff §3.2.
The binomial model describes the number of successes in a fixed number of trials. Many data sets instead record counts with no natural upper limit: the number of times something happened in a given period, or in a given region. The Poisson model is the standard starting point for such data, and its Bayesian analysis runs closely parallel to that of the previous chapter, with the Gamma distribution taking the place of the Beta.
5.1 Setting
We observe counts of events that occur independently of one another, over equal periods of time or within regions of equal size. Examples include the number of cases of a rare disease in a region in each year; the number of radioactive decays from a sample of uranium in each minute; the number of customers arriving at a campus shop between ten and eleven on weekday mornings; and the number of junk emails received in an hour.
Definition 5.1. A random variable has a Poisson distribution with mean if
The sample space is countable, so is discrete, and the parameter space is . The mean and the variance are both equal to : This equality of mean and variance is a strong restriction, and one worth checking against data: counts whose variance is much larger than their mean (which is common) are said to be overdispersed relative to the Poisson model.
The Poisson distribution arises as a limit of the binomial. If , and and in such a way that , then the distribution of converges to . So the Poisson model is appropriate for the number of occurrences of a rare event among a very large number of independent opportunities, which is the situation in each of the examples above.
We use two data sets for illustration. The first records the number of fatal accidents on scheduled airline flights in each year from 1976 to 1985 (GCSR, Exercise 2.13):
| Year | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 |
| Accidents | 24 | 25 | 31 | 31 | 22 | 21 | 26 | 20 | 16 | 22 |
The second records the number of ribwort plantains found in each of 100 equal-sized regions of a plot of land:
| Plants | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9+ |
| Regions | 7 | 17 | 22 | 17 | 15 | 9 | 5 | 4 | 4 | 0 |
5.2 Likelihood
Suppose . The likelihood is Two things are apparent. First, the likelihood depends on the data only through the total , which is therefore a sufficient statistic for : the total number of events is all that matters, not how they were distributed among the periods. Second, as a function of the likelihood has the form . This is the kernel of a Gamma density, which suggests that a Gamma prior will be conjugate.
Definition 5.2. A random variable has a distribution, where (the shape) and (the rate), if its density is Its mean and variance are and , and its mode is if and if .
5.3 Gamma prior, Gamma posterior
With a prior, , and the posterior is By the kernel method, so the Gamma family is indeed conjugate for Poisson data. The updating rule is again simple: add the total count to , and the number of observation periods to .
The interpretation parallels that of the Beta prior. The prior carries the same information as earlier observation periods in which a total of events were seen. The prior mean is thus a prior estimate of the rate, and measures how much weight it carries. The posterior mean is again a weighted average of prior mean and sample mean, with weights proportional to the prior sample size and the actual sample size . The posterior variance, , is approximately when is large, and so shrinks in proportion to .
5.4 Posterior predictive distribution
Suppose we wish to predict a future count , for example the number of airline accidents in 1986. We take to be exchangeable with the observed , so that given it has the same distribution and is independent of them. Its posterior predictive distribution is obtained by averaging the sampling model over the posterior: The second equality uses the conditional independence of and the data given . The predictive distribution incorporates two distinct sources of uncertainty: the variability of a Poisson count about its mean even when the mean is known, and our uncertainty about the mean itself.
The integral can be evaluated directly, but there is a neater route that avoids integration altogether and that works in any conjugate model. Imagine that we have observed as well as . Applying Bayes’ theorem to the new observation, with the current posterior playing the part of the prior, gives Rearranging, This identity holds for every value of . The left-hand side does not involve , so when we substitute the three densities on the right, every occurrence of must cancel, and we may use whatever form of the densities is convenient. All three are known:
, the sampling model;
, the current posterior;
, the posterior we would have after observations, obtained from the updating rule.
Write and for the posterior parameters. Substituting, and, as promised, has disappeared. This is a negative binomial distribution, which we write following Hoff’s parameterisation. You should be aware that there is no agreed parameterisation of the negative binomial; the R function dnbinom, for instance, uses a different one, and it is always worth checking which is in use. In Hoff’s form, the distribution has mean and variance .
The predictive mean and variance can also be found without identifying the distribution, using the identities (2.1) and (2.2): The decomposition of the variance matches the two sources of uncertainty described above. The first term is the Poisson variability we would have if were known exactly. The second is the extra variability due to our uncertainty about . The predictive distribution is therefore overdispersed relative to a Poisson with the same mean. As more data are collected, grows, the second term vanishes, and the predictive distribution approaches a Poisson distribution with mean equal to the estimated rate.
5.5 Sampling from the predictive distribution
For many models the predictive distribution cannot be found in closed form. It is then usually still easy to simulate from it, and the method is worth learning now because it is completely general. Since we can draw from the joint distribution of in two stages:
draw a value from the posterior ;
draw a value from the sampling model , with the parameter set to .
The pair is then a draw from , and so on its own is a draw from the marginal distribution . Repeating the procedure times gives a sample from the predictive distribution, from which we can estimate any summary we like.
For the Poisson model with a Gamma prior, step (a) draws from and step (b) draws from . The resulting draws come from the distribution found above. The recipe needs nothing more than the ability to sample from the posterior and from the sampling model, which is why it will serve us in much more complicated models later.
5.6 Airline accidents
We now analyse the airline data. Let be the number of fatal accidents in year , and suppose . For the prior we take . This has mean and standard deviation , a vague statement that accidents occur at a rate of the order of twenty a year, carrying the weight of only of a year’s data. With years and a total of accidents, Sampling from this posterior in R:
y <- c(24, 25, 31, 31, 22, 21, 26, 20, 16, 22)
n <- length(y)
a <- 1; b <- 0.05; nsamp <- 100000
set.seed(678)
theta.draws <- rgamma(nsamp, a + sum(y), b + n)
quantile(theta.draws, probs = c(0.025, 0.25, 0.5, 0.75, 0.975))
# 2.5% 25% 50% 75% 97.5%
# 20.85750 22.72680 23.74727 24.80283 26.91193
The 95% central posterior interval for the accident rate is about accidents a year. In this case we could have computed it exactly with qgamma, which gives , and the agreement is a useful check on the simulation.
To predict the number of accidents in 1986, we follow the two-stage recipe, drawing a Poisson count for each posterior draw of :
postpred.draws <- rpois(nsamp, theta.draws)
quantile(postpred.draws, probs = c(0.025, 0.25, 0.5, 0.75, 0.975))
# 2.5% 25% 50% 75% 97.5%
# 14 20 24 27 34
So, according to this model, the number of fatal accidents in 1986 would lie between 14 and 34 with probability about . Notice how much wider this is than the interval for . Ten years of data determine the underlying rate quite well, but a single year’s count varies considerably about the rate even when the rate is known. Confusing the two intervals, and reporting the narrower one as a prediction, is a common error.
Exercises
Exercise 5.1
For the airline data with the prior, find the exact mean and variance of the posterior predictive distribution of the 1986 count. Compare the variance with that of a Poisson distribution whose mean is fixed at the posterior mean of .
Show solutionHide solution
The posterior is with and . The predictive mean is . The predictive variance is A Poisson distribution with mean has variance . The extra is the posterior variance of . It is small here because ten years of data determine fairly well.
Exercise 5.2
For the plantain data, take , and find the limit of the posterior distribution of as . No region has nine or more plants.
Show solutionHide solution
There are regions. The total count is The posterior is , which tends to , with mean and standard deviation . The limiting prior, , is improper, but the posterior is proper because the total count is positive.
6 Exponential data
The Poisson model describes how many events occur in a fixed period. The exponential model describes the complementary quantity: how long we wait between events. The two are closely linked, and we shall see that the same Gamma family serves as a conjugate prior for both. The chapter also introduces censored observations, which arise whenever a study ends before every waiting time has been observed.
6.1 Setting
We are interested in the lengths of intervals in time or space between events, and we treat the intervals as independent random variables. Examples include the time until a machine breaks down or a patient relapses, the time between successive visitors to a website, and the distance between potholes along a road.
Definition 6.1. A random variable has an exponential distribution with rate if its density is
The sample space is an interval, so is continuous, and the parameter space is . The mean and variance are so a high rate means short waiting times. The distribution is the special case of the Gamma distribution.
The exponential distribution has a distinctive property: it is memoryless. If , then for all . Having already waited for time makes no difference to how much longer we expect to wait. This is appropriate for events that occur at random at a constant rate, but it may not be for, say, the failure of a machine that wears out with age.
6.2 Likelihood and posterior
Suppose . The likelihood is It depends on the data only through , the total waiting time, which is therefore a sufficient statistic. As a function of it is again a Gamma kernel. With a prior, so The prior carries the information of earlier observations with a total waiting time of .
It is instructive to compare this with the Poisson case. There, the posterior was ; here it is . In both cases the first parameter accumulates events and the second accumulates the time over which they were observed, which is often called the exposure. This is no coincidence. If events occur at random at rate , the waiting times between them are and the count in a period of length one is . Both models describe the same process, and both give information about in the form of events per unit of exposure.
6.3 Posterior predictive distribution
The method of Section 5.4 applies without change. Let and be the posterior parameters. The posterior after one further observation would be , so using . This is a Pareto distribution of the second kind, also called the Lomax distribution. Its tail decreases only as a power of , much more slowly than the exponential tail of any single distribution. The reason is that the predictive distribution is a mixture of exponential distributions with different rates, and the mixture components with small rates, which are not ruled out by the data, contribute long waiting times. This is the continuous analogue of the overdispersion we saw in the Poisson case.
To simulate from the predictive distribution, draw from and then from .
6.4 Leukaemia remission times
We now apply the model to the times of remission, in weeks, of leukaemia patients, from a study by Gehan (1965) reported by Cox and Oakes (1984). Half the patients were allocated at random to be treated with the drug 6-mercaptopurine (6-MP); the other half served as controls. An asterisk marks a censored time, which we discuss in the next section.
| Drug (6-MP) | 6*, 6, 6, 6, 7, 9*, 10*, 10, 11*, 13, 16, 17*, 19*, 20*, 22, 23, 25*, 32*, 32*, 34*, 35* |
| Control | 1, 1, 2, 2, 3, 4, 4, 5, 5, 8, 8, 8, 8, 11, 11, 12, 12, 15, 17, 22, 23 |
We begin with the control group, which has no censored times. Before fitting a model it is sensible to check whether it is plausible. The slides show a histogram of the control times with the density superimposed, where weeks, and a quantile–quantile plot of the sorted times against the corresponding quantiles of that exponential distribution. The points in the quantile–quantile plot lie reasonably close to a straight line, and the exponential model seems adequate.
We take with prior . This prior is equivalent to having seen of an event in one week, and carries very little information. The control group has patients with total remission time weeks, so
The rate is not the most natural quantity to report. Clinicians would rather know the mean remission time, . We could find its posterior distribution with the transformation formula of Section 2.6, but there is a much easier way. If are draws from the posterior of , then are draws from the posterior of :
remistime <- c(1,1,2,2,3,4,4,5,5,8,8,8,8,11,11,12,12,15,17,22,23)
theta.draws <- rgamma(100000, 0.05 + 21, 1 + sum(remistime))
quantile(1/theta.draws, probs = c(0.025, 0.25, 0.5, 0.75, 0.975))
# 2.5% 25% 50% 75% 97.5%
# 5.914584 7.640598 8.832950 10.273225 14.056048
So the mean remission time for control patients lies between about 5.9 and 14.1 weeks with probability . Chapter 8 explains why this simple device of transforming the draws is valid in general.
We can also predict the remission time of a future control patient, by drawing from the posterior and then from . The slides show a histogram of such draws, and ask what is unsatisfactory about it. It is worth considering this before reading further. It may help to ask where the predictive distribution places most of its probability, and to compare that with the remission times actually recorded; and to recall what the memoryless property implies about patients who have just begun remission.
6.5 Censored observations
Twelve of the 21 times in the drug group are marked as censored. For these patients the study ended, or contact with the patient was lost, while they were still in remission. We do not know their remission times; we know only that each was at least as long as the recorded value.
It would be tempting simply to discard these observations, but that would be a serious mistake. The censored patients are precisely those whose remissions lasted longest, so discarding them would make the drug appear much less effective than it is (see Exercise 6.1). Nor can we treat the recorded values as if they were the true remission times, since that would understate them. The correct approach is to use exactly the information we have: that the remission time exceeded the recorded value.
Consider first a single observation, with and , and suppose that we observe not itself but only the event . The likelihood is the probability of what we observed, which is now the probability of that event: The posterior is therefore Compare this with the posterior when the time is observed exactly, . In the language of events and exposure, a censored observation adds its time to the exposure, just as an exact observation does, but it does not add an event, since the event (the end of remission) has not been seen.
With several independent observations, some exact and some censored, the likelihood is the product of the densities for the exact observations and the survival probabilities for the censored ones. If of the observations are exact, and is the sum of all the recorded times, exact and censored, the likelihood is and The general principle, which applies well beyond the exponential model, is that the likelihood should always be the probability of exactly what was observed, no more and no less.
Exercises
Exercise 6.1
For the drug group, use the prior and the result above.
Find the posterior distribution of , the rate for the drug group.
Find and compare it with the same quantity for the control group.
What would the posterior have been had the censored observations been discarded?
Describe how to estimate by simulation, assuming and are independent a priori.
Show solutionHide solution
(a) In the drug group there are exact times, summing to , and censored times, summing to . So and
(b) By Exercise 6.2, weeks. For the control group, weeks.
(c) Discarding the censored times leaves , with weeks. The drug would appear far less effective, because the discarded patients are those with the longest remissions.
(d) Draw and independently, for . Estimate the probability by the proportion of with . The posteriors are independent because the priors are independent and the likelihood factorises into a part for each group. With the estimate is about .
Exercise 6.2
Show that if with , then .
Show solutionHide solution
using the Gamma integral with , and . Note that .
7 Normal data
References: Hoff §5.2–5.3; GCSR §2.5–2.6, §3.2–3.4.
The normal distribution is the most widely used model for continuous data, and its Bayesian analysis introduces two new features. First, the model has two parameters, the mean and the variance, and we must think about prior beliefs on both and about how they interact. Second, the posterior for one parameter when the other is unknown is no longer of the same form as when the other is known, and this is our first encounter with the need to integrate out a parameter that is not of direct interest.
7.1 Setting
The normal model is suitable for quantities that can take any value on the real line and are roughly symmetric about a central value. Its wide applicability is explained, at least in part, by the central limit theorem: a quantity formed as the sum of many small independent contributions is approximately normally distributed, whatever the distributions of the contributions. Examples include the daily change in the logarithm of a stock price, the error in a measurement made by an optical instrument, and the position of an animal moving at random.
Definition 7.1. A random variable has a normal distribution with mean and variance , written , if its density is
Our running example is a set of 100 measurements of the speed of light in air made by Michelson in the summer of 1879. The values are recorded in kilometres per second, with 299 000 subtracted. On this scale the currently accepted value is 734.5.
We consider three cases in turn, each building on the last: the mean unknown with the variance known; the mean known with the variance unknown; and both unknown. The first two are rarely realistic in themselves, since we seldom know one parameter exactly while being uncertain about the other. But they are the building blocks for the third case, and, as we shall see in Chapter 9, for the Gibbs sampler.
Throughout, it helps to think in terms of precision, the reciprocal of a variance. Precision measures how much information a distribution carries: a small variance means a high precision and a sharply defined quantity.
7.2 Mean unknown, variance known
7.2.1 A single observation
We start with the simplest case. Let , where is known, and give a normal prior, , with and fixed. The prior mean is our best prior guess for and the prior variance expresses how uncertain we are about it.
The posterior is proportional to the product of prior and likelihood: The expression in square brackets is a quadratic in , so the posterior is the exponential of a quadratic, which is the form of a normal density. To identify its mean and variance we expand the squares and collect terms in : The terms free of contribute a constant factor to the posterior and may be dropped. Now define With this notation the posterior is In the second step we completed the square by multiplying by , which is permissible because this factor does not involve . The result is the kernel of a normal density, and so The normal prior is therefore conjugate for the normal model with known variance.
The formulae for and have a clear interpretation.
The posterior precision is the sum of the prior precision and the precision of the observation: . Information from the two sources simply adds, and the posterior is always more precise than either the prior or the observation alone.
The posterior mean is a weighted average of the prior mean and the observation, in which each is weighted by its precision. If the prior is vague ( large), the posterior mean is close to the observation; if the measurement is imprecise ( large), it stays close to the prior mean.
7.2.2 Several observations
Now suppose we have observations, , with the same prior. The posterior is where in the last step we dropped , which does not involve , and wrote .
The data now enter only through the sample mean , which is therefore sufficient for . Moreover, the expression has exactly the form we had for a single observation, with replaced by and replaced by . This makes sense: the sample mean has distribution , so observing the whole sample is equivalent, as far as is concerned, to observing its mean, a single observation with precision . Making these substitutions in the single-observation result, So the posterior precision is the prior precision plus the precision of the sample mean, and the posterior mean is a precision-weighted average of the prior mean and the sample mean.
As increases, the data precision grows without limit, while the prior precision stays fixed. Unless is very small, or the prior is very precise compared with a single observation (), the data dominate and The corresponding 95% central posterior interval is approximately . This is numerically the same as the familiar frequentist confidence interval for a normal mean with known variance, a coincidence that recurs in many models when the prior is vague and the sample is large. As discussed in Chapter 4, the interpretation is different: here the interval is a probability statement about given the observed data.
7.2.3 Prediction
Let be a future observation. Given , , independently of the data. It is convenient to write , where is independent of both and the data. Given the data, . So, given the data, is the sum of two independent normal random variables, and is therefore itself normal. (Equivalently, is bivariate normal given , and so is marginally normal.) It remains only to find its mean and variance, which we do with (2.1) and (2.2): Hence The predictive variance is the sum of the sampling variance and the posterior variance of the mean . As in the Poisson case, these reflect two different kinds of uncertainty. The posterior variance can be reduced by collecting more data, and tends to zero as . The sampling variance cannot: however well we know , a single new observation will vary about it with variance .
7.3 Mean known, variance unknown
Next suppose the mean is known and the variance is not: .
The likelihood, regarded as a function of , is This involves a power of multiplied by the exponential of a constant divided by . As a function of the precision it would be a Gamma kernel. As a function of itself it is the kernel of the distribution of the reciprocal of a Gamma variable.
Definition 7.2. If and , we say that has an inverse-gamma distribution and write . By the transformation formula of Section 2.6, with , Its mean is for (Exercise 6.2).
We therefore take an inverse-gamma prior for . For the sake of interpretation it is convenient to write its parameters as and : The reason for this choice will become clear in a moment. Let be the mean squared deviation of the observations from the known mean. Then which is an inverse-gamma kernel. Hence and the inverse-gamma prior is conjugate.
The parameterisation now explains itself. In the likelihood, is the number of observations and is their sum of squared deviations. In the prior, plays the part of a number of observations and that of a sum of squares. So the prior carries the information of observations whose mean squared deviation is , and updating consists of adding the actual sample size to the prior sample size and the actual sum of squares to the prior sum of squares:
7.4 Both mean and variance unknown
In practice both parameters are usually unknown, and we need a joint prior for . Two choices are common. The conjugate prior, which we treat here, makes and dependent a priori. The semi-conjugate prior, treated in Hoff §6.1–6.3, makes them independent a priori; its posterior is not of a standard form, and it is most easily handled with the Gibbs sampler of Chapter 9 (see Exercise 9.2).
7.4.1 The conjugate prior
The conjugate model is The prior is specified in two stages: a marginal prior for of the kind used in the previous section, and a conditional prior for given . Since the conditional prior for involves , the two parameters are dependent a priori: the larger the variance of the observations, the less certain we are about their mean.
The prior variance of , , has been written as a multiple of the sampling variance. The effect is that our prior information about is expressed in units of observations. Comparing with the result of Section 7.2, where the sample mean of observations had variance , we see that the prior for is equivalent to the information in observations with mean . Similarly the prior for is equivalent to observations with mean squared deviation . This is a natural and convenient way to specify a prior when our prior knowledge really can be thought of as coming from an earlier sample. It is less natural if, for example, we have firm knowledge about from a source that has nothing to do with the variability of the measurements. Another way to see the structure is that the prior on given implies so the prior fixes our uncertainty about the mean measured in units of the standard deviation.
7.4.2 The posterior
Theorem 7.3. Under the conjugate prior, where with and .
Proof. The joint posterior can be written , and we find the two factors in turn.
The conditional posterior of . For fixed , the model for is exactly that of Section 7.2, with prior variance . The prior precision is and the data precision is . They add to give posterior precision , and the posterior mean is the precision-weighted average .
The marginal posterior of . We need the identity which follows by writing and noting that the cross term sums to zero. The joint posterior is proportional to prior times likelihood: The two quadratics in can be combined by completing the square: (This can be checked by expanding both sides.) Substituting, the joint posterior becomes where is as defined in the statement. To find the marginal posterior of we integrate over . The second factor is, apart from the constant , a normal density in with variance , and so integrates to a constant that does not depend on . What remains is the first factor, which is the stated inverse-gamma kernel. ◻
The updating rules are the natural extension of those we have seen. The prior sample sizes and each increase by . The posterior mean is the weighted average of prior mean and sample mean, with weights and . The posterior sum of squares has three parts: the prior sum of squares ; the sum of squares within the sample, ; and a term that measures the disagreement between the prior mean and the sample mean. If the data turn out to be centred far from where the prior expected, this last term is large and our estimate of the variance increases, which is sensible, since such a discrepancy is itself evidence of greater variability than we supposed.
7.4.3 Simulating from the posterior
The factorisation tells us how to simulate from the joint posterior. For :
draw from the marginal posterior , which we do by drawing from the distribution and taking the reciprocal;
draw from the conditional posterior , using the value of just drawn.
Each pair is then an independent draw from the joint posterior. In R:
normalconj <- function(nsamp, y, nu0, sigma0, mu0, kappa0) {
n <- length(y); ybar <- mean(y); s2 <- var(y)
kappan <- kappa0 + n
mun <- (kappa0 * mu0 + n * ybar) / kappan
nun <- nu0 + n
sigman2 <- (nu0 * sigma0^2 + (n - 1) * s2 +
(kappa0 * n / kappan) * (ybar - mu0)^2) / nun
sigma2.draws <- 1 / rgamma(nsamp, nun / 2, nun * sigman2 / 2)
theta.draws <- rnorm(nsamp, mun, sqrt(sigma2.draws / kappan))
list(theta = theta.draws, sigma2 = sigma2.draws)
}
The draws taken on their own are a sample from the marginal posterior of , which is usually the distribution of main interest. Here is what is called a nuisance parameter: it must be included in the model, but we are not directly interested in it, and simulation lets us account for our uncertainty about it simply by ignoring the draws at the end.
7.4.4 The marginal posterior of
In this model the marginal posterior of can also be found exactly: a distribution with degrees of freedom. To see this, integrate out of the joint posterior found in the proof above. As a function of , the joint density is which is an inverse-gamma kernel with shape and scale . The integral of an kernel over is , so which is the kernel of the stated distribution. So uncertainty about turns what would have been a normal posterior for (if were known) into a posterior, which has heavier tails. With large, as it is when is large, the distribution is close to the normal and the distinction matters little. The result is the Bayesian counterpart of the familiar interval for a normal mean, and with a vague prior () the two coincide numerically.
7.4.5 Prediction
The posterior predictive density of a future observation is To draw from it we follow the usual procedure: draw from the joint posterior as above, and then draw from . In this model an exact result is also available: The argument is the same as for the marginal posterior of . Given , the result of Section 7.2.3 gives , and integrating over the inverse-gamma posterior of turns this normal into a .
7.4.6 Michelson’s data
For the Michelson data, , and . The slides show 10 000 draws from the joint and marginal posteriors under two priors:
, , , ;
, , , .
The two priors differ considerably in their means, but in both cases and are small compared with , so the prior carries the weight of at most one observation and the posteriors are dominated by the data. The two sets of plots are accordingly very similar. The posterior for is concentrated around 850, with a 95% interval roughly 16 units either side (Exercise 7.1).
Both posteriors lie far from the accepted value of 734.5. This is not a failure of the Bayesian method but of the model. The model assumes that the measurements are centred on the true speed of light, and Michelson’s apparatus in 1879 was evidently subject to a systematic error of which he was unaware. The posterior faithfully reports what the data say under the assumptions made; it cannot correct assumptions that are wrong. The example is a useful reminder that a posterior distribution describes uncertainty within a model, and that the model itself deserves scrutiny.
Exercises
Exercise 7.1
For the Michelson data under the first prior above, compute , , and . Hence give a 95% central posterior interval for and a 95% predictive interval for a new measurement.
Show solutionHide solution
With , , , , , and : so and . The posterior scale for is , and . The 95% posterior interval for is For a new measurement the scale is , giving . The accepted value lies well outside the interval for and inside the predictive interval: a single measurement near the true value would not be unusual, but the average of Michelson’s measurements is far from it.
Exercise 7.2
In the model with known, show that updating the prior with , and then updating the resulting posterior with , gives the same result as updating the prior with at once.
Show solutionHide solution
After the posterior has precision and mean . Using this as the prior for gives precision and mean which is the posterior from with . The result holds for any model with conditionally independent observations, since .
8 Monte Carlo methods
Reference: GCSR §1.9; Hoff Chapter 4.
We have already used simulation several times: to compute posterior intervals, to find the posterior of , and to draw from predictive distributions. This chapter explains why these methods work and how accurate they are. The ideas are simple, but they are the foundation of nearly all modern Bayesian computation, since in realistic models the integrals required by Bayes’ theorem can almost never be evaluated exactly.
8.1 The idea
Suppose we want to know a number , and that computing it exactly is impossible, complicated or slow, while a good approximation would serve our purpose. If can be written as the expectation of some random variable, , and if we can draw samples from the distribution of , then we can estimate by the sample mean where are independent draws. This is the Monte Carlo method, named after the casino.
Two familiar results justify it. By the law of large numbers, as , so the estimate can be made as accurate as we like by taking enough draws. And by the central limit theorem, if is finite then, for large , This tells us how accurate the estimate is. Its standard deviation, the Monte Carlo standard error, is , which we estimate by , where is the standard deviation of the draws. An approximate 95% interval for is .
A simple illustration is the estimation of an area. Suppose a region of the plane, perhaps the union of several overlapping circles as on the slides, is awkward to measure, but lies inside a rectangle whose area we know. Draw points independently and uniformly at random in , and let if the th point falls in and otherwise. Then , so the proportion of points falling in , multiplied by the area of , estimates the area of . All we need is a way to tell whether a given point lies in .
8.2 Simulation in Bayesian inference
Now consider a parameter vector with joint posterior . We are often interested in only one component, and so need its marginal posterior, For most models this integral has no closed form, and for all but small even numerical integration is difficult, because the number of points needed on a grid grows exponentially with the dimension.
Suppose instead that we can draw a sample from the joint posterior. Then the th components of these draws, , form a sample from the marginal posterior . This follows directly from what a marginal distribution is: the distribution of one coordinate of the random vector, whatever the others happen to be. So to marginalise a sample we simply ignore the coordinates we are not interested in. No integration is required. We used exactly this device for the nuisance parameter in the previous chapter.
From the sample we can estimate any summary of the marginal posterior:
the posterior mean , by the sample mean ;
the posterior median, the value such that , by the sample median of the draws;
a 95% central posterior interval , with , by the and sample quantiles of the draws. With , these are approximately the 250th and 9751st values when the draws are sorted into increasing order.
Each of these is itself a Monte Carlo estimate, with an error that decreases as increases.
8.3 Functions of parameters
Often the quantity of interest is not a parameter itself but some function of the parameters, . The mean remission time was one example. Others are the difference between two rates, the ratio of a standard deviation to a mean, or the probability that one treatment is better than another. The formulation is very general. It includes , and also indicator functions: if then , so posterior probabilities of events are also posterior expectations.
To find analytically, one would transform from to new variables , find their joint density using the Jacobian of the transformation, and integrate out . This is laborious even when it is possible.
By simulation it is almost trivial. Given draws from , compute These are draws from , because each is the value of at a random drawn from the posterior, which is exactly what it means for to have the distribution . Summaries of are then estimated from the as above.
8.4 An example
The following example, in which the exact answer is known, lets us check the method. Suppose are independent random variables, and let We draw samples of and use them to estimate , the standard deviation of , and the interquartile range of . In R, we generate the draws as a matrix, one row per draw of , and apply to each row:
theta.samp <- matrix(runif(10000 * 20, 0, 1), nrow = 10000)
psi.samp <- -rowSums(log(theta.samp))
mean(psi.samp) # 20.01562
sd(psi.samp) # 4.464726
mean(psi.samp > 30) # 0.0204
IQR(psi.samp) # 5.992474
Note that the estimate of is simply the proportion of draws exceeding 30, the sample mean of the indicator .
In this example simulation is not really needed, since one can show that (Exercise 8.1). The exact values of the four summaries are , , and , and the simulation estimates are close to all of them. A histogram of the draws with the density superimposed, shown on the slides, confirms the agreement.
If the estimates are not accurate enough, the remedy is to increase . Since , the standard error decreases in proportion to , so halving it requires four times as many draws. Precision is bought slowly. On the other hand, it is entirely under our control, which the sample size of the data usually is not, and with modern computers in the tens or hundreds of thousands is seldom a burden.
Exercises
Exercise 8.1
Show that if then . Deduce that in the example above has a distribution.
Show solutionHide solution
For , , the distribution function. So is a sum of independent variables, that is, of variables with a common rate. By the result of Exercise 2.2, applied repeatedly, sums of independent Gamma variables with a common rate are Gamma, with the shapes added. Hence .
Exercise 8.2
In the example above, find the Monte Carlo standard error of the estimate of when . How large must be for the standard error to be below ?
Show solutionHide solution
The estimate is a mean of Bernoulli variables with . Its standard error is . For a standard error below we need .
9 Markov chain Monte Carlo
The methods of Chapter 8 require independent draws from the posterior distribution. For the conjugate models we have studied these are easy to obtain, because the posterior is a standard distribution for which sampling routines exist. For most other models they are not. The posterior is known only up to its normalising constant, as the product of prior and likelihood, and it is not of any recognisable form.
Markov chain Monte Carlo (MCMC) methods overcome this difficulty. Rather than drawing independent samples, they construct a sequence of dependent draws, each generated from the one before, in such a way that the distribution of the draws approaches the posterior as the sequence continues. Two features make them so widely useful. They require the posterior density only up to a constant, which is exactly what Bayes’ theorem provides without further work. And the individual steps are simple, usually involving only low-dimensional distributions, even when the posterior itself is high-dimensional. Once we have a long enough sequence of draws, we use it just as we used independent draws in Chapter 8.
9.1 Markov chains and stationary distributions
We recall a few facts from the theory of Markov chains, which you will have met in Applied Probability. A sequence of random variables is a Markov chain if the distribution of each , given all the earlier values, depends only on the immediately preceding value . The chain is described by its transition kernel , the probability of moving to state from state . (For continuous states, is a density in .)
A distribution is stationary for the chain if, whenever has distribution , so does : Under mild conditions (roughly, that the chain can reach every region of the state space and does not cycle periodically), a chain with stationary distribution converges to it: whatever the starting value, the distribution of approaches as , and averages along the chain converge to expectations under . So if we can design a chain whose stationary distribution is the posterior, and run it for long enough, its later values can be treated as draws from the posterior.
The following condition is the usual tool for checking that a given distribution is stationary.
Theorem 9.1 (Detailed balance). If a distribution and a transition kernel satisfy then is a stationary distribution of the chain with kernel .
Proof. Sum both sides over . The left-hand side becomes . The right-hand side becomes , since the transition probabilities out of sum to one. ◻
One way to picture detailed balance is to imagine a large population of walkers distributed across the states according to , each moving according to . The left-hand side is the rate at which walkers flow from to , and the right-hand side the rate from to . If these flows balance for every pair of states, the overall distribution of walkers does not change. Detailed balance is sufficient for stationarity but not necessary; a chain can have as its stationary distribution without satisfying it, as we shall see.
9.2 The Gibbs sampler
Let be the distribution we wish to sample from, the target. In our applications it is a posterior, but the method does not depend on this. The Gibbs sampler proceeds as follows.
Gibbs sampler. Choose a starting point . For , and for in turn, draw
In words, we cycle through the components, and update each by drawing a new value from its full conditional distribution, its distribution given the current values of all the other components. Components already updated in the current sweep are conditioned on at their new values, and the rest at their old values. The claim is that the vectors , for , form a Markov chain whose stationary distribution is . They are therefore, after an initial period, correlated draws from .
The method is useful because full conditional distributions are often easy to sample from even when the joint distribution is not. The full conditional of is proportional to the joint density regarded as a function of alone, with the other components held fixed, and in many models (particularly those built from conjugate pieces) it turns out to be a standard distribution. We shall see an example in the hierarchical model of Chapter 11, and another in Exercise 9.2.
9.2.1 Why the Gibbs sampler works
We give the argument for a discrete state space. The continuous case is the same, with sums replaced by integrals.
Define equivalence relations on the set of states. For each , say that if for all : that is, and agree in every coordinate except possibly the th. The equivalence class of under is the set of states reachable from by changing its th coordinate alone. Let be the total probability of that class.
Consider a single update of coordinate . It moves from state to state with probability This is exactly a draw from the full conditional of : the chain can move only within the equivalence class of its current state, and it chooses a state in that class with probability proportional to . The division by makes the probabilities sum to one over the class.
We now check detailed balance for . If then also , because an equivalence relation is symmetric, and both sides of the detailed balance equation are zero. If , then and lie in the same equivalence class, and so the class totals agree: . Hence So each single-coordinate update satisfies detailed balance with respect to , and therefore leaves stationary.
One complete sweep of the Gibbs sampler applies the updates in turn. If the state at the start of the sweep has distribution , then after applying it still has distribution ; after it still does; and so on to the end of the sweep. So is stationary for the sweep as a whole. It is worth noticing that the complete sweep does not in general satisfy detailed balance, since running the updates in reverse order is not the same as running them forwards. This does not matter, since detailed balance is only a sufficient condition and we have established stationarity directly.
An alternative is the random-scan Gibbs sampler, which at each step chooses one coordinate at random, with probability , and updates only that coordinate. Its transition kernel is the average , and since each satisfies detailed balance, so does the average. The version on the lecture slides is of this kind, with the factor absorbed into the normalising constants.
9.2.2 Using the output
The draws from a Gibbs sampler, or from any MCMC method, differ from the independent draws of Chapter 8 in two respects, and both need attention in practice.
First, the chain starts from an arbitrary point, which may lie in a region of low posterior probability, and it takes some time to reach the region where the posterior is concentrated. The early draws are therefore not representative of the posterior, and are usually discarded as burn-in. A plot of the draws against the iteration number, called a trace plot, is the simplest way to judge how long this takes: after burn-in the trace should wander around a stable level with no visible trend. Running several chains from widely separated starting points, and checking that they settle in the same place, is a more thorough check.
Second, successive draws are correlated, because each is generated from the one before. The law of large numbers still holds, so averages along the chain still converge to posterior expectations, but a correlated sample carries less information than an independent sample of the same size, and the Monte Carlo error is larger. The Gibbs sampler moves slowly when components of are strongly correlated in the target, since each update changes one coordinate while holding the others fixed, and so can take only small steps along a narrow ridge of high probability. Exercise 9.1 makes this precise for a bivariate normal target. When this happens, the chain must be run for much longer, or the model reparameterised to reduce the correlation.
The Gibbs sampler takes its name from the physicist Josiah Willard Gibbs, through its connection with the distributions of statistical mechanics. It was introduced to statistics by the brothers Stuart and Donald Geman in 1984, in work on the restoration of noisy images, and was brought to the attention of Bayesian statisticians generally by Gelfand and Smith in 1990.
9.3 The Metropolis–Hastings algorithm
The Gibbs sampler requires us to draw from every full conditional distribution. When some full conditional is not a standard distribution, we need another way to generate a move. The Metropolis–Hastings algorithm provides one. It requires only that we can evaluate the target density up to a constant, and that we can draw from some convenient proposal distribution of our choosing.
Let be the target density, known up to a constant, and let be a proposal density, which suggests a new value given the current value .
Metropolis–Hastings. Choose . For :
draw a proposal from ;
compute the acceptance probability
with probability accept the proposal and set ; otherwise reject it and set .
The target enters only through the ratio , in which any normalising constant cancels. This is the property that makes the algorithm so useful for Bayesian computation: we can take , the unnormalised posterior, and never compute the marginal likelihood.
The rule has an intuitive reading, most easily seen when the proposal is symmetric, . The ratio of proposal densities is then one, and . A proposal to move to a point of higher posterior density is always accepted. A proposal to move to a point of lower density is accepted with probability equal to the ratio of the densities, so that downhill moves are possible but become less likely the further downhill they go. The chain thus spends most of its time where the posterior density is high, but still visits regions of lower density in the correct proportion. This special case, with a symmetric proposal, is the original algorithm of Metropolis and his colleagues. A common choice is the random-walk proposal , with . The ratio in the general algorithm, introduced by Hastings in 1970, corrects for any asymmetry in the proposal, so that a proposal which tends to suggest moves in one direction does not bias the chain in that direction.
9.3.1 Why Metropolis–Hastings works
Detailed balance is again the tool. For , the chain moves from to only by proposing and then accepting it, so its transition density is where denotes the probability of accepting a proposed move from to . Substituting into the detailed balance equation, , we require or equivalently Any acceptance rule satisfying this condition gives a chain with stationary distribution . The Metropolis–Hastings choice is . For the reverse move the ratio is , so . If , the ratio of the two acceptance probabilities is ; if , it is . In either case the condition holds. Moves in which the chain stays where it is (because a proposal was rejected) satisfy detailed balance trivially, since both sides involve the same state.
Other acceptance rules also satisfy the condition, but the Metropolis–Hastings rule accepts proposals as often as possible, since one of and is always equal to one. Frequent acceptance means the chain moves more and explores the target more quickly.
9.3.2 Choosing the proposal
The algorithm is correct for almost any proposal, but its efficiency depends strongly on the choice. With a random-walk proposal, the scale matters. If is very small, nearly every proposal is accepted, but each moves the chain only a short distance, and it explores the target slowly. If is very large, most proposals land in regions of low density and are rejected, and the chain stays in one place for long periods. Either way successive draws are highly correlated. A useful rule of thumb for random-walk proposals is to adjust until roughly a quarter to a half of proposals are accepted, and trace plots help to judge whether the chain is moving well.
The algorithm was published in 1953 by Nicholas Metropolis, Arianna and Marshall Rosenbluth, and Augusta and Edward Teller, in a paper on the simulation of the physical properties of materials. Historical accounts now credit much of the work to the Rosenbluths.
9.3.3 Metropolis within Gibbs
The two methods combine naturally. In a Gibbs sampler, a full conditional that cannot be sampled directly may be replaced by a single Metropolis–Hastings step that has that full conditional as its target. Since the Metropolis–Hastings step leaves its target stationary, it leaves the joint distribution stationary in the same way that an exact Gibbs update does, and the argument of the previous section goes through unchanged. This is called Metropolis-within-Gibbs, and it is how the hierarchical model of Chapter 11 is fitted in practice.
Exercises
Exercise 9.1
Let have a bivariate normal distribution with zero means, unit variances and correlation .
Write down the full conditional distributions.
Write
Rcode for a Gibbs sampler.Show that, when the chain is stationary, successive draws of have correlation . What happens as ?
Show solutionHide solution
(a) and .
(b)
gibbs.bvn <- function(K, rho, start = c(0, 0)) {
out <- matrix(NA, K, 2)
th <- start
for (k in 1:K) {
th[1] <- rnorm(1, rho * th[2], sqrt(1 - rho^2))
th[2] <- rnorm(1, rho * th[1], sqrt(1 - rho^2))
out[k, ] <- th
}
out
}
draws <- gibbs.bvn(5000, rho = 0.9)
plot(draws[, 1], type = "l") # trace plot
(c) Given , the next has mean , and the next has mean times that. So . At stationarity both have variance one, so the correlation is . As successive draws become nearly identical and the chain explores the distribution very slowly. Many more draws are needed for a given Monte Carlo precision.
Exercise 9.2
Consider the normal model with the semi-conjugate prior: , with and independent a priori. Find the full conditional distributions of and , and describe a Gibbs sampler for the joint posterior.
Show solutionHide solution
Given , the model for is the known-variance model of Section 7.2. So Given , the model for is the known-mean model. So The Gibbs sampler starts from some , perhaps , and alternates: draw from the first distribution with ; then draw from the second with . Note that and must be recomputed at every iteration, since they depend on the current . This is Hoff’s example in §6.3.
10 More on priors
So far we have chosen priors largely for convenience, usually from a conjugate family, and have interpreted their parameters as the information in an imaginary earlier sample. This chapter looks more closely at the choice of prior. We first show that conjugate priors exist for a whole class of models and that the ‘imaginary data’ interpretation holds throughout that class. We then turn to the harder question of what prior to use when we have, or wish to claim, little prior information.
10.1 Exponential families and conjugate priors
Reference: Hoff §3.3.
A one-parameter exponential family is a model whose density or mass function can be written in the form Here is called the natural parameter and the sufficient statistic. The essential feature is that the data and the parameter interact only through the product in the exponent. Many standard models have this form once the parameter is suitably transformed.
Example 10.1 (Bernoulli). So , , and the natural parameter is the log-odds . Inverting, and , so .
Example 10.2 (Poisson). So , , and .
The exponential model, and the normal model with either the mean or the variance known, can be written in the same form (see Exercise 10.3 for the first of these).
10.1.1 The conjugate prior
For any one-parameter exponential family, consider a prior for the natural parameter of the form where and are constants. After observing independently from the model, the posterior is where is the average of the sufficient statistics. The posterior has the same form as the prior, with new constants, so this family of priors is conjugate. The updating rule is:
becomes ;
becomes , a weighted average of and with weights and .
The interpretation we have met in each particular model now appears in general. The prior carries the same information as imaginary observations whose sufficient statistics average . This gives a practical recipe for choosing a prior: set to your best prior guess for the average value of , and use to express how confident you are in that guess, in units of observations. A small value, say , gives a vague prior whose influence on the posterior will soon be swamped by the data.
To see that this reproduces the conjugate priors we already know, we transform back from to the original parameter , remembering to include the Jacobian.
Example 10.3 (Bernoulli). The conjugate prior is . With we have and , so the induced prior on is This is the distribution. So we recover the Beta prior, with (the prior sample size) and (the prior mean).
Example 10.4 (Poisson). The conjugate prior is . With , , and the induced prior on is the distribution. We recover the Gamma prior, with observation periods and total count .
10.2 Non-informative priors
References: GCSR Chapter 2; Lee §2.4.
Every Bayesian analysis requires a prior. Since the posterior is proportional to prior times likelihood, the prior can in principle have a large influence on the conclusions. In simple problems with a moderate amount of data this influence is usually small, as we have seen repeatedly. But it is not always small. With a parameter of moderate or high dimension, a prior that seems harmless for each component separately may be highly informative about some function of the components. And in some applications there is simply no agreed prior information, or there is a wish to present an analysis whose conclusions do not appear to depend on anyone’s particular beliefs.
This has motivated a long search for priors that play a minimal role in the analysis, and that ‘let the data speak for themselves’. Such priors go by many names: vague, flat, diffuse, reference, objective, non-informative. None of these names should be taken quite literally. As we shall see, there is no prior that represents complete ignorance in every respect, and the search is better understood as one for priors that are reasonable defaults.
10.3 Improper priors
A natural way to make a prior uninformative is to make it very spread out, and the limit of this process often leads to a ‘density’ that cannot be normalised.
A prior is proper if it integrates to one. If with finite, then can be made proper by dividing by , so only the shape of a prior matters. If the integral is infinite, the prior is improper. An improper prior is not a probability distribution, and cannot literally represent anyone’s beliefs. It may nonetheless be used, provided the resulting posterior is proper, that is, provided . The posterior can then be interpreted as an approximation to the posterior under a proper but very diffuse prior.
10.3.1 Binomial model
In the binomial model with a prior, we interpreted and as prior numbers of successes and failures. It seems natural, then, to express the absence of prior information by setting . This corresponds to which is called the Haldane prior. Its integral over is infinite, since near each end the integrand behaves like or : So the Haldane prior is improper. Nevertheless, setting in the posterior formula gives , which is a proper distribution provided both and . If, however, every observation is a success, or every observation is a failure, the posterior is improper and the analysis breaks down. The quality control data of Exercise 4.1, with no defective items, are an example where the Haldane prior cannot be used.
This suggests a safe procedure for using improper priors:
find the posterior under a proper conjugate prior;
let the hyperparameters tend to the values that give the improper prior ( in this example);
if the limit is a proper distribution, it may be used as the posterior.
10.3.2 Normal model with known mean
With , the parameter is the number of observations the prior is worth. Letting seems the natural way to express ignorance. In the limit the prior density becomes , which has infinite integral over (the integral diverges at both ends), so the limiting prior is improper. Setting in the posterior, however, gives which is proper for any provided .
In both examples an improper prior led to a proper posterior, at least for most data sets. This does not always happen, and in complicated models it can fail in ways that are not obvious. An improper prior places on its user the burden of proving that the posterior is proper. MCMC methods will happily produce output from an improper posterior, and that output will be meaningless.
10.4 Jeffreys’ prior
The uniform prior has an obvious appeal as an expression of ignorance, but it has a serious defect, which we noted in Section 2.6. If we know nothing about a parameter , then presumably we know nothing about any one-to-one function of it, . A rule for choosing non-informative priors ought therefore to give consistent answers whether it is applied to or to . But the prior densities for and must be related by the transformation formula, so a prior that is uniform in is not uniform in unless is linear. For example, a uniform prior on the success probability of a binomial model is not uniform on the log-odds. The rule ‘use a uniform prior’ therefore gives different answers depending on which parameterisation we happen to start from, and this is unsatisfactory.
Jeffreys proposed a rule that does not suffer from this defect. It takes where is the Fisher information of the model, (The two expressions are equal under mild regularity conditions, and the second is usually easier to compute.) The Fisher information measures how sharply, on average, the likelihood discriminates between nearby values of . Jeffreys’ prior is therefore larger where the data are expected to be more informative. The key property is that it transforms correctly.
Lemma 10.5. Let be a one-to-one, continuously differentiable transformation. Then
Proof. The model is the same whichever parameter we use to describe it, so when . Differentiating with respect to by the chain rule, Now square both sides and take expectations over , conditional on on the left and on the corresponding on the right. The factor is not random and comes outside the expectation, giving the result. ◻
Suppose, then, that we apply Jeffreys’ rule to , taking . The prior this induces on is, by the transformation formula and the lemma, This is exactly what we would have obtained by applying Jeffreys’ rule to directly. The rule gives the same answer whichever parameterisation we begin with, which is the consistency we asked for.
Example 10.6 (Normal variance). Let , with known and unknown. Then Since , we have , and so Jeffreys’ prior is therefore . This is the same improper prior that we obtained in the previous section by letting in the conjugate prior, so two quite different lines of argument lead to the same default choice.
Jeffreys’ prior is widely used, but it should not be regarded as the final answer to the problem of representing ignorance. It is often improper, so the propriety of the posterior must be checked. Its invariance is a property of the rule, not a demonstration that the resulting prior expresses no information. And for parameters of more than one dimension, the natural generalisation, , can give unsatisfactory results; Jeffreys himself recommended against using it in some multi-parameter problems.
Exercises
Exercise 10.1
Find Jeffreys’ prior for:
in the model;
in the model, with observations.
In each case state whether the prior is proper, and give the posterior.
Show solutionHide solution
(a) , so Taking expectations with gives . So , the distribution. It is proper. The posterior is .
(b) For one observation, , with expectation . For observations . So , which is improper on . It is the limit of as . The posterior is , which is proper for any data.
Exercise 10.2
In the normal model with known mean, find Jeffreys’ prior for the standard deviation directly. Check that it agrees with the prior after a change of variable.
Show solutionHide solution
With , with expectation . So . Starting instead from and changing variable, . They agree, as the lemma requires. The prior is also equivalent to a uniform prior on .
Exercise 10.3
Write the model in exponential-family form. Find the prior on induced by the conjugate prior for the natural parameter.
Show solutionHide solution
. Take , so that , with , for , and . The conjugate prior is . Since , the distribution. The shape is rather than because the natural parameter here is linear in , so there is no Jacobian factor as in the Poisson case. The prior still carries imagined observations with mean , since the posterior is .
11 Hierarchical models
Reference: GCSR §5.1–5.3; Hoff Chapter 8.
In every model so far, the data have come from a single population described by a single parameter, or a single vector of parameters. Many data sets are made up of several related groups: patients in different hospitals, pupils in different schools, experiments conducted in different laboratories. Each group has its own parameter, but the groups are similar enough that knowing about some of them tells us something about the others. Hierarchical models are the Bayesian way of expressing this, and they bring together nearly every idea in the course: exchangeability, conjugacy, prediction and MCMC.
11.1 Several binomial experiments
Suppose we have the results of binomial experiments, each with its own success probability . How should we analyse them?
At one extreme, if we believe the are completely unrelated, we can analyse each experiment separately, exactly as in Chapter 4. We would give each its own prior, perhaps with fixed and , or perhaps the same for every , and obtain from the th experiment alone. At the other extreme, if we believe all the are equal, we can pool the experiments into a single large one. Neither extreme is usually right.
Often the are related but not identical, so that knowing one of them gives some information about the others. For example:
might be the probability that drug produces a certain effect, where the drugs all belong to the same family of chemical compounds;
might be the mortality rate from a certain disease in city ;
might be the probability that a laboratory rat in experiment develops a tumour when given a dose of a certain drug.
In such cases it is natural to regard the as a sample from some common population of values, and to use what we learn about that population to inform our estimate of each individual .
11.2 Rat tumour data
Our example comes from GCSR §5.1. In the current experiment, 4 of 14 laboratory rats developed a certain kind of tumour. The results of 70 earlier experiments with rats of the same strain are also available. The earlier tumour rates have mean and standard deviation , and in 14 of those experiments no tumours were observed.
Analysing the current experiment alone, with a uniform prior, gives , with mean . This takes no account of the earlier experiments, which suggest that tumour rates are usually lower than this. How should we use the historical data to improve our inference about ?
11.2.1 Empirical Bayes
One simple approach is to use the historical data to choose a prior for . We seek a distribution whose mean and variance match the sample mean and sample variance of the 70 earlier rates: Solving these two equations for and gives With and this yields and . The prior has mean and is worth about ten observations. Combining it with the current data gives the posterior , with mean . The estimate has been pulled well down from the raw rate of , towards the historical average.
This approach, in which the prior is estimated from the data, is called empirical Bayes. It is practical and often gives sensible answers. But it has two weaknesses. It treats the estimated values of and as if they were known exactly, and so understates our uncertainty; with only 70 earlier experiments, and are in fact rather uncertain. And the moment-matching method, while simple, is somewhat arbitrary. The hierarchical model addresses both points.
11.3 The hierarchical model
The fully Bayesian approach is to treat the unknown and as parameters like any other, and to give them a prior distribution. In general terms, suppose If we have no information that distinguishes the groups from one another before seeing the data, we should judge exchangeable. De Finetti’s theorem then tells us to model them as conditionally i.i.d. given some further parameter , called a hyperparameter: and to give a prior distribution of its own, . For the binomial experiments, and . The distribution describes the population from which the group parameters are drawn, and describes the characteristics of that population, such as its mean and spread.
The model is called hierarchical because it has several levels:
the prior distribution of the hyperparameter ;
the distribution of the group parameters given ;
the distribution of the data given the group parameters .
It can be represented by a directed acyclic graph (DAG), with a node for each random quantity and an arrow from to each , and from each to the corresponding . The arrows show the order in which the model generates the quantities: first , then the given , then the data given the .
11.3.1 Conditional independence and the sharing of information
The DAG also encodes conditional independence. In such a graph, each variable is conditionally independent of the variables that are not its descendants, given its parents (the variables with arrows pointing into it). So, given , the observation is independent of and of all the other s and s, and Similarly, given , the are independent of one another.
But is unknown, and this is what makes the model useful. If we were told the value of , say, this would change our beliefs about , the characteristics of the population from which was drawn. And through it would change our beliefs about . In the same way, the data from each experiment inform us about , and hence about every other experiment. Information is shared across the experiments by way of the hyperparameter. This is exactly the dependence through an unknown common parameter that we met in Chapters 2 and 3, now operating one level higher.
It is worth stressing that the DAG describes the joint distribution before any data are observed. Once we condition on the data, the conditional independence relations it displays generally no longer hold for the posterior distribution of the parameters.
11.3.2 The posterior
The unknowns are now both the group parameters and the hyperparameter . Their joint posterior is where the factorisation follows the levels of the hierarchy. With experiments, has 71 components and the posterior has 73 dimensions. Direct integration is out of the question, but the structure of the posterior is well suited to the Gibbs sampler.
11.4 The rat tumour example
The full model is
11.4.1 The prior on
The parameters and are not easy to think about directly. It is more natural to work with , the equivalent number of observations carried by the population distribution, and , the mean of the population distribution, which is the prior expectation of each . The lecture example uses independent priors and with . This says that we have no prior preference for the average tumour rate, and that we expect the population of rates to be about as concentrated as a Beta distribution worth twenty or so observations, while allowing values of much larger or smaller. Exercise 11.1 derives the corresponding prior on . GCSR use a different prior, , which is improper; see their §5.3 for the reasoning behind it.
11.4.2 A Gibbs sampler
We sample from the posterior with a Gibbs sampler, alternating between the group parameters and the hyperparameters.
Update the . The full conditional of is proportional to the joint posterior regarded as a function of , which involves only the factors . This is a Beta prior times a binomial likelihood, and by the conjugate result of Chapter 4, The are conditionally independent given , and the data, so all 71 can be drawn at once.
Update . The full conditional of involves the prior and the Beta densities of the current : The data do not appear directly, because given the the hyperparameters are independent of the data. This full conditional is not a standard distribution, so we replace the exact draw by a Metropolis–Hastings step, perhaps a random walk on , as described at the end of Chapter 9.
In practice one rarely writes such samplers from scratch. Software such as Stan, JAGS and BUGS will construct an MCMC sampler automatically from a description of the model. The results on the slides were obtained with JAGS.
11.4.3 Results
The slides show draws from the joint posterior of , and of , and the marginal posterior of . The posterior of is close to the empirical Bayes posterior found earlier, but slightly wider. The extra width comes from our uncertainty about and , which the hierarchical model includes and the empirical Bayes analysis ignores.
The most instructive plot shows the posterior medians and 95% intervals for all 71 , plotted against the raw rates . A clear pattern appears. Experiments with low raw rates have posterior medians somewhat above those rates, and experiments with high raw rates have posterior medians somewhat below. Every estimate is pulled towards the overall mean.
This phenomenon is called shrinkage, and it is a consequence of the sharing of information described above, often called borrowing strength. The posterior for each depends not only on the data from experiment but, through their influence on , on the data from all the other experiments. An experiment that recorded an unusually high or low rate is judged, in effect, against the background of all the others, and its extreme result is partly attributed to chance. The amount of shrinkage is greatest for the experiments with the least data of their own, since for them the population information carries relatively more weight (Exercise 11.2).
Shrinkage is most striking for the experiments with no observed tumours. Their raw rate is zero, but it would be unreasonable to conclude that the true tumour rate in those experiments is zero when other experiments with the same strain of rat recorded tumours. The hierarchical model gives them small but positive posterior medians.
Finally, the slides compare the 95% intervals from the hierarchical model with those from separate analyses using independent uniform priors on each . The hierarchical intervals are shorter, because each experiment benefits from the information in the others. In the separate analyses the posterior medians lie close to the raw rates, except where the raw rate is zero, where the uniform prior itself pulls the estimate away from zero. The hierarchical model has let the data decide how much the experiments should be pooled: somewhere between the two extremes of treating them as identical and treating them as unrelated.
Exercises
Exercise 11.1
Let and independently, and let and . Find the joint density of .
Show solutionHide solution
The inverse is , . The map has Jacobian determinant so the inverse map has . Hence Compare Exercise 2.2, where the same change of variables appears in reverse.
Exercise 11.2
In the hierarchical binomial model, suppose that and were known. Show that is a weighted average of and . Which experiments are shrunk most?
Show solutionHide solution
If and are known, the are independent given the data, and . So The weight on the common mean is . It is largest when is small. Small experiments are shrunk most. With as in the rat data, an experiment with puts about a third of its weight on the common mean.