Bayesian Optimization
Part I: Foundations
中文

Probability as Bookkeeping for Uncertainty

Section 1.3 set a requirement. To decide where to evaluate an expensive objective next, a Bayesian optimizer needs a model that knows what it does not know: one that can say "the objective is probably high here, and we have no idea over there". This chapter supplies the language in which such statements become numbers that a program can store, combine, and update. That language is probability.

We will treat probability as bookkeeping. There is a fixed budget of belief, one unit in total, spread over everything that might be true. Two rules say how the books must balance: the sum rule, used when we stop tracking a quantity, and the product rule, used when we combine a quantity with something that depends on it. Bayes' rule, the step that turns data into revised belief, follows from these two in one line. No later chapter needs a third rule. The surrogate model, the acquisition function, and the model of a person's preferences are all these rules applied to larger objects.

The chapter starts with what a probability is and what it is about, builds the two rules from a small table of numbers, and then uses them to update a belief one observation at a time, with a coin you can flip. It ends with the summaries (expectation and variance) and the assumption (independence) that later chapters lean on constantly. Readers who have taken a probability course can skim, but should not skip Section 2.5 and Section 2.7, which set up ideas the Gaussian process chapters reuse.

2.1 Uncertainty as a quantity #

Recall the first scenario of Section 1.1: tuning the learning rate of a neural network, where each training run takes hours. Before running anything, you already hold opinions. A learning rate of 10−310^{-3} will probably train; a learning rate of 1010 takes steps so large that training will almost certainly diverge; 10−210^{-2} could go either way. These opinions decide which run you start first. An automatic method must hold opinions too, in a form it can compute with: it has to say "probably" with a number, and it has to change that number in a disciplined way when a run finishes.

2.1.1 Two readings of a probability #

There are two common answers to the question of what a probability measures.

The frequency reading says that the probability of heads is the fraction of heads in a long run of flips. It is concrete and can be checked by experiment, but it needs an experiment that can be repeated.

The belief reading says that a probability measures how strongly one should believe a statement, given the information at hand. It applies to statements that cannot be repeated. "The best learning rate for this network on this data set lies between 10−310^{-3} and 10−210^{-2}" is either true or false; there is no long run of networks to count over. What is uncertain is our knowledge, not the world.

Bayesian optimization needs the belief reading, because its unknown is a fixed function. The objective does not change between evaluations (apart from measurement noise, which Section 2.7 treats separately). When the model says "the value at xx is probably between 0.8 and 0.9", the spread describes our ignorance about one particular function, and each evaluation reduces it. This is why the methods in this book are called Bayesian, after Thomas Bayes, whose essay, published posthumously in 1763, worked out how to revise such a belief about an unknown chance from the number of times an event had happened and failed (Bayes, 1763). That is the coin problem of Section 2.5.2.

A reader may wonder why degrees of belief should obey the same arithmetic as frequencies rather than some other calculus. Cox (1946) argued that any way of attaching numbers to plausibility that meets a few consistency requirements must follow the same sum and product rules. Two examples of such requirements: information that is equivalent must lead to equal plausibility, and the plausibility of "A and B" must be determined by the plausibility of A together with the plausibility of B once A is known. Jaynes (2003) builds the whole of probability theory on this argument. For our purposes the upshot is practical: both readings share one calculus, so we never have to choose between them in order to compute.

2.1.2 Outcomes, events, and the axioms #

To compute with beliefs we need a small amount of structure. An outcome is one complete way the world could turn out, and the sample space Ω\Omega is the set of all outcomes. An event is a set of outcomes, such as "the training run diverges". A probability assigns a number to each event.

Definition 2.1 Probability

A probability P\Prob assigns to every event AA a number P(A)\Prob(A) such that

  1. P(A)≥0\Prob(A) \ge 0 for every event AA;
  2. P(Ω)=1\Prob(\Omega) = 1;
  3. P(A∪B)=P(A)+P(B)\Prob(A \cup B) = \Prob(A) + \Prob(B) whenever AA and BB have no outcome in common.

These three axioms are the bookkeeping rules in their most basic form (Blitzstein and Hwang, 2019). One unit of belief is spread over the outcomes; the probability of an event is the belief sitting on its outcomes; two events that share no outcome cannot share any belief, so their amounts add. Everything else follows. For example, an event AA and its complement "not AA" share no outcome and together cover Ω\Omega, so P(not A)=1−P(A)\Prob(\text{not } A) = 1 - \Prob(A).

2.1.3 Random variables #

We rarely care about outcomes in full detail. We care about numbers computed from them: an accuracy, a count, the value of an objective. A random variable is such a number.

Definition 2.2 Random variable

A random variable XX is a function that assigns a number X(ω)X(\omega) to each outcome ω\omega in the sample space.

The name is misleading on both counts: a random variable is neither random nor a variable. It is a deterministic function whose input we do not know. Take a training run. The outcome ω\omega is everything that could vary: the random seed, the order of the data, nondeterminism in the hardware. The validation accuracy is a function of ω\omega. Once the run finishes, ω\omega is fixed and the accuracy is a number; before it finishes, all we can say is how our belief is spread over the numbers it might be. A programmer can read XX as a pure function applied to a hidden argument.

A word on notation, since later chapters rely on it. A capital letter XX names the random variable and a lowercase xx names a value it might take, so "X=xX = x" is the event that the variable takes the value xx, and P(X=x)\Prob(X = x) is its probability. We write p(x)p(x) for this probability when the variable is clear from context. The symbol ∼\sim reads "is distributed as": X∼Bernoulli(0.3)X \sim \text{Bernoulli}(0.3) says that XX follows the distribution named on the right. A vertical bar reads "given": p(x ∣ y)p(x \given y) is a probability of xx computed as if yy were known, made precise in Section 2.4. From Chapter 3 onward the book follows the custom of machine learning and drops the capitals, writing p(y)p(y) and y∼N(0,1)y \sim \N(0, 1) with one letter for both the variable and its value; the context always tells which is meant.

Sources cited in Section 2.1 4
  1. Bayes (1763) An Essay towards Solving a Problem in the Doctrine of Chances
  2. Cox (1946) Probability, Frequency and Reasonable Expectation
  3. Jaynes (2003) Probability Theory: The Logic of Science
  4. Blitzstein and Hwang (2019) Introduction to Probability

2.2 Discrete distributions #

A random variable is discrete when its possible values can be listed: a coin lands heads or tails, a die shows one of six faces, a count is 0,1,2,…0, 1, 2, \dots. For such a variable the books are a table, one entry per value.

Definition 2.3 Probability mass function

The probability mass function of a discrete random variable XX is p(x)=P(X=x)p(x) = \Prob(X = x). It satisfies p(x)≥0p(x) \ge 0 for every xx and ∑xp(x)=1\sum_x p(x) = 1.

The simplest discrete distribution has two values. A Bernoulli random variable is 1 ("heads", "success") with probability θ\theta and 0 with probability 1−θ1 - \theta. Both cases fit in one formula,

p(x ∣ θ)=θx(1−θ)1−x,x∈{0,1},p(x \given \theta) = \theta^{x} (1 - \theta)^{1 - x}, \qquad x \in \{0, 1\},
(2.1)

which gives θ\theta when x=1x = 1 and 1−θ1 - \theta when x=0x = 0. The bar in p(x ∣ θ)p(x \given \theta) separates the value whose probability we are stating from the quantity it depends on. In the belief reading this is more than a notation for a parameter: an unknown θ\theta is just another uncertain quantity, and p(x ∣ θ)p(x \given \theta) is a conditional probability in the sense of Section 2.4.

The Bernoulli distribution describes every yes-or-no outcome in this book. Does a training run diverge? Does a test fail? Does a person, shown two designs, prefer the first? Part IV models each such comparison as a Bernoulli variable whose θ\theta depends on how much better the first option is than the second (Chapter 16).

Count the heads in nn flips and you get a binomial random variable KK. Any particular sequence of flips with kk heads and n−kn - k tails has probability θk(1−θ)n−k\theta^k (1 - \theta)^{n - k}, because the flips do not influence each other and probabilities of non-interacting events multiply (a fact made precise in Section 2.7). There are (nk)\binom{n}{k} such sequences, one for each way of choosing which kk flips land heads, and no two of them can happen together, so the third axiom adds their probabilities:

p(k ∣ n,θ)=(nk)θk(1−θ)n−k,k=0,1,…,n.p(k \given n, \theta) = \binom{n}{k} \theta^k (1 - \theta)^{n - k}, \qquad k = 0, 1, \dots, n.
(2.2)

For ten flips of a fair coin, the probability of exactly five heads is (105)/210=252/1024≈0.246\binom{10}{5} / 2^{10} = 252 / 1024 \approx 0.246. Even for a fair coin, an even split happens less than one time in four.

A die has six values, each with its own probability p1,…,p6p_1, \dots, p_6 summing to one. This is a categorical distribution, the generalization of the Bernoulli to any finite number of outcomes. It appears when a person picks one favorite from several options at once, the setting of Luce's choice model in Section 16.4.

2.3 Continuous distributions #

Validation accuracy and the value of an objective at an input are real numbers. A table cannot hold them. The values of a count can at least be listed, 0,1,2,…0, 1, 2, \dots, with one probability for each; the real numbers in an interval cannot be listed, and no assignment of positive probability to every one of them sums to one. In fact, for a continuous quantity, every exact value has probability zero. The probability that the accuracy is exactly 0.9137000…0.9137000\dots is zero. What carries probability is an interval: the accuracy lies between 0.91 and 0.92.

2.3.1 Densities #

The fix is to record probability per unit length, the way physics records mass per unit length. A steel rod has a density of so many grams per centimeter; no single point of the rod has any mass, but every segment does, and its mass is the integral of the density over the segment. A probability density works the same way.

Definition 2.4 Probability density

A continuous random variable XX has density p(x)p(x) if, for every interval,

P(a≤X≤b)=∫abp(x) dx.\Prob(a \le X \le b) = \int_a^b p(x)\, \dd x.

A density satisfies p(x)≥0p(x) \ge 0 and ∫−∞∞p(x) dx=1\int_{-\infty}^{\infty} p(x)\, \dd x = 1.

For a short interval of width Δ\Delta around xx, the integral is close to the height times the width, so P(x≤X≤x+Δ)≈p(x) Δ\Prob(x \le X \le x + \Delta) \approx p(x)\, \Delta. The density is the probability of a small interval divided by its width.

Pitfall A density is not a probability

A density can be larger than one. The uniform distribution on the interval [0,0.1][0, 0.1] has density 1010 there, because its one unit of probability is packed into a length of 0.10.1. A density also has units: one over the units of xx. A ratio of densities at two points is meaningful (it compares the probabilities of small intervals around them), and so is the area under a density, but a density value on its own is not the probability of anything. This matters later, when the logarithm of a density evaluated at observed data comes out as a large positive number: nothing has gone wrong.

2.3.2 The cumulative distribution function #

A second way to describe any random variable, discrete or continuous, is its cumulative distribution function (CDF),

F(x)=P(X≤x).F(x) = \Prob(X \le x).

The CDF rises from 0 on the far left to 1 on the far right and never decreases. The probability of an interval is a difference of two CDF values, P(a<X≤b)=F(b)−F(a)\Prob(a < X \le b) = F(b) - F(a), and for a continuous variable the density is the slope of the CDF, p(x)=F′(x)p(x) = F'(x). The CDF of the standard Gaussian, written Φ\Phi and introduced in Section 4.1, appears throughout the book: in the probability of improvement and expected improvement (Section 12.2, Section 12.3) and in the model of a person's comparisons (Section 16.3).

2.3.3 Two examples #

The uniform distribution on [a,b][a, b] has constant density 1/(b−a)1 / (b - a) between aa and bb and zero elsewhere. It encodes "every value in the range is equally plausible", and it is how random search and many initial designs choose inputs (Section 11.4).

The exponential distribution describes the waiting time until an event that occurs at a constant rate λ\lambda, such as the next failure of a long-running job when failures strike at random. Its density and CDF for x≥0x \ge 0 are

p(x)=λe−λx,F(x)=1−e−λx.p(x) = \lambda e^{-\lambda x}, \qquad F(x) = 1 - e^{-\lambda x}.

With one failure per day on average, λ=1\lambda = 1 per day, and the probability that the next failure comes between one and two days from now is F(2)−F(1)=e−1−e−2≈0.233F(2) - F(1) = e^{-1} - e^{-2} \approx 0.233. The same number comes from integrating the density from 1 to 2.

2.4 Joint, marginal, and conditional #

So far each distribution has described one quantity. Bayesian optimization is about several quantities at once: the objective's values at two nearby inputs, a person's answer and the preference behind it, a test result and whether the code is broken. The point of a model is that learning one of these tells us something about another. That requires a distribution over several quantities together.

2.4.1 A table of joint probabilities #

Take an example every software engineer knows. A commit is either broken or fine, and the continuous integration test run on it either fails or passes. Suppose the team's history says that 10% of commits are broken, that the test fails on 90% of broken commits, and that it also fails on 5% of fine commits, because of flaky tests and timeouts. In terms of counts: of 1,000 commits, 100 are broken and 90 of those fail the test; 900 are fine and 45 of those fail anyway.

Dividing the counts by 1,000 gives the belief about the next commit, spread over the four combinations. This is the joint distribution of the two variables, and its table, with the sums of each row and column written in the margins, holds everything there is to know about them.

Table 2.1 Joint probabilities of a commit's state and its test result, with row and column sums.
fail pass total
broken 0.090 0.010 0.100
fine 0.045 0.855 0.900
total 0.135 0.865 1

Three different questions can be read off this table, and each corresponds to one operation.

2.4.2 The sum rule: marginalizing #

What is the probability that the next commit is broken, regardless of the test? Add the broken row: 0.090+0.010=0.1000.090 + 0.010 = 0.100. What is the probability that the test fails, regardless of the commit? Add the fail column: 0.090+0.045=0.1350.090 + 0.045 = 0.135. Each total in the margin is the distribution of one variable on its own, and it is called a marginal distribution for that reason. Summing over a variable we no longer want to track is marginalizing it out. It does not discard that variable's belief; it pools it.

2.4.3 Conditioning #

Now suppose the test has failed. Which commits are still possible? Only those in the fail column: the pass column is ruled out. The belief in the fail column adds up to only 0.1350.135, so to make it a proper distribution again we divide each entry by 0.1350.135:

P(broken ∣ fail)=0.0900.135≈0.667,P(fine ∣ fail)=0.0450.135≈0.333.\Prob(\text{broken} \given \text{fail}) = \frac{0.090}{0.135} \approx 0.667, \qquad \Prob(\text{fine} \given \text{fail}) = \frac{0.045}{0.135} \approx 0.333.

This is conditioning: strike out what the observation rules out, and rescale what remains so it sums to one. A failing test raised the probability that the commit is broken from 10% to about 67%. Every act of learning from data in this book, from a Gaussian process absorbing an evaluation to a preference model absorbing an answer, is this operation on a larger table.

2.4.4 The product rule #

Written as a formula, conditioning divides a joint probability by a marginal: p(y ∣ x)=p(x,y)/p(x)p(y \given x) = p(x, y) / p(x). Multiply both sides by p(x)p(x) and read the result the other way around. It says how to build a joint distribution: first choose xx with probability p(x)p(x), then choose yy with the probability that applies once xx is known. This is how Table 2.1 was made: the entry for broken and fail is P(broken)×P(fail ∣ broken)=0.1×0.9=0.09\Prob(\text{broken}) \times \Prob(\text{fail} \given \text{broken}) = 0.1 \times 0.9 = 0.09. Together with the sum rule, this gives the two rules the chapter's opening promised.

Definition 2.5 The sum rule and the product rule

For random variables XX and YY,

p(x)=∑yp(x,y)(sum rule),p(x) = \sum_y p(x, y) \qquad \text{(sum rule)},
(2.3)
p(x,y)=p(y ∣ x) p(x)=p(x ∣ y) p(y)(product rule).p(x, y) = p(y \given x)\, p(x) = p(x \given y)\, p(y) \qquad \text{(product rule)}.
(2.4)

The conditional distribution p(y ∣ x)=p(x,y)/p(x)p(y \given x) = p(x, y) / p(x) is defined whenever p(x)>0p(x) > 0. For continuous variables, sums become integrals and probabilities become densities.

The product rule extends to any number of variables by applying it repeatedly, peeling off one variable at a time:

p(x1,x2,x3)=p(x1) p(x2 ∣ x1) p(x3 ∣ x1,x2).p(x_1, x_2, x_3) = p(x_1)\, p(x_2 \given x_1)\, p(x_3 \given x_1, x_2).

This chain rule is the shape of every model in the book: a distribution over the unknowns, then a distribution of the data given the unknowns.

Combining the two rules gives a formula used so often that it has a name of its own. Marginalize yy with the sum rule, then expand each joint term with the product rule:

p(y)=∑xp(y ∣ x) p(x).p(y) = \sum_x p(y \given x)\, p(x).
(2.5)

This is the law of total probability. In words: the probability of an observation is its probability under each possibility, averaged with the possibilities' own probabilities as weights. For the test, P(fail)=0.9×0.1+0.05×0.9=0.135\Prob(\text{fail}) = 0.9 \times 0.1 + 0.05 \times 0.9 = 0.135, the column total of Table 2.1. This sentence returns as the denominator of Bayes' rule.

2.4.5 Seeing the rules #

Figure 2.1 draws the same joint distribution as areas. The unit square is cut into two columns whose widths are the probabilities of broken and fine; each column is cut at a height given by the probability that the test fails for that kind of commit. Width times height is area, so each region's area is a joint probability: the product rule, drawn.

broken 10%fine 90%fail 90%pass 10%fail 5%pass 95%width = P(commit) · height = P(test | commit)area = P(commit, test)joint probabilities and their sumsfailpasstotalbroken0.0900.0100.100fine0.0450.8550.900total0.1350.8651Before any test is run:P(broken) = 0.100broken 10%fine 90%
broken 10%fine 90%fail 90%pass 10%fail 5%pass 95%width = P(commit) · height = P(test | commit)area = P(commit, test)joint probabilities and their sumsfailpasstotalbroken0.0900.0100.100fine0.0450.8550.900total0.1350.8651Before any test is run:P(broken) = 0.100broken 10%fine 90%
Figure 2.1 A joint distribution of two yes-or-no quantities drawn as areas. Column widths are the probabilities that a commit is broken or fine; within each column, the solid region is the probability that the test fails given that state, and the faded region that it passes. Each region's area is a joint probability, listed with its row and column sums in the table. Choose what to condition on, or click a region, to keep only the matching regions and rescale them to sum to one. The rates are illustrative.

Some things to try:

  • Condition on fail, then on broken. The first gives P(broken ∣ fail)≈0.667\Prob(\text{broken} \given \text{fail}) \approx 0.667, the second P(fail ∣ broken)=0.9\Prob(\text{fail} \given \text{broken}) = 0.9. They are different numbers answering different questions: the first keeps the fail regions of both columns, the second keeps the broken column. Mistaking one for the other is the error that Section 2.5 guards against.
  • Condition on pass. A passing test lowers the probability of a broken commit from 0.1 to about 0.012. It does not make it zero, because 10% of broken commits pass.
  • Set P(fail ∣ fine)\Prob(\text{fail} \given \text{fine}) to zero. With no false alarms, every failure comes from a broken commit, and conditioning on fail gives certainty.
  • Lower P(broken)\Prob(\text{broken}) to 0.01. The broken column shrinks to a sliver, and so does its share of the fail regions. Section 2.5 explains what this does to the meaning of a failure.

2.4.6 The same rules for densities #

Everything above holds for continuous quantities with integrals in place of sums. A joint density p(x,y)p(x, y) over two real numbers has marginal p(x)=∫p(x,y) dyp(x) = \int p(x, y)\, \dd y and conditional p(y ∣ x)=p(x,y)/p(x)p(y \given x) = p(x, y) / p(x). One subtlety: conditioning on an exact value X=xX = x conditions on an event of probability zero, which the definition of conditional probability for events cannot handle. The density form handles it naturally. Take the joint density along the line X=xX = x, a one-dimensional slice, and rescale the slice so that it integrates to one. Conditioning a Gaussian on observed values is exactly this slicing (Section 4.5), and so is Gaussian process regression (Section 8.1).

2.5 Bayes' rule #

In the test example, our knowledge naturally runs in one direction. We know how the test behaves on broken and on fine commits, P(fail ∣ broken)\Prob(\text{fail} \given \text{broken}), because we can measure it by breaking code on purpose. The question we face runs the other way: the test failed, so how likely is it that the commit is broken? Bayes' rule turns one conditional into the other.

Derivation Bayes' rule
  1. By the product rule (Equation (2.4)) written one way, p(x,y)=p(y ∣ x) p(x)p(x, y) = p(y \given x)\, p(x).
  2. By the same rule written the other way, p(x,y)=p(x ∣ y) p(y)p(x, y) = p(x \given y)\, p(y).
  3. Both right-hand sides equal p(x,y)p(x, y), so p(x ∣ y) p(y)=p(y ∣ x) p(x)p(x \given y)\, p(y) = p(y \given x)\, p(x).
  4. Divide both sides by p(y)p(y), which is allowed whenever p(y)>0p(y) > 0: p(x ∣ y)=p(y ∣ x) p(x)/p(y)p(x \given y) = p(y \given x)\, p(x) / p(y).
  5. Expand the denominator with the law of total probability (Equation (2.5)), renaming the summation variable to x′x' to keep it apart from the xx in the numerator: p(y)=∑x′p(y ∣ x′) p(x′)p(y) = \sum_{x'} p(y \given x')\, p(x').

The result is Bayes' rule. It earns names for its parts when the variable we condition on is data, D\D, and the other is an unknown, θ\theta, such as a coin's bias, whether a commit is broken, or later a whole function:

p(θ ∣ D)⏟posterior=p(D ∣ θ)⏞likelihood  p(θ)⏞priorp(D)⏟evidence,p(D)=∑θp(D ∣ θ) p(θ).\underbrace{p(\theta \given \D)}_{\text{posterior}} = \frac{\overbrace{p(\D \given \theta)}^{\text{likelihood}}\; \overbrace{p(\theta)}^{\text{prior}}} {\underbrace{p(\D)}_{\text{evidence}}}, \qquad p(\D) = \sum_{\theta} p(\D \given \theta)\, p(\theta).
(2.6)
  • The prior p(θ)p(\theta) is the belief about θ\theta before seeing the data.
  • The likelihood p(D ∣ θ)p(\D \given \theta) is how probable the observed data would be if θ\theta were the truth. It is read as a function of θ\theta with the data held fixed, and it is not a distribution over θ\theta: its values need not sum to one.
  • The posterior p(θ ∣ D)p(\theta \given \D) is the revised belief.
  • The evidence p(D)p(\D), also called the marginal likelihood, is the probability the model gave to the data before seeing them. It does not depend on θ\theta; within one update it only rescales.

Because the evidence is the same for every θ\theta, Bayes' rule is often written as a proportionality:

p(θ ∣ D)∝p(D ∣ θ) p(θ).p(\theta \given \D) \propto p(\D \given \theta)\, p(\theta).
(2.7)

The symbol ∝\propto means "equal up to a factor that does not depend on θ\theta". As a procedure: multiply the prior by the likelihood, entry by entry, then rescale so the result sums to one. The rescaling factor is one over the evidence. Section 5.1 develops this vocabulary further, and the evidence returns as the tool for choosing a model's own settings (Section 5.6, Section 9.3).

Key idea Posterior is prior times likelihood, rescaled

To learn from data, multiply what you believed by how well each possibility predicted what you saw, then rescale so the total is one again. The amount of rescaling is the probability you had given to what you saw.

2.5.1 When the prior is small #

The example below applies Bayes' rule in a setting where the result surprises most people the first time.

Example 2.2 A failing test on a rarely broken codebase

Suppose only 1% of commits are broken, while the test keeps its rates: it fails on 90% of broken commits and on 5% of fine ones. A commit fails the test. By Equation (2.6),

P(broken ∣ fail)=0.9×0.010.9×0.01+0.05×0.99=0.0090.0585≈0.154.\Prob(\text{broken} \given \text{fail}) = \frac{0.9 \times 0.01}{0.9 \times 0.01 + 0.05 \times 0.99} = \frac{0.009}{0.0585} \approx 0.154.

A failure that is eighteen times more likely from a broken commit than from a fine one leaves the commit only about 15% likely to be broken. Counting makes the reason plain: of 10,000 commits, 100 are broken and 90 of them fail, while 9,900 are fine and 495 of them fail. Of the 585 failures, only 90 come from broken commits. Fine commits are so much more common that their rare false alarms outnumber the real alarms.

broken 1%fine 99%fail 90%pass 10%fail 5%pass 95%width = P(commit) · height = P(test | commit)area = P(commit, test)joint probabilities and their sumsfailpasstotalbroken0.00900.00100.0100fine0.04950.94050.9900total0.05850.94151Keep only the runs where the test failed:P(broken | fail) = 0.0090 / 0.0585 = 0.154broken 15.4%fine 84.6%
broken 1%fine 99%fail 90%pass 10%fail 5%pass 95%width = P(commit) · height = P(test | commit)area = P(commit, test)joint probabilities and their sumsfailpasstotalbroken0.00900.00100.0100fine0.04950.94050.9900total0.05850.94151Keep only the runs where the test failed:P(broken | fail) = 0.0090 / 0.0585 = 0.154broken 15.4%fine 84.6%
Figure 2.2 The setting of Example 2.2: broken commits are rare (1%), and the figure is conditioned on a failing test. The broken column is a sliver, so its fail region is small next to the fail region of the fine column, even though that one is only 5% of its column. Move the sliders to see how the answer depends on each rate; the rates are illustrative.

People reasoning informally tend to give the prior too little weight in problems like this one, a pattern known as base-rate neglect (Kahneman and Tversky, 1973; Bar-Hillel, 1980). The same problems are solved correctly more often when the numbers are stated as counts out of a population, as in the last paragraph of Example 2.2, rather than as probabilities (Gigerenzer and Hoffrage, 1995). A program applying Equation (2.6) has no such difficulty, which is one reason to write the rule down rather than trust intuition.

The same arithmetic applies to optimization. If good configurations are rare and a single evaluation is noisy, then a configuration that beats the baseline once is not, on that evidence alone, likely to be good: lucky draws from the many mediocre configurations can outnumber the honest results of the few good ones. A model that tracks both its prior and the noise accounts for this automatically.

2.5.2 Updating a belief flip by flip #

The test example had two possibilities and one observation. Optimization gathers many observations about an unknown that can take many values. The smallest problem with that shape is a coin with an unknown bias, the problem Bayes himself considered.

Let θ\theta be the probability that the coin lands heads. To keep the bookkeeping visible, allow eleven possible values, θ∈{0,0.1,0.2,…,1}\theta \in \{0, 0.1, 0.2, \dots, 1\}. The belief about θ\theta is a table of eleven probabilities, and with no reason to favor any value, the prior puts 1/111/11 on each.

Flip the coin once and see heads. The likelihood of heads under hypothesis θ\theta is θ\theta itself, by Equation (2.1). By Equation (2.7) the posterior is proportional to θ×1/11\theta \times 1/11, and rescaling divides by the sum of all eleven products:

p(θ ∣ H)=θ/11∑θ′θ′/11=θ5.5.p(\theta \given \text{H}) = \frac{\theta / 11}{\sum_{\theta'} \theta' / 11} = \frac{\theta}{5.5}.

So the hypothesis θ=0\theta = 0, a coin that never lands heads, now has probability zero: one head rules it out for good. The hypothesis θ=1\theta = 1 has risen from 1/11≈0.0911/11 \approx 0.091 to 1/5.5≈0.1821/5.5 \approx 0.182. The evidence, the sum before rescaling, is ∑θ(θ/11)=0.5\sum_{\theta} (\theta / 11) = 0.5: before the flip, the model gave heads a probability of one half, as it should for a flat prior.

The next flip uses the same rule with today's posterior as tomorrow's prior. If it lands tails, the likelihood is 1−θ1 - \theta, and the new belief is proportional to θ(1−θ)\theta (1 - \theta). After hh heads and tt tails, in any order, the belief is

p(θ ∣ flips)∝θh(1−θ)t p(θ).p(\theta \given \text{flips}) \propto \theta^h (1 - \theta)^t\, p(\theta).
(2.8)
Derivation Updating one flip at a time equals updating all at once

Write the data as two flips x1,x2x_1, x_2, and assume that the flips are independent once θ\theta is known (Section 2.7), so that p(x1,x2 ∣ θ)=p(x1 ∣ θ) p(x2 ∣ θ)p(x_1, x_2 \given \theta) = p(x_1 \given \theta)\, p(x_2 \given \theta).

  1. Bayes' rule for both flips at once, Equation (2.7), gives p(θ ∣ x1,x2)∝p(x1,x2 ∣ θ) p(θ)p(\theta \given x_1, x_2) \propto p(x_1, x_2 \given \theta)\, p(\theta).
  2. By the independence assumption, this is p(x2 ∣ θ) p(x1 ∣ θ) p(θ)p(x_2 \given \theta)\, p(x_1 \given \theta)\, p(\theta).
  3. By Equation (2.7) for the first flip alone, p(x1 ∣ θ) p(θ)∝p(θ ∣ x1)p(x_1 \given \theta)\, p(\theta) \propto p(\theta \given x_1).
  4. So p(θ ∣ x1,x2)∝p(x2 ∣ θ) p(θ ∣ x1)p(\theta \given x_1, x_2) \propto p(x_2 \given \theta)\, p(\theta \given x_1): Bayes' rule for the second flip, with the posterior after the first flip as its prior.
  5. Multiplication does not depend on order, so the result is the same whichever flip is processed first. Repeating the argument for nn flips gives Equation (2.8).

Figure 2.3 lets you run these updates. Each flip is drawn as one application of Equation (2.7): the belief before the flip, times the likelihood of the flip, rescaled.

FlipsHHTH4 flips · 3 H, 1 TBefore the last flip00.150.300.51Likelihood of H: θ00.5100.51After: belief now00.150.300.51×∝÷0.596bias θbias θbias θP(next flip is H) = 0.661P(θ > 0.5) = 0.742product before rescalingThe last flip (H) had been predicted with probability 0.596; dividing by 0.596 rescales the product to sum to one.
HHTH4 flips · 3 H, 1 TBefore the last flip00.150.300.51Likelihood of H: θ00.5100.51After: belief now (product ÷ 0.596)00.150.300.51×∝bias θP(next flip is H) = 0.661P(θ > 0.5) = 0.742product before rescalingLast flip (H) predicted with probability 0.596:the normalizer.
Figure 2.3 Bayes' rule on a grid of eleven hypotheses about a coin's bias. The first panel shows the belief before the most recent flip, the second the likelihood of that flip under each hypothesis, and the third their product (dashed outline), rescaled to sum to one. Call flips yourself, or flip the mystery coin, whose bias is one of 0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, and 0.9, hidden until you reveal it. The readouts give the probability that the next flip lands heads and the probability that the bias exceeds one half. The four priors are illustrative.

Some things to try:

  • Start over and call heads three times. Press New coin to clear the flips. The bar at θ=0\theta = 0 vanishes after the first head and never comes back. A hypothesis that the data rule out stays ruled out, because zero times anything is zero.
  • Watch the normalizer. Before each flip, the readout gives the probability that the next flip lands heads, ∑θθ p(θ ∣ flips)\sum_\theta \theta\, p(\theta \given \text{flips}). Call the flip, and the line beneath reports the same number (or one minus it, for tails) as the amount the product was rescaled by. The evidence is the probability the model had given to what happened. A surprising flip, one with small evidence, moves the belief the most.
  • Change the prior, keep the flips. With Probably fair, a handful of heads barely moves the belief away from 0.5; with Maybe a trick coin, a few flips of each side quickly eliminate both trick hypotheses. With Certain it is fair, nothing ever changes: a prior of zero on every other value cannot be overturned by any amount of data. A prior should give some probability to everything the data might need to reveal.
  • Play against the mystery coin. Press New coin, flip the mystery coin ten times, guess its bias, and reveal it. Keep flipping: the belief concentrates around the true value, but slowly. A bias of 0.6 takes on the order of a hundred flips to tell apart from 0.5 with any confidence; the standard deviation (Section 2.6.2) of the fraction of heads shrinks only like 1/n1/\sqrt{n}, for reasons Section 2.7 makes precise.

The coin is not as far from this book's subject as it looks. Replace the flip by a person asked whether design A is better than design B, and θ\theta by the probability that they say yes. Each answer is a Bernoulli observation, and the update is the same multiply-and-rescale. Part IV does this, with an unknown utility function in place of the single number θ\theta (Chapter 18). And in Section 5.2 the eleven hypotheses become a continuum of values in [0,1][0, 1] and the table becomes a density; the update is the same, with integrals in place of sums.

2.5.3 Computing it #

A grid of hypotheses is the most direct implementation of Bayes' rule, and two practical points apply to it and to everything later.

First, products of many probabilities underflow. After a few hundred observations, a likelihood such as θh(1−θ)t\theta^h (1 - \theta)^t is smaller than the smallest positive floating-point number and rounds to zero. Implementations therefore work with logarithms: the log of a product is a sum of logs, and the rescaling step uses the log-sum-exp function, log⁡∑ieai\log \sum_i e^{a_i}, computed stably by factoring out the largest aia_i.

In code NumPy
import numpy as np
from scipy.special import logsumexp

theta = np.linspace(0, 1, 11)         # the eleven hypotheses
log_prior = np.full(11, -np.log(11))  # flat prior

def update(log_belief, flip):
    with np.errstate(divide="ignore"):  # allow log(0) = -inf
        log_lik = np.log(theta if flip == "H" else 1 - theta)
    log_post = log_belief + log_lik     # prior times likelihood
    return log_post - logsumexp(log_post)  # divide by evidence

b = log_prior
for f in "HHTH":
    b = update(b, f)
print(np.round(np.exp(b), 3))
# [0.    0.002 0.013 0.038 0.078 0.127 0.176 0.209 0.208 0.148 0.   ]

Second, grids do not scale. One unknown on eleven values needs eleven numbers; dd unknowns need 11d11^d. A belief about where the best setting of six hyperparameters lies, with eleven candidate values for each, already needs 116≈1.8×10611^6 \approx 1.8 \times 10^6 entries, and ten hyperparameters need about 26 billion. The objective of a Bayesian optimizer is an unknown function, with a value at every input, so no grid can hold the belief about it. The way out is to choose distributions whose updates have a closed form, so that the whole table is summarized by a few numbers that Bayes' rule changes in a predictable way. The Gaussian distribution of Chapter 4 is the central example, and Chapter 17 turns to approximations when no closed form exists.

Sources cited in Section 2.5 3
  1. Kahneman and Tversky (1973) On the Psychology of Prediction
  2. Bar-Hillel (1980) The Base-Rate Fallacy in Probability Judgments
  3. Gigerenzer and Hoffrage (1995) How to Improve Bayesian Reasoning Without Instruction: Frequency Formats

2.6 Expectation and variance #

A distribution is a whole table or curve. Decisions usually need a few numbers from it: what value should we expect, and how sure are we? Every acquisition function in Part III is a summary of this kind; expected improvement, for instance, is literally an expectation (Section 12.3).

2.6.1 Expectation #

Definition 2.6 Expectation

The expectation, or mean, of a random variable XX is the average of its values weighted by their probabilities:

E[X]=∑xx p(x)(discrete),E[X]=∫x p(x) dx(continuous).\E[X] = \sum_x x\, p(x) \quad \text{(discrete)}, \qquad \E[X] = \int x\, p(x)\, \dd x \quad \text{(continuous)}.

The expectation is the center of mass of the belief: if the probabilities were weights placed along a ruler, the ruler would balance at E[X]\E[X]. A fair die has expectation (1+2+⋯+6)/6=3.5(1 + 2 + \dots + 6)/6 = 3.5, which is not a value the die can show; an expectation need not be a possible outcome. A Bernoulli variable has expectation 1⋅θ+0⋅(1−θ)=θ1 \cdot \theta + 0 \cdot (1 - \theta) = \theta. In Figure 2.3, the probability that the next flip lands heads is the expectation of θ\theta under the current belief.

Often we need the expectation of a quantity computed from XX rather than of XX itself. There is no need to work out the distribution of that quantity first; weight its values directly:

E[g(X)]=∑xg(x) p(x).\E[g(X)] = \sum_x g(x)\, p(x).
(2.9)

In Bayesian optimization, XX is the unknown value of the objective at a candidate input, and gg might be the improvement over the best value so far, max⁡(X−b,0)\max(X - b, 0). Its expectation under the model's belief is the expected improvement.

The most useful property of expectation is that it passes through sums and constant multiples. For any random variables XX and YY and constants aa, bb, cc,

E[aX+bY+c]=a E[X]+b E[Y]+c.\E[aX + bY + c] = a\,\E[X] + b\,\E[Y] + c.
(2.10)

This linearity holds whether or not XX and YY are related, which makes it useful far beyond sums of unrelated quantities. The binomial count of Equation (2.2) is a sum of nn Bernoulli variables, one per flip, so its expectation is nθn\theta without any binomial coefficients.

Pitfall The expectation of a function is not the function of the expectation

Linearity holds for sums and constant multiples only. For other functions, E[g(X)]\E[g(X)] and g(E[X])g(\E[X]) differ in general. Expected improvement shows why the difference matters. Suppose the model's belief about the objective at some input has mean exactly equal to the best value found so far, bb. Then the improvement of the mean is max⁡(E[X]−b,0)=0\max(\E[X] - b, 0) = 0, but the expected improvement E[max⁡(X−b,0)]\E[\max(X - b, 0)] is positive, because the belief gives weight to values above bb and the function ignores values below it. For a Gaussian belief (Chapter 4) with standard deviation ss it is about 0.4 s0.4\,s (Section 12.3). The gap is the value of uncertainty, and it is what makes an optimizer explore.

2.6.2 Variance #

The expectation says where a belief is centered; the variance says how widely it is spread.

Definition 2.7 Variance and standard deviation

The variance of XX, with mean μ=E[X]\mu = \E[X], is the expected squared distance from the mean,

Var⁡[X]=E[(X−μ)2]=E[X2]−μ2.\Var[X] = \E\big[(X - \mu)^2\big] = \E[X^2] - \mu^2.
(2.11)

The standard deviation is Var⁡[X]\sqrt{\Var[X]}, which has the same units as XX.

The second form of Equation (2.11) follows from linearity: expanding the square, E[X2−2μX+μ2]=E[X2]−2μ E[X]+μ2=E[X2]−μ2\E[X^2 - 2\mu X + \mu^2] = \E[X^2] - 2\mu\,\E[X] + \mu^2 = \E[X^2] - \mu^2. A Bernoulli variable has E[X2]=θ\E[X^2] = \theta (since X2=XX^2 = X when XX is 0 or 1), so its variance is θ−θ2=θ(1−θ)\theta - \theta^2 = \theta(1 - \theta), largest for a fair coin and zero for a coin that always lands the same way. Shifting a variable does not change its spread and scaling it scales the spread: Var⁡[aX+c]=a2Var⁡[X]\Var[aX + c] = a^2 \Var[X].

2.6.3 Covariance #

With two random variables we can ask whether they move together. The covariance

Cov⁡[X,Y]=E[(X−E[X])(Y−E[Y])]\Cov[X, Y] = \E\big[(X - \E[X])(Y - \E[Y])\big]

is positive when XX tends to be above its mean whenever YY is above its mean, negative when they move in opposite directions, and zero when there is no such linear tendency. Dividing by both standard deviations gives the correlation, a number between −1-1 and 11 that does not depend on units.

Covariance is what makes the variance of a sum differ from the sum of the variances:

Var⁡[X+Y]=Var⁡[X]+Var⁡[Y]+2 Cov⁡[X,Y].\Var[X + Y] = \Var[X] + \Var[Y] + 2\,\Cov[X, Y].
(2.12)

(Expand the square inside the expectation and apply linearity.) With many variables, the covariances of all pairs form a table, the covariance matrix, which is the central object of the next three chapters. Section 3.3 explains which tables can be covariance matrices, and a Gaussian process kernel is a rule for filling in such a table: k(x,x′)k(x, x') is the covariance between the objective's values at xx and x′x' (Section 7.3). Two nearby inputs have a large covariance, so observing one moves the belief about the other.

2.6.4 Averaging over what you do not know #

The product rule let us build a joint distribution from a marginal and a conditional. Expectation and variance can be built the same way, in two stages. The law of total expectation says that the overall mean is the average of the conditional means:

E[X]=E[E[X ∣ Y]].\E[X] = \E\big[\E[X \given Y]\big].
(2.13)

Here E[X ∣ Y]\E[X \given Y] is the mean of XX under the conditional distribution p(x ∣ y)p(x \given y), a number that depends on yy; the outer expectation averages it over YY. (For discrete variables: ∑yp(y)∑xx p(x ∣ y)=∑xx∑yp(x,y)=∑xx p(x)\sum_y p(y) \sum_x x\, p(x \given y) = \sum_x x \sum_y p(x, y) = \sum_x x\, p(x), by the product rule and then the sum rule.)

The variance version is more interesting, because it splits uncertainty into two kinds. Picture one noisy evaluation of an objective. Part of its spread would remain even if we knew the objective's value exactly: that is the noise. The rest comes from not knowing that value. The law of total variance says that the two parts add.

Derivation The law of total variance

Write m(Y)=E[X ∣ Y]m(Y) = \E[X \given Y] for the conditional mean.

  1. By Equation (2.11), Var⁡[X]=E[X2]−(E[X])2\Var[X] = \E[X^2] - (\E[X])^2.
  2. By Equation (2.13) applied to X2X^2, E[X2]=E[E[X2 ∣ Y]]\E[X^2] = \E\big[\E[X^2 \given Y]\big].
  3. By Equation (2.11) applied to the conditional distribution, E[X2 ∣ Y]=Var⁡[X ∣ Y]+m(Y)2\E[X^2 \given Y] = \Var[X \given Y] + m(Y)^2.
  4. Combining steps 2 and 3, E[X2]=E[Var⁡[X ∣ Y]]+E[m(Y)2]\E[X^2] = \E\big[\Var[X \given Y]\big] + \E\big[m(Y)^2\big].
  5. By Equation (2.13), E[X]=E[m(Y)]\E[X] = \E[m(Y)], so (E[X])2=(E[m(Y)])2(\E[X])^2 = (\E[m(Y)])^2.
  6. Substitute steps 4 and 5 into step 1. The two terms E[m(Y)2]−(E[m(Y)])2\E\big[m(Y)^2\big] - (\E[m(Y)])^2 form the variance of m(Y)m(Y) by Equation (2.11), which leaves the result below.
Var⁡[X]=E[Var⁡[X ∣ Y]]+Var⁡[E[X ∣ Y]].\Var[X] = \E\big[\Var[X \given Y]\big] + \Var\big[\E[X \given Y]\big].
(2.14)

Now apply it to that noisy evaluation. Let YY be the unknown value of the objective at some input, ff, and let XX be the result of the next noisy evaluation there, ff plus independent noise of variance σn2\sigma_n^2. Given ff, the evaluation has mean ff and variance σn2\sigma_n^2. Then Equation (2.14) says

Var⁡[evaluation]=σn2+Var⁡[f].\Var[\text{evaluation}] = \sigma_n^2 + \Var[f].

The first term is noise: no amount of modeling removes it, and repeating the evaluation would give a different number every time. The second term is the model's own uncertainty about ff, which evaluations reduce. The two are often called aleatoric (from chance) and epistemic (from lack of knowledge) uncertainty. Section 8.3 meets them as the difference between the posterior variance of ff and the variance of a new measurement, and acquisition functions target the second kind: there is no point in exploring to reduce noise.

2.6.5 Expectations by sampling #

When the sum or integral in an expectation has no closed form, the standard remedy is to draw samples x(1),…,x(S)x^{(1)}, \dots, x^{(S)} from p(x)p(x) and average: E[g(X)]≈1S∑sg(x(s))\E[g(X)] \approx \frac{1}{S} \sum_{s} g(x^{(s)}). This Monte Carlo estimate is correct on average (unbiased), and its standard deviation shrinks like 1/S1/\sqrt{S}, for the reason given in Section 2.7. Libraries such as BoTorch compute many acquisition functions this way, by averaging over samples from the model's posterior (Balandat et al., 2020).

Sources cited in Section 2.6 1
  1. Balandat et al. (2020) BoTorch: A Framework for Efficient Monte-Carlo Bayesian Optimization

2.7 Independence #

Several steps in this chapter quietly assumed that observations do not influence each other: the binomial formula, the sequential coin update, the averaging of Monte Carlo samples. This section states the assumption, shows where it fails, and explains why noise in Bayesian optimization is usually modeled as independent.

Definition 2.8 Independence

Random variables XX and YY are independent if p(x,y)=p(x) p(y)p(x, y) = p(x)\, p(y) for all xx and yy. Equivalently, whenever p(x)>0p(x) > 0, p(y ∣ x)=p(y)p(y \given x) = p(y): learning XX does not change the belief about YY.

In the mosaic of Figure 2.1, independence means that both columns are cut at the same height: the test fails equally often on broken and fine commits. Set both sliders to 0.5 and condition on fail; the probability of a broken commit does not move from its prior, because the test carries no information.

Independent variables have zero covariance, so by Equation (2.12) the variance of a sum of independent variables is the sum of their variances. The converse is false. If XX is −1-1, 00, or 11 with equal probability and Y=X2Y = X^2, the covariance is zero, yet YY is completely determined by XX. Covariance detects only linear relationships.

2.7.1 Conditional independence #

The coin of Section 2.5.2 holds a subtlety that the rest of the book depends on. Are two flips of a coin with unknown bias independent? Under the flat prior on eleven values, the first flip lands heads with probability 0.5. If it does, the belief about θ\theta shifts toward heads, and the probability that the second flip also lands heads becomes

P(H2 ∣ H1)=∑θθ θ5.5=3.855.5=0.7.\Prob(\text{H}_2 \given \text{H}_1) = \sum_\theta \theta\, \frac{\theta}{5.5} = \frac{3.85}{5.5} = 0.7.

So P(H1,H2)=0.5×0.7=0.35\Prob(\text{H}_1, \text{H}_2) = 0.5 \times 0.7 = 0.35, not 0.5×0.5=0.250.5 \times 0.5 = 0.25. The flips are not independent: each one carries information about the bias, and so about the next. You can watch this in Figure 2.3, where the probability of heads on the next flip changes with every flip.

Yet if the bias were known, say θ=0.3\theta = 0.3, each flip would land heads with probability 0.3 regardless of the others. The flips are independent given θ\theta.

Definition 2.9 Conditional independence

XX and YY are conditionally independent given ZZ if p(x,y ∣ z)=p(x ∣ z) p(y ∣ z)p(x, y \given z) = p(x \given z)\, p(y \given z) for all xx, yy, and zz with p(z)>0p(z) > 0.

This is the structure of every model in the book. Observations are conditionally independent given the unknown, which makes the likelihood a product that is easy to write down. They are dependent once the unknown is marginalized out, because they share it, and that dependence is exactly how one observation informs predictions about another. A Gaussian process works the same way, with a whole function in place of θ\theta.

Observations that are independent given the unknown and that all follow the same distribution are called independent and identically distributed, or i.i.d. Their likelihood is a product of identical factors,

p(D ∣ θ)=∏i=1np(xi ∣ θ),p(\D \given \theta) = \prod_{i=1}^n p(x_i \given \theta),
(2.15)

which is how Equation (2.8) arose.

2.7.2 Why noise is modeled as independent #

The standard observation model of Bayesian optimization, introduced in Section 8.3, writes each evaluation as the objective plus noise, yi=f(xi)+εiy_i = f(x_i) + \varepsilon_i, with the noise terms εi\varepsilon_i independent of each other and of ff. There are three reasons for this choice.

The first is that it is often physically plausible. Each training run draws a fresh random seed; each stride of a person walking in an exoskeleton is a new stride. Nothing ties the noise in one evaluation to the noise in the next. The exoskeleton case also shows how much noise a method may have to absorb. Ding et al. (2018) used Bayesian optimization to tune the peak and offset timing of the hip assistance given by a soft exosuit, scoring each setting by the walker's measured energy expenditure, a signal whose low signal-to-noise ratio they name as a central practical challenge. The settings found, in an average of 21.4 ± 1.0 minutes, reduced metabolic cost by 17.4 ± 3.2% (mean ± standard error) compared with walking without the device. Chapter 24 works through this problem in detail.

The second is convenience. The likelihood becomes a product, as in Equation (2.15), and with Gaussian noise the noise covariance matrix is diagonal, which keeps the computations of Section 8.4 simple.

The third is that independence is what makes averaging work. If ε1,…,εn\varepsilon_1, \dots, \varepsilon_n are independent with variance σ2\sigma^2 each, then by Equation (2.12) (with every covariance zero) their sum has variance nσ2n\sigma^2, and their mean, which divides the sum by nn, has variance nσ2/n2=σ2/nn\sigma^2 / n^2 = \sigma^2 / n. The standard deviation of an average falls like 1/n1/\sqrt{n}: four times as many evaluations halve the noise. This is the rate at which the coin's belief concentrates and the rate at which a Monte Carlo estimate converges.

Pitfall Correlated errors counted as independent

When errors share a cause, treating them as independent makes a model overconfident. Suppose nn evaluations share a common offset cc with variance σc2\sigma_c^2, such as a miscalibrated sensor or a person who is in a generous mood for the whole session, on top of independent noise with variance σ2\sigma^2. Their mean has variance σc2+σ2/n\sigma_c^2 + \sigma^2 / n, not σ2/n\sigma^2 / n: repetition removes the independent part and leaves the shared offset untouched. A model that assumes independence counts nn correlated measurements as nn separate pieces of evidence and becomes more certain than the data justify. Evaluations run in the same batch, and a person's answers within a session that drift or anchor on the previous question, are the usual suspects. The book returns to drifting human judgments in Section 32.3 and Section 29.10.

Sources cited in Section 2.7 1
  1. Ding et al. (2018) Human-in-the-Loop Optimization of Hip Assistance with a Soft Exosuit during Walking

2.8 Exercises #

Exercise 2.1

Use the setting of Example 2.2: 1% of commits are broken, the test fails on 90% of broken commits and on 5% of fine ones. A commit fails, the test is run again, and it fails again. Assuming the two runs are conditionally independent given the commit's state, compute P(broken ∣ two failures)\Prob(\text{broken} \given \text{two failures}) in two ways: all at once, and one failure at a time with the first posterior as the second prior. Then explain why the assumption might fail for a flaky test.

Solution

All at once: the likelihoods are 0.92=0.810.9^2 = 0.81 for a broken commit and 0.052=0.00250.05^2 = 0.0025 for a fine one, so

P(broken ∣ two failures)=0.81×0.010.81×0.01+0.0025×0.99=0.00810.010575≈0.766.\Prob(\text{broken} \given \text{two failures}) = \frac{0.81 \times 0.01}{0.81 \times 0.01 + 0.0025 \times 0.99} = \frac{0.0081}{0.010575} \approx 0.766.

One at a time: the first failure gives 0.1540.154, as in Example 2.2. Using it as the prior for the second failure, 0.9×0.1540.9×0.154+0.05×0.846≈0.766\frac{0.9 \times 0.154}{0.9 \times 0.154 + 0.05 \times 0.846} \approx 0.766, the same answer up to rounding, as the derivation in Section 2.5.2 promises.

The assumption fails if whatever made the test fail on a fine commit tends to persist, for example a test that depends on a slow external service or on a timing quirk of that particular change. Then P(second failure ∣ first failure,fine)\Prob(\text{second failure} \given \text{first failure}, \text{fine}) is much larger than 0.05, the second failure carries far less information, and the true posterior is lower than 0.766.

Exercise 2.2

A coin's bias is one of three values, θ∈{0.25,0.5,0.75}\theta \in \{0.25, 0.5, 0.75\}, each with prior probability 1/31/3. (a) Find the posterior after one head. (b) Find the probability that the second flip lands heads given that the first did, and compare it with the probability that the first flip lands heads. (c) Find the posterior after two heads.

Solution

(a) The posterior is proportional to θ×1/3\theta \times 1/3. The products are 1/12,2/12,3/121/12, 2/12, 3/12, summing to 1/21/2, so the posterior is 1/6,1/3,1/21/6, 1/3, 1/2.

(b) The first flip lands heads with probability 13(0.25+0.5+0.75)=0.5\frac{1}{3}(0.25 + 0.5 + 0.75) = 0.5. After one head, the second lands heads with probability 0.25⋅16+0.5⋅13+0.75⋅12=0.5830.25 \cdot \frac{1}{6} + 0.5 \cdot \frac{1}{3} + 0.75 \cdot \frac{1}{2} = 0.583. The flips are dependent, because they share the unknown bias, even though they are independent given θ\theta.

(c) The posterior is proportional to θ2\theta^2: 0.0625,0.25,0.56250.0625, 0.25, 0.5625, summing to 0.8750.875, so the posterior is about 0.071,0.286,0.6430.071, 0.286, 0.643. Applying the update of (a) a second time gives the same result.

Exercise 2.3

Let XX be uniform on [0,0.25][0, 0.25]. What is its density? What is P(0.1≤X≤0.2)\Prob(0.1 \le X \le 0.2)? Compute E[X]\E[X] and Var⁡[X]\Var[X].

Solution

The density is 1/0.25=41/0.25 = 4 on the interval, a density larger than one. The probability of the subinterval is its length times the density, 0.1×4=0.40.1 \times 4 = 0.4. The mean is the midpoint, E[X]=0.125\E[X] = 0.125, and E[X2]=∫00.254x2 dx=43(0.25)3≈0.02083\E[X^2] = \int_0^{0.25} 4x^2\, \dd x = \frac{4}{3} (0.25)^3 \approx 0.02083, so by Equation (2.11) Var⁡[X]=0.02083−0.1252≈0.00521\Var[X] = 0.02083 - 0.125^2 \approx 0.00521, which is 0.252/120.25^2 / 12. The standard deviation is about 0.0720.072.

Exercise 2.4

A model's belief about the objective at an input has mean 0.70.7 and standard deviation 0.10.1. Each evaluation adds independent noise with standard deviation 0.050.05. What is the standard deviation of the next evaluation's result? If the input is evaluated so many times that the model becomes certain of ff there, what does it become?

Solution

By Equation (2.14), the variance is 0.052+0.12=0.01250.05^2 + 0.1^2 = 0.0125, so the standard deviation is about 0.1120.112. Once the model is certain of ff, the second term vanishes and the standard deviation of a new evaluation is the noise alone, 0.050.05. Repeated evaluations remove the epistemic part of the uncertainty, never the aleatoric part.

Further reading #

  • Blitzstein and Hwang (2019), chapters 1 to 7, covers everything in this chapter in depth, with many worked problems and a gift for explaining conditional probability through stories.
  • MacKay (2003), chapters 2 and 3, introduces probability and inference from the belief viewpoint, with coin and dice examples close to the ones here. The book is free to read online.
  • Bishop (2006), section 1.2, presents the sum rule, the product rule, Bayes' rule, and expectations in the notation that machine learning papers use.
  • Jaynes (2003) develops probability as an extension of logic, starting from the consistency argument of Cox (1946); chapter 2 derives the sum and product rules from it.
  • Gigerenzer and Hoffrage (1995) shows how the format in which numbers are presented changes how well people reason with Bayes' rule.

References

  1. Balandat, M., Karrer, B., Jiang, D. R., Daulton, S., Letham, B., Wilson, A. G., and Bakshy, E. (2020). BoTorch: A Framework for Efficient Monte-Carlo Bayesian Optimization. Advances in Neural Information Processing Systems 33 (NeurIPS 2020). Cited in §2.6
  2. Bar-Hillel, M. (1980). The Base-Rate Fallacy in Probability Judgments. Acta Psychologica. Cited in §2.5
  3. Bayes, T. (1763). An Essay towards Solving a Problem in the Doctrine of Chances. Philosophical Transactions of the Royal Society of London. Cited in §2.1
  4. Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer.
  5. Blitzstein, J. K., and Hwang, J. (2019). Introduction to Probability. Chapman and Hall/CRC. Cited in §2.1
  6. Cox, R. T. (1946). Probability, Frequency and Reasonable Expectation. American Journal of Physics. Cited in §2.1
  7. Ding, Y., Kim, M., Kuindersma, S., and Walsh, C. J. (2018). Human-in-the-Loop Optimization of Hip Assistance with a Soft Exosuit during Walking. Science Robotics. Cited in §2.7
  8. Gigerenzer, G., and Hoffrage, U. (1995). How to Improve Bayesian Reasoning Without Instruction: Frequency Formats. Psychological Review. Cited in §2.5
  9. Jaynes, E. T. (2003). Probability Theory: The Logic of Science. Cambridge University Press. Cited in §2.1
  10. Kahneman, D., and Tversky, A. (1973). On the Psychology of Prediction. Psychological Review. Cited in §2.5
  11. MacKay, D. J. C. (2003). Information Theory, Inference, and Learning Algorithms. Cambridge University Press.