Chapter 4
Discrete random variables
Lectures 9–11 · counting what happens: distributions, expected values, and the named models that describe them
How many passengers will show up for the flight? How many of the 20 bags tested will be fake? How many 911 calls will arrive in the next hour? How many guesses will it take to crack a password? Every one of these questions is about a count, and every one of them has an answer that is uncertain until it happens.
Chapter 3 gave us the language for uncertainty and, at the very end, the idea of a random variable: a rule that turns outcomes into numbers. This chapter puts that idea to work for counts. We will learn how to describe a count's whole distribution, how to boil it down to two numbers (its expected value and its spread), and then meet a small family of named distributions (binomial, geometric, negative binomial, hypergeometric and Poisson) that between them describe a remarkable number of real situations.
The named distributions are where probability starts to pay off. Instead of counting outcomes from scratch every time, you'll learn to recognize a situation ("this is a fixed number of independent yes/no trials, so it's binomial") and then use a formula, or one line of R, to answer any question about it. Recognizing the situation is the hard part, and it's a skill, so this chapter gives you a lot of practice at it.
Each named distribution is a small model of a mechanism, with one or two unknown numbers (its parameters) that control its behaviour: a success probability , or a rate . The models serve both of our goals. For prediction, a model with known parameters tells us what to expect: how many passengers will show up, how likely a lab is to miss every fake. For inference, we turn this around: having seen the data, which model and which parameter values could have produced them? Was Paul the octopus guessing? Were the V-1 bombs aimed? Is a year with 12 great discoveries surprising, if the rate is about 3 a year? This chapter does the forward reasoning carefully, and points out the backward questions as they arise; Chapters 8 and 9 answer them properly.
Here is the route through the chapter.
- Sections 4.1 to 4.3 describe a discrete random variable: its PMF and CDF, its expected value, and its variance.
- Sections 4.4 to 4.7 meet the named distributions, each with its story, its formula, its mean and variance, and its R functions.
- Section 4.8 pulls them together: how to choose the right model for a word problem.
Think About It: Before You Start
A raffle sells 1,000 tickets at $5 each, and there is a single prize of $2,000. Without calculating anything precise: is buying a ticket a good idea "on average"? Would your answer change if you were buying tickets to support a charity you care about? If you were the raffle's organizer? Keep your answers in mind: Section 4.2 makes "on average" precise, and you'll see that the number is only half the story.
On average, each ticket pays out $2,000 / 1,000 = $2, so a $5 ticket loses $3 on average: a bad bet in purely financial terms. But "on average" ignores what you care about. A supporter of the charity is happy to "lose" $3, because the money goes to a cause they value. The organizer collects $5,000 and pays $2,000, a guaranteed $3,000 for the charity: for them there's no uncertainty at all. The expected value is a tool for decisions, not the whole decision, and the same idea (costs and values, not just probabilities) runs back to the airline in Chapter 1.
Lecture 9 — Distributions, expected value and variance
4.1 Describing a discrete random variable
The probability mass function
A random variable is discrete if its possible values can be listed: , perhaps infinitely many, but with gaps between them. Counts are the main example. To describe a discrete random variable completely, we list its possible values and the probability of each one.
Definition: Probability Mass Function (PMF)
The probability mass function of a discrete random variable is the function defined for every real number . It is positive only at the possible values of (the support) and zero everywhere else. Every PMF satisfies
- for every , and
- , the sum running over all possible values.
Both properties come straight from the axioms of Chapter 3: probabilities are never negative, and the events
A PMF can be given in three ways, and you should be comfortable moving between them: a table of values and probabilities, a formula for , and a bar chart with a bar of height at each value .
Example 4.1: Guessing a Pop Quiz, by Hand ★ lecture example
A surprise quiz has three true/false questions, and you haven't done the reading, so you guess each one by flipping a coin in your head. Let be the number you get right. Find the PMF of as a table, as a formula and as a picture, and check that it is a valid PMF.
List the outcomes. Write R for a right answer and W for a wrong one. There are equally likely sequences (counting case 1 from Chapter 3), and counts the R's:
| outcome | RRR | RRW | RWR | WRR |
|---|---|---|---|---|
| 3 | 2 | 2 | 2 | |
| outcome | RWW | WRW | WWR | WWW |
| 1 | 1 | 1 | 0 |
Group the outcomes by the value of . for one outcome, for three, for three, for one. Each outcome has probability , so
| x | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
As a formula. The number of sequences with exactly right answers is the number of ways to choose which of the 3 questions you got right, (counting case 3). So
Valid? Every , and
As a picture, and a check in R (dbinom computes binomial probabilities, as we'll see in Section 4.4):
x <- 0:3
p <- dbinom(x, size = 3, prob = 0.5)
p
sum(p)
ggplot(data.frame(x, p), aes(x, p)) +
geom_col(width = 0.4) +
labs(x = "number of correct guesses, x", y = "p(x)")
[1] 0.125 0.375 0.375 0.125
[1] 1
The bars for a PMF are drawn thin and separated, to show that can only take these exact values. Notice the good news and the bad news: a pure guesser gets at least 2 out of 3 half the time, but all 3 only one time in 8. (A teacher who wants to tell guessers from students who know the material needs more than three questions: see Exercise 13.)
PMFs don't have to come from counting equally likely outcomes. Often they are estimated from data, using the empirical probabilities of Section 3.1.
Example 4.2: A Century of Great Discoveries ★ lecture example
R's discoveries dataset records the number of "great" inventions and scientific discoveries made in each year from 1860 to 1959, as listed in the World Almanac and Book of Facts (1975). Let be the number of great discoveries in a year chosen at random from this century. Estimate the PMF of , draw it, and estimate .
The empirical PMF is the table of relative frequencies (Section 3.1): for each value , the fraction of the 100 years with exactly discoveries.
d <- as.numeric(discoveries) # 100 yearly counts, 1860 to 1959
table(d)
p_hat <- prop.table(table(d)) # relative frequencies
round(p_hat, 2)
d
0 1 2 3 4 5 6 7 8 9 10 12
9 12 26 20 12 7 6 4 1 1 1 1
d
0 1 2 3 4 5 6 7 8 9 10 12
0.09 0.12 0.26 0.20 0.12 0.07 0.06 0.04 0.01 0.01 0.01 0.01
| x | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 12 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| years | 9 | 12 | 26 | 20 | 12 | 7 | 6 | 4 | 1 | 1 | 1 | 1 |
With exactly 100 years, each count divided by 100 is its estimated probability: , the most common value, and so on. The counts add to 100, so the estimates add to 1.
ggplot(data.frame(x = as.numeric(names(p_hat)), p = as.numeric(p_hat)), aes(x, p)) +
geom_col(width = 0.4) +
scale_x_continuous(breaks = 0:12) +
labs(x = "great discoveries in a year, x", y = "estimated p(x)")
The probability. is the disjoint union of mean(d >= 4).
A critical reading. What counts as "great" is someone's judgement, made decades later, and recent discoveries may not yet have been recognized: the measurement process (Section 1.4) shapes the data. Notice also : no year had exactly 11, though 12 happened once. An empirical PMF with zeros in the middle reminds us that it's an estimate of the true distribution, not the distribution itself.
The cumulative distribution function
Many questions ask about a range of values: "at most 2 visits", "more than 100 passengers", "between 3 and 6 calls". For these, it is convenient to have running totals of the PMF.
Definition: Cumulative Distribution Function (CDF)
The cumulative distribution function of a random variable is
Theorem: Properties of a CDF
For any random variable with CDF :
- , and never decreases: if then .
- as and as .
- For ,
. .
For a discrete random variable, is a step function: flat between possible values, and jumping up by at each possible value .
- is a probability, so it lies in . If , then
, so by the subset rule of Section 3.3. - Intuitively, shrinks to the empty set as and grows to the whole sample space as . (Making this rigorous needs a continuity property of probability that follows from axiom 3; we take it as given.)
- is the disjoint union of and , so
. Rearrange. - Complement rule: is the complement of . ∎
Watch Out: Strict or Not Strict?
For a discrete random variable, and are different: includes , and
Example 4.3: Reading Probabilities from a CDF ★ lecture example
For the number of correct guesses on the three-question quiz (Example 4.1), find the CDF, draw it, and use it to find , , and . If a passing grade needs at least 2 correct, what is the chance a guesser passes?
Running totals. Add the PMF from left to right:
| x | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
Between the possible values, stays flat. So in full, Notice that , for example: "at most 1.5 right" means "at most 1 right".
ggplot(data.frame(x = c(-1, 0:3, 4)), aes(x)) +
stat_function(fun = function(x) pbinom(x, 3, 0.5), geom = "step", n = 1001) +
geom_point(data = data.frame(x = 0:3, F = pbinom(0:3, 3, 0.5)), aes(x, F)) +
labs(x = "x", y = "F(x) = Pr(X ≤ x)")
The probabilities.
. . . So a pure guesser passes half the time. . (Check: that's .)
In R, pbinom(1, 3, 0.5) gives . Every named distribution has a "p" function for its CDF.
The widget below lets you shape a PMF yourself and watch its CDF respond. The triangle under the PMF is the expected value, the subject of the next section.
Check Yourself
Add them up. What must a PMF's values add to?
These add to 1, but can a probability be negative?
Only option 3 has non-negative values that add to exactly 1.
A random variable has CDF values , , , , and takes only the values 1, 2, 3, 4. Find .
"At least 3" is the complement of "at most 2". Which CDF value is that?
Using the same CDF, find .
The PMF at a value is the size of the jump in the CDF there.
Think About It: A Model or the Data?
In Example 4.1 the PMF came from a model (each guess is right with probability ½). In Example 4.2 it came from data (100 years of discoveries). Give one advantage of each approach. If you wanted to predict the number of great discoveries in 2030, which would you trust, and why might neither be very good?
A model gives exact probabilities for every value, including ones never seen in the data (such as 11 discoveries), and it explains why the probabilities are what they are. Data need no assumptions: they show what actually happened, warts and all. For 2030, neither is ideal: the data describe 1860–1959, and the rate of discovery (and what counts as "great") has surely changed since; a model fitted to old data inherits the same problem. Good prediction needs both a sensible model and data from a process that still works the same way.
Key Takeaways
- A discrete random variable is described by its PMF
: non-negative values adding to 1. Show it as a table, a formula or a bar chart. - The CDF
is a running total; for discrete it's a step function jumping by at each value. and . Watch the difference between and . - A PMF can be computed from a model, or estimated from data as relative frequencies.
4.2 Expected value: the long-run average
One number for the centre
In Chapter 2, the mean of a dataset summarized its centre. A random variable has a centre too, and it is defined in exactly the same spirit.
Suppose a die is rolled 600 times. We'd expect about 100 of each face, so the average of the 600 rolls should be about
Definition: Expected Value
The expected value (or mean, or expectation) of a discrete random variable with PMF is the sum of each possible value times its probability. (If takes infinitely many values, we require the sum to be finite; otherwise doesn't exist.) It is often written or .
There are two ways to picture the expected value, and both are worth keeping.
- The long-run average. If you observe over and over, independently, the average of your observations settles down to . (This is the Law of Large Numbers again, proved in Chapter 7.)
- The balance point. Put a weight of at each value on a see-saw. is where it balances, just as the sample mean was the balance point of the data in Chapter 2.
Notice that need not be a possible value of : a die never shows 3.5. "Expected" is a historical name, not a prediction of any single outcome.
Example 4.4: How Many Discoveries in a Typical Year? ★ lecture example
Using the empirical PMF of great discoveries per year from Example 4.2, find by hand and in R. Compare it with the average of the 100 yearly counts. What does the number mean?
By hand. Multiply each value by its estimated probability and add:
In R, the same calculation is sum(x * p). Compare it with the ordinary average of the data:
x <- as.numeric(names(p_hat))
sum(x * p_hat) # expected value of the empirical PMF
mean(d) # the average of the 100 yearly counts
[1] 3.1
[1] 3.1
Both give 3.1. That's no coincidence: averaging 100 numbers is the same as weighting each distinct value by the fraction of the time it occurs, which is exactly what does. The expected value of an empirical distribution is the sample mean of Chapter 2. For a model distribution, is the mean we'd see in the long run.
Meaning. Averaged over the century, about 3.1 great discoveries were made per year: 310 in 100 years. No year had 3.1 discoveries, but a historian estimating how many great discoveries to expect in a decade would say about 31. Try the "great discoveries" option in the widget above: the running average of simulated years settles at 3.1.
Prediction and inference. As a prediction, 3.1 is our best guess (under squared loss) for the number of great discoveries in a year like these. As an inference, it estimates the underlying rate of discovery in that century. Notice that the two uses need different caveats: the prediction assumes future years behave like 1860–1959; the inference assumes the years are a fair record of what happened.
Example 4.5: Is a Powerball Ticket Worth $2? ★ lecture example
A Powerball ticket costs $2. Its prizes and odds, from the official prize chart, are:
| match | prize | odds (1 in ...) |
|---|---|---|
| Powerball only | $4 | 38.32 |
| 1 + Powerball | $4 | 91.98 |
| 2 + Powerball | $7 | 701.33 |
| 3 numbers | $7 | 579.76 |
| 3 + Powerball | $100 | 14,494.11 |
| 4 numbers | $100 | 36,525.17 |
| 4 + Powerball | $50,000 | 913,129.18 |
| 5 numbers | $1,000,000 | 11,688,053.52 |
| 5 + Powerball | jackpot | 292,201,338 |
(a) Ignoring the jackpot, what is the expected prize per ticket? (b) How big must the jackpot be for a ticket to be worth $2 "on average"? (c) Why is even that answer too optimistic?
Set up. Let be the prize on one ticket. Each tier's probability is 1 divided by its odds, and the tiers are disjoint (a ticket wins at most one), so by the definition of expected value
(a) The non-jackpot tiers contribute, for example,
prize <- c(4, 4, 7, 7, 100, 100, 50000, 1e6)
odds <- c(38.32, 91.98, 701.33, 579.76, 14494.11, 36525.17, 913129.18, 11688053.52)
round(prize / odds, 4) # each tier's contribution, in dollars
sum(prize / odds) # expected non-jackpot prize per ticket
(2 - sum(prize / odds)) * 292201338 # break-even jackpot
[1] 0.1044 0.0435 0.0100 0.0121 0.0069 0.0027 0.0548 0.0856
[1] 0.3198782
[1] 490933824
So the non-jackpot prizes are worth about 32 cents per $2 ticket. Interestingly, the $50,000 and $1 million tiers contribute 14 cents of that between them: the rare big prizes matter about as much as the frequent small ones.
(b) The jackpot adds . For we need
(c) Three reasons a $491 million advertised jackpot still isn't a fair bet. The advertised jackpot is paid over 29 years; the lump-sum cash value is roughly half. Large prizes are taxed heavily. And when the jackpot is huge, ticket sales soar, so the chance of having to share the jackpot with other winners rises. Each of these cuts the expected value well below $2. On expected value alone, a Powerball ticket is a poor investment; people buy them for the dream, which is a perfectly reasonable thing to pay $2 for, as long as you know that's what you're buying.
Source: Powerball prize chart, powerball.com.
Where the expected value comes from. A bar chart of each tier's contribution (prize × probability) shows that the rare large prizes contribute as much as the common small ones:
tiers <- c("PB only", "1+PB", "2+PB", "3", "3+PB", "4", "4+PB", "5")
d <- data.frame(tier = factor(tiers, levels = tiers), cents = 100 * prize / odds)
ggplot(d, aes(tier, cents)) + geom_col(width = 0.6) +
labs(x = "prize tier (numbers matched)", y = "cents per ticket")
Expected values of functions
Often we need the expected value not of itself, but of something computed from it: the cost of a decision, or (which we'll need for the variance). There's no need to find the distribution of the new quantity first.
Theorem: Expected Value of a Function of X
For any function , provided the sum of is finite.
takes the value exactly when takes one of the values with . So
In words: to find the average of , apply to each possible value and weight by the same probabilities. (Some books call this the "law of the unconscious statistician", because it's what people do without thinking.)
Example 4.6: The Overbooking Bill, Exactly ★ lecture example
In Chapter 1, an airline sold 110 tickets for a 100-seat plane; each ticket holder shows up with probability 0.9, independently. An empty seat costs $250 and a bumped passenger $1000. The simulation in Example 1.1 estimated the average cost per flight at about $1240. Compute it exactly.
Set up. Let be the number who show up; its PMF is binomial (Section 4.4), and R's dbinom(x, 110, 0.9) gives . The cost is a function of :
Apply the theorem.
x <- 0:110
p <- dbinom(x, size = 110, prob = 0.9)
cost <- ifelse(x < 100, 250 * (100 - x), 1000 * (x - 100))
sum(cost * p) # expected cost per flight
# repeat for every number of tickets from 95 to 120
exp_cost <- sapply(95:120, function(n) {
x <- 0:n
sum(ifelse(x < 100, 250 * (100 - x), 1000 * (x - 100)) * dbinom(x, n, 0.9))
})
(95:120)[which.min(exp_cost)] # the best number of tickets
[1] 1240.143
[1] 108
The exact expected cost is $1240.14, matching the simulation's estimate. Doing the same for every number of tickets shows that 108 tickets minimizes the expected cost (about $1041 per flight), as the widget in Chapter 1 showed.
ggplot(data.frame(n = 95:120, exp_cost), aes(n, exp_cost)) +
geom_line() + geom_point(size = 1) +
geom_point(data = data.frame(n = 108, exp_cost = min(exp_cost)), size = 3.5, colour = "orange") +
labs(x = "tickets sold", y = "expected cost ($)")
Chapter 1's question ("how many tickets?") is now a precise calculation: choose the decision that minimizes the expected value of the loss.
Theorem: Linearity of Expectation
For any random variables and and constants and :
; , whether or not and are independent.
Part 1. Use the theorem above with , then split the sum and use :
Linearity is the most useful property in the whole chapter, and part 2 is surprisingly powerful because it needs no independence. The expected total of many random quantities is the total of their expected values, whatever the connections between them.
Example 4.7: A Secret Santa Disaster
Twenty friends organize a Secret Santa: each writes their name on a slip, the slips are shuffled in a hat, and each person draws one, to buy a present for whoever is named. Anyone who draws their own name spoils the game. How many people do you expect to draw their own name?
Finding the full distribution of the number of "self-draws" is hard. The expected value is easy with indicators (Section 3.8). Let if friend draws their own name and 0 otherwise. The total number of self-draws is
Each friend is equally likely to draw any of the 20 slips, so
set.seed(20)
self_draws <- replicate(10000, sum(sample(20) == 1:20))
mean(self_draws) # close to 1
mean(self_draws == 0) # fraction of games with nobody drawing themselves
[1] 0.9844
[1] 0.3721
About 37% of shuffles work first time, so expect to reshuffle more often than not. (The exact answer is very close to , for any reasonably large group: a famous result called the matching problem.)
The whole distribution. A bar chart of the 10,000 simulated games shows how many people typically draw their own name. The orange dots are the probabilities from a Poisson distribution with mean 1 (Section 4.7), which turns out to be an excellent approximation:
d <- as.data.frame(table(factor(self_draws, levels = 0:6)) / 10000)
names(d) <- c("k", "prop")
d$k <- as.numeric(as.character(d$k))
ggplot(d, aes(k, prop)) + geom_col(width = 0.5) +
geom_point(aes(y = dpois(k, 1)), colour = "orange", size = 3) +
labs(x = "number of people who draw their own name", y = "proportion of games")
Check Yourself
takes the values 0, 1, 2, 3 with probabilities 0.1, 0.2, 0.2, 0.5. Find .
Multiply each value by its probability and add the four products.
In the raffle at the start of the chapter (1,000 tickets at $5, one $2,000 prize), what is the expected net gain from one ticket, in dollars?
Your net gain is with probability , and otherwise.
If , what is ?
Linearity:
.
Think About It: When the Average Is the Wrong Target
A hospital uses the expected number of emergency admissions per night, 12, to decide how many beds to keep free. Why is planning for exactly the expected value a bad idea? What would a better rule look like?
On about half of nights (roughly, since the distribution is not symmetric), admissions exceed the average, and patients would have nowhere to go. The cost of a shortage (a patient turned away) is far bigger than the cost of an empty bed, so the loss is lopsided, and the best plan is a high quantile of the distribution (Chapter 2's loss-function interlude), for example enough beds to cover 95% or 99% of nights. The expected value is the right target only when over- and under-shooting cost the same. To choose the quantile you need the whole distribution, not just its mean: that is what the named models in this chapter provide.
Key Takeaways
: the long-run average, and the balance point of the PMF. It need not be a possible value. : no need to find the distribution of first. - Linearity:
and , even without independence. - The best decision under uncertainty often minimizes an expected loss, but expected value isn't the whole story when a bad outcome would be unbearable.
4.3 Variance: how far from the average?
Two jobs both pay $50,000 a year on average. One pays exactly $50,000; the other pays $20,000 or $80,000 with equal chance. Most people would not call them equivalent. As in Chapter 2, a centre needs a spread to go with it.
Definition: Variance and Standard Deviation of a Random Variable
The variance of a random variable with mean is the expected squared distance from the mean:
Compare with the sample variance of Chapter 2: there we averaged the squared deviations of the data (dividing by ); here we average the squared deviations of the possible values, weighted by their probabilities. The standard deviation is in the same units as and measures a typical distance from the mean.
Squaring and summing is tedious by hand. This shortcut is usually quicker.
Theorem: Shortcut Formula for the Variance
In words: the mean of the square, minus the square of the mean.
Expand the square and use linearity, remembering that is a constant:
Since a variance can't be negative, the theorem also shows that
Example 4.8: Deal or No Deal? ★ lecture example
On a game show you are offered three choices.
- A: take $50,000 now.
- B: flip a coin: $100,000 for heads, nothing for tails.
- C: draw a card from four: one card pays $200,000, the other three nothing.
Find the expected value and the standard deviation of the prize for each choice, by hand. Which would you choose, and why?
Expected values.
Variances, by the shortcut formula
- A always pays 50, so
and : no risk at all. - B:
, so and . - C:
, so and .
So the standard deviations are $0, $50,000 and about $86,600: the same average, increasingly risky.
sd_of <- function(x, p) { mu <- sum(x * p); sqrt(sum(x^2 * p) - mu^2) }
c(A = sd_of(50000, 1),
B = sd_of(c(0, 100000), c(1/2, 1/2)),
C = sd_of(c(0, 200000), c(3/4, 1/4)))
A B C
0.00 50000.00 86602.54
Which to choose? Expected value can't decide this: they're tied. Most people take A, because $50,000 for certain changes their life and a 75% chance of nothing (choice C) is painful. A billionaire, for whom $50,000 is small change, might reasonably take C for the fun of it. The standard deviation measures the risk; how much risk you should take depends on your circumstances, which is the loss function idea of Chapter 2 again. The real game show Deal or No Deal offered contestants exactly this kind of choice, and economists studied the contestants' decisions to learn how people value risk.
The three choices side by side. Same balance point, very different spread:
choices <- data.frame(
choice = rep(c("A", "B", "C"), c(1, 2, 2)),
prize = c(50, 0, 100, 0, 200), prob = c(1, 0.5, 0.5, 0.75, 0.25))
ggplot(choices, aes(prize, prob)) + geom_col(width = 12) +
geom_vline(xintercept = 50, linetype = "dashed") +
facet_wrap(~ choice) + scale_x_continuous(breaks = c(0, 100, 200)) +
theme(panel.spacing = unit(1.2, "lines")) +
labs(x = "prize (thousands of dollars)", y = "probability")
Theorem: Variance of a Linear Function
For constants and ,
By linearity,
This matches the "changing units" theorem for data in Chapter 2: adding a constant shifts the centre but not the spread. For instance, if every game-show prize in Example 4.8 were taxed at a flat 30%, the take-home prize would have standard deviation ; if instead a $1,000 appearance fee were added to every prize, the standard deviation wouldn't change at all.
Watch Out: Variances Don't Always Add
Expected values always add:
Think About It: What Does a Standard Deviation of Risk Mean?
Two investments each return $100 on average. Investment A has a standard deviation of $5; investment B, $60. Which would you choose for money you need next month for rent? For money you won't touch for 30 years? Why might the answer differ?
For rent money, A: you need to be nearly sure of having it, and B could easily return much less than $100. For long-term money, many people accept B's ups and downs if, as is common in practice, riskier investments also have higher average returns; over 30 years, the good and bad years partly average out. Spread measures risk, and whether risk matters depends on what the money is for: again, the decision depends on the loss function, not just the distribution.
Check Yourself
takes the values 0, 1, 2, 3 with probabilities 0.1, 0.2, 0.2, 0.5, so . Find .
First find
If , what is ?
The constant 4 doesn't change the spread. What happens to the variance when you multiply by ?
Key Takeaways
; , in the units of . : shifting doesn't change spread. - Variances add for independent random variables only.
Lecture 10 — Binomial, geometric and hypergeometric models
4.4 Bernoulli and binomial: counting successes
One trial
The simplest random variable of all records whether something happened: a test is positive or not, a passenger shows up or not, a coin lands heads or not. Statisticians call the two outcomes "success" (coded 1) and "failure" (coded 0), whatever they actually are; a "success" can be a disease, a crime or a defect.
Definition: Bernoulli Distribution
A random variable has the Bernoulli distribution with success probability , written , if
Theorem: Mean and Variance of a Bernoulli Random Variable
If , then and
The variance is largest when (the hardest outcome to predict) and zero when or (no uncertainty at all).
Many trials: the binomial distribution
Now repeat a Bernoulli trial times and count the successes. If a drug test gives a false positive for 5% of clean athletes, how many false positives should we expect among 20 clean athletes? What's the chance of none at all? Example 4.1 (guessing a true/false quiz) already did this for and . Here is the general story.
Theorem: The Binomial Distribution
Suppose we perform trials such that
- each trial has two outcomes, success or failure;
- the trials are independent;
- each trial has the same success probability .
Let be the number of successes. Then has the binomial distribution, , with PMF
One particular sequence. Consider any one sequence of outcomes with exactly successes, such as The trials are independent, so its probability is the product of the probabilities of its outcomes: factors of and factors of , giving whatever the order.
How many such sequences? A sequence with successes is determined by choosing which of the trials are the successes: ways (counting case 3).
Add them up. The sequences are disjoint outcomes, each with the same probability, so
Each piece of the formula has a job: is the probability of one arrangement, and counts the arrangements. A Galton board makes this visible: each ball makes left-or-right "trials", and the number of rights it takes decides where it lands.
Theorem: Mean and Variance of a Binomial Random Variable
If , then
Write
- By linearity,
. - The trials are independent, so the variances add (Chapter 6 proves this):
. ∎
The mean is common sense: 20 athletes, each with a 5% chance, gives 1 false positive on average. Proving it from the PMF directly would take a page of algebra; the indicator trick takes one line.
Idea: Algorithm: Is It Binomial?
Before using the binomial formula, check the four conditions. A memory aid is BINS:
- Binary: each trial has two outcomes (success or failure)?
- Independent: does one trial's outcome leave the others' probabilities unchanged?
- N: is the number of trials fixed in advance?
- Same : does every trial have the same success probability?
Then name , and what counts as a "success", and write before calculating anything.
In R, every named distribution has four functions, named by a letter plus the distribution's short name:
| function | gives | binomial example |
|---|---|---|
d... |
the PMF, | dbinom(x, n, p) |
p... |
the CDF, | pbinom(x, n, p) |
q... |
a quantile: the smallest with a given probability | qbinom(0.95, n, p) |
r... |
random draws (simulation) | rbinom(10, n, p) |
Example 4.9: Paul the Octopus ★ lecture example
During the 2010 football World Cup, an octopus called Paul, living in an aquarium in Oberhausen, Germany, was offered two boxes of food before each of Germany's matches, each box marked with a team's flag. The box he opened first was taken as his prediction. Paul correctly "predicted" all 7 of Germany's matches and then the final (Spain beat the Netherlands): 8 out of 8. Including the European Championship two years earlier, his record was 12 correct out of 14.
(a) If Paul was simply choosing at random, what is the probability of 8 out of 8? (b) Of 12 or more out of 14? (c) Hundreds of animals around the world (other octopuses, parakeets, elephants, guinea pigs) were "predicting" World Cup matches. If 200 animals each guessed 8 matches at random, how many would you expect to get all 8 right?
Is it binomial? Each prediction is right or wrong (binary); a random chooser's guesses are independent; the number of matches is fixed; and each guess is right with probability (same ). So the number right is binomial.
(a)
(b)
dbinom(8, 8, 0.5) # (a)
1 - pbinom(11, 14, 0.5) # (b) Pr(Y >= 12)
200 * dbinom(8, 8, 0.5) # (c) expected number of perfect animals
[1] 0.00390625
[1] 0.006469727
[1] 0.78125
(c) Each animal is perfect with probability , so by linearity (with indicators, as in Example 4.7) the expected number of perfect animals is
The lesson is the birthday problem again (Example 3.9): a one-in-256 event is rare for one animal and unremarkable among hundreds. We only heard about Paul because he got them right; nobody reported on the parakeet that got 4 out of 8. Selecting the winners after the fact is how many "amazing" track records, from stock-pickers to psychics, are made. Chapter 9 calls this the problem of multiple testing.
How surprising is 8 out of 8? The PMF of shows how far Paul's result sits from what guessing usually produces:
d <- data.frame(x = 0:8, p = dbinom(0:8, 8, 0.5), paul = 0:8 == 8)
ggplot(d, aes(x, p, fill = paul)) + geom_col(width = 0.5) +
scale_fill_manual(values = c("grey60", "orange"), guide = "none") +
scale_x_continuous(breaks = 0:8) +
labs(x = "correct predictions out of 8, if guessing", y = "probability")
This is inference. We asked: how probable is the observed result if the mechanism is pure guessing? Very improbable for one animal, but not for the luckiest of hundreds. Chapter 9 formalizes this as a hypothesis test and its p-value.
Example 4.10: False Positives in a Clean Team ★ lecture example
A drug test gives a false positive for 5% of athletes who don't use the drug, independently from athlete to athlete. A team of 20 clean athletes is tested. Find (a) the probability of no positives, (b) exactly one positive, (c) at least one positive, and (d) the mean and standard deviation of the number of positives. Do (a) to (c) by hand, then in R.
Is it binomial? Binary (positive or not); independent (stated); fixed; same for every clean athlete. So = number of false positives , with "success" meaning a positive test. (A "success" is just the outcome we count, here an unwelcome one.)
(a)
(b)
(c) "At least one" is easiest through the complement:
(d)
dbinom(0, size = 20, prob = 0.05) # (a)
dbinom(1, size = 20, prob = 0.05) # (b)
1 - pbinom(0, size = 20, prob = 0.05) # (c): 1 - Pr(X <= 0)
round(dbinom(0:5, 20, 0.05), 4) # the first few PMF values
[1] 0.3584859
[1] 0.3773536
[1] 0.6415141
[1] 0.3585 0.3774 0.1887 0.0596 0.0133 0.0022
ggplot(data.frame(x = 0:6, p = dbinom(0:6, 20, 0.05)), aes(x, p)) +
geom_col(width = 0.4) +
labs(x = "false positives among 20 clean athletes", y = "probability")
What it means. Even with no drug users at all, there's nearly a two-in-three chance that someone tests positive. A single positive on a large team is not, by itself, evidence of drug use; that's why positive screens are confirmed with a second, more specific test (and why Section 3.6's Bayes calculation matters).
Example 4.11: The Chance Someone Is Bumped
Return to the airline: 110 tickets, each ticket holder showing up with probability 0.9 independently. What is the probability that more than 100 show up? How many tickets could the airline sell and keep that probability below 5%?
1 - pbinom(100, size = 110, prob = 0.9)
# the same for every number of tickets from 100 to 115
n <- 100:115
data.frame(tickets = n, p_bump = round(1 - pbinom(100, n, 0.9), 3))
[1] 0.3289856
tickets p_bump
1 100 0.000
2 101 0.000
3 102 0.000
4 103 0.001
5 104 0.006
6 105 0.017
7 106 0.040
8 107 0.081
9 108 0.143
10 109 0.227
11 110 0.329
12 111 0.441
13 112 0.554
14 113 0.660
15 114 0.752
16 115 0.826
The probability is 0.329, matching the simulation in Example 1.1. Scanning the table, stays below 5% for up to 106 tickets (0.040) and jumps above it at 107 (0.081). So a rule "keep the chance of bumping under 5%" gives 106 tickets, while the expected-cost rule of Example 4.6 gave 108. Different goals, different answers: the second rule cares how many are bumped and what empty seats cost, the first only whether anyone is.
n <- 100:115
ggplot(data.frame(n, p = 1 - pbinom(100, n, 0.9)), aes(n, p)) +
geom_line() + geom_point() +
geom_hline(yintercept = 0.05, linetype = "dashed") +
labs(x = "tickets sold", y = "Pr(someone is bumped)")
The curve rises steeply: each extra ticket beyond about 105 adds several percentage points to the chance of bumping someone.
Think About It: When the Binomial Breaks
An airline's model assumes passengers show up independently. But families and business groups travel together, and a snowstorm or a delayed connecting flight keeps many passengers away at once. How would each of these violate the BINS conditions? Would the true distribution of show-ups be more spread out or less spread out than the binomial, and why does that matter for overbooking?
Groups break independence: if one member of a family of five shows up, the others almost certainly do too, so passengers come and go in clumps. A snowstorm also breaks same : on a bad day everyone's chance of showing up drops together. Both make large deviations from the average more common than the binomial predicts: a more spread-out distribution. An airline that used the binomial would underestimate how often a flight is badly overbooked (or half empty). This is a general lesson: independence is the assumption that most often fails, and when it fails, real-world variability is usually bigger than the model says.
Check Yourself
Run through BINS. In particular: if the first fragment has a high refractive index, what does that tell you about the second, from the same pane?
Fragments of one pane share its chemistry, so their measurements are strongly related (Chapter 1's clustered data). The binomial needs independent trials; here learning one fragment's value tells you a lot about the others.
A juror is struck from the jury pool (for example, because of a conflict) with probability 0.25, independently. Of 12 jurors called, what is the probability that exactly 3 are struck?
dbinom(3, 12, 0.25).
, so
In the previous question, what is the standard deviation of the number struck?
with , .
Key Takeaways
- Bernoulli: one yes/no trial; mean , variance .
- Binomial : the number of successes in independent trials with the same .
. - Mean , variance : found by writing as a sum of indicators.
- Check BINS first. Independence is the condition that fails most often in practice.
- R:
dbinom,pbinom,qbinom,rbinom.
4.5 Geometric and negative binomial: waiting for success
The binomial fixes the number of trials and counts the successes. Turn that around: keep going until you get a success, and count how long it takes. A lab tests bags one at a time until it finds a fake. A hacker tries passwords until one works. A detective interviews witnesses until one saw something.
Definition: Geometric Distribution
In a sequence of independent trials, each a success with probability , let be the number of failures before the first success. Then has the geometric distribution, , with PMF
The formula is the multiplication rule for independent events: failures in a row, each with probability , then one success with probability . These add to 1 by the geometric series of Section 0.4:
Watch Out: Counting Failures or Counting Trials?
Books disagree on whether a geometric random variable counts the failures before the first success (values 0, 1, 2, ...) or the trials up to and including it (values 1, 2, 3, ...). They differ by exactly 1. These notes, and R's dgeom and dnbinom, count failures. If a question asks "on which trial does the first success happen?", the answer is .
Theorem: Mean, Variance and Memorylessness of the Geometric
If :
- and
; the expected number of trials up to the first success is . for - Memorylessness. For any ,
.
Part 2. means the first trials are all failures, which has probability by independence.
Part 3. is a subset of , so their intersection is , and by part 2
Part 1, the mean. A neat trick: for a random variable taking values ,
Memorylessness says that past failures don't make a success "due". If you've already tried 50 passwords without success, the number of further tries you'll need has the same distribution as when you started. This is the gambler's fallacy of Chapter 3, made precise: independent trials have no memory.
Example 4.12: Testing Until the First Fake ★ lecture example
In a seizure, 5% of bags are fakes. A lab tests bags chosen at random, one at a time, until it finds a fake. (The seizure is large, so treat the tests as independent with .) (a) What is the probability that the first fake is the 10th bag tested? (b) That the lab has to test more than 30 bags to find one? (c) How many bags does the lab test on average?
Name the model. Each test is a trial; "success" = finding a fake, . Let be the number of genuine bags (failures) before the first fake:
(a) "The first fake is the 10th bag" means 9 failures then a success, :
(b) "More than 30 bags needed" means the first 30 are all genuine, : So more than one time in five, the lab tests 30 bags and still hasn't found a fake.
(c) The expected number of failures is
dgeom(9, prob = 0.05) # (a)
1 - pgeom(29, prob = 0.05) # (b): Pr(X >= 30) = 1 - Pr(X <= 29)
0.95^30 # the same, from the formula
(1 - 0.05) / 0.05 # (c) expected failures
[1] 0.03151247
[1] 0.2146388
[1] 0.2146388
[1] 19
ggplot(data.frame(x = 0:80, p = dgeom(0:80, 0.05)), aes(x, p)) +
geom_col(width = 0.8) +
geom_vline(xintercept = 19, linetype = "dashed") +
labs(x = "genuine bags tested before the first fake", y = "probability")
The most likely value is 0 (the very first bag is fake), yet the mean is 19 and the tail is long: the geometric distribution is strongly right-skewed. "1 in 20" doesn't mean you'll find one within 20 tries:
Example 4.13: Collect All Six Toys ★ lecture example
A cereal brand puts one of 6 different toys in each box, each equally likely and independently. How many boxes do you expect to buy before you have the whole set?
Break the wait into stages. After you have different toys, a new box gives a new toy with probability . So the number of boxes needed to get from toys to is a geometric wait for a "success" with , and its expected number of boxes (trials, including the success) is .
| toys so far, toys so far, k | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| chance a box is new | ||||||
| expected boxes for this stage | 1 | 1.2 | 1.5 | 2 | 3 | 6 |
Add the stages (linearity of expectation):
set.seed(6)
boxes_needed <- replicate(10000, {
seen <- c(); n <- 0
while (length(unique(seen)) < 6) { seen <- c(seen, sample(6, 1)); n <- n + 1 }
n
})
mean(boxes_needed)
mean(boxes_needed > 20) # how often a collector needs more than 20 boxes
ggplot(data.frame(boxes_needed), aes(boxes_needed)) +
geom_bar() +
geom_vline(xintercept = 14.7, linetype = "dashed") +
labs(x = "boxes needed to collect all 6 toys", y = "number of collectors")
[1] 14.6569
[1] 0.1502
About 15% of collectors need more than 20 boxes. This is the coupon collector's problem. For toys the answer is , which grows a little faster than : collecting all 50 stickers in an album takes about 225 packs on average. Companies that sell trading cards and "loot boxes" in video games know this arithmetic very well.
Waiting for the th success
A prosecutor may need not one confirmed fake but several. Waiting for the th success generalizes the geometric.
Definition: Negative Binomial Distribution
In independent trials with success probability , let be the number of failures before the th success. Then has the negative binomial distribution, , with PMF
Why the formula? means the th success happens on trial . So trial is a success (probability ), and the first trials contain exactly successes and failures, in any order. That's a binomial probability, . Multiply by (independence). For the mean and variance, think of as geometric waits one after another:
Example 4.14: Who Wins the World Series?
In baseball's World Series, two teams play until one of them has won 4 games (a "best of seven"). Suppose the better team wins each game with probability 0.55, independently. What is the probability that the better team wins the series? What if it wins each game with probability 0.6?
Name the model. Think of the games as trials, with "success" = the better team wins. The better team wins the series if it reaches its 4th success before the other team reaches 4, that is, if it loses at most 3 games before its 4th win. With = games lost before the 4th win,
By the formula,
| losses losses x | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 1 | 4 | 10 | 20 | |
| 0.0915 | 0.1647 | 0.1853 | 0.1668 |
Adding,
pnbinom(3, size = 4, prob = 0.55) # better team wins the series
pnbinom(3, size = 4, prob = 0.60)
p <- seq(0.5, 0.8, by = 0.05)
data.frame(game = p, series = round(pnbinom(3, 4, p), 3))
[1] 0.6082878
[1] 0.710208
game series
1 0.50 0.500
2 0.55 0.608
3 0.60 0.710
4 0.65 0.800
5 0.70 0.874
6 0.75 0.929
7 0.80 0.967
(Notice that we can pretend all 7 games are played, even though the series stops early: the extra games can't change who reached 4 wins first.)
What it means. A team that wins 55% of games wins a best-of-seven series only about 61% of the time; at 60% per game, about 71%. A short series is a noisy test of which team is better: the better team loses the World Series surprisingly often, which is part of what makes it fun to watch. Longer series would sort the teams more reliably, by the Law of Large Numbers.
p <- seq(0.5, 0.8, by = 0.01)
ggplot(data.frame(p, series = pnbinom(3, 4, p)), aes(p, series)) +
geom_line() +
geom_abline(slope = 1, intercept = 0, linetype = "dashed") +
labs(x = "Pr(better team wins one game)", y = "Pr(wins the series)")
The series amplifies a small edge (the curve is above the dashed diagonal), but not by much: a series is a sample of at most 7 games, and small samples are noisy.
Think About It: Is Every Try Really Independent?
The geometric distribution assumes independent trials with the same . For each situation, say whether that's plausible: (a) a burglar trying door handles along a street until one opens; (b) a person guessing a 4-digit PIN who never repeats a guess; (c) a basketball player shooting free throws until she misses.
(a) Doubtful: unlocked doors cluster (some streets or buildings are more careless), so after several locked doors the chance of the next being open may be lower than average, not the same. (b) No: guessing without repetition from a finite list makes each new guess more likely to succeed, since fewer possibilities remain; the wait is then uniform on 1 to 10,000, not geometric. (c) Roughly plausible, though players tire and nerves vary. The "hot hand" debate in sports statistics is exactly about whether successive shots are independent. A model's assumptions are claims about the mechanism, and checking them is part of inference.
Key Takeaways
- Geometric : failures before the first success;
; mean ; expected trials . - Memoryless: past failures don't make success "due".
- Negative binomial : failures before the th success; mean .
- Check whether a question counts failures or trials. R:
dgeom,pgeom,dnbinom,pnbinom.
4.6 Hypergeometric: sampling without replacement
The binomial assumes every trial has the same success probability. When we sample without replacement from a small population, that fails: each item drawn changes what's left. Draw a fake bag from 2,000 with 100 fakes, and the next bag is a fake with probability , not . Example 3.11 handled this by counting; here is the general version.
Definition: Hypergeometric Distribution
A population of items contains "successes" and "failures". A simple random sample of items is drawn without replacement. Let be the number of successes in the sample. Then has the hypergeometric distribution, with PMF for every whole number with , and
Why the formula? Every set of items is equally likely: samples. A sample with exactly successes is made by choosing of the successes and of the failures: ways, by the multiplication rule. Divide (Section 3.4). Why the mean? Write as a sum of indicators: give each of the successes in the population an indicator for "is in the sample". By the theorem in Section 1.3, each unit is in a simple random sample with probability , so each indicator has mean , and linearity gives
Compare with the binomial, with . The means are the same. The variance has an extra factor , called the finite population correction: sampling without replacement gives less variability, because the sample can't keep drawing the same kind of item. When the sample is a tiny fraction of the population, the correction is close to 1 and the two distributions are almost identical.
Theorem: Binomial Approximation to the Hypergeometric
If and grow with , while stays fixed, then the hypergeometric probabilities converge to probabilities. In practice the binomial is a good approximation when the sample is less than about 5% of the population.
Sketch. Writing out the factorials, the hypergeometric probability is times a product of fractions: for the successes and for the failures. As and grow, each fraction of the first kind tends to and each of the second kind to , so the product tends to . Removing a few items barely changes the proportions in a huge population. ∎
Example 4.15: The Lady Tasting Tea ★ lecture example
At an afternoon tea at the Rothamsted agricultural research station in England in the early 1920s, the scientist Muriel Bristol claimed she could taste whether milk had been poured into the cup before or after the tea. The statistician Ronald Fisher, who was there, proposed a test: prepare 8 cups, 4 of each kind, in random order, tell her there are 4 of each, and ask her to pick out the 4 "milk first" cups. Let be the number of milk-first cups among the 4 she picks. If she is just guessing, (a) what is the distribution of ? (b) What is the probability she gets all 4 right? (c) Exactly 3?
Name the model. Guessing means her 4 chosen cups are a random sample of 4 from the 8, drawn without replacement. The population has cups, of which are "successes" (milk first). So is hypergeometric with , , .
(b) There are equally likely ways to pick 4 cups, and exactly one of them is the correct set:
(c) Exactly 3 right means choosing 3 of the 4 milk-first cups and 1 of the 4 tea-first cups:
dhyper(0:4, m = 4, n = 4, k = 4) # the whole PMF
choose(8, 4)
[1] 0.01428571 0.22857143 0.51428571 0.22857143 0.01428571
[1] 70
The full PMF is for .
Fisher's reasoning. If she identified all 4 correctly, either she had a real ability or she was very lucky: a 1-in-70 chance. That's rare enough to take her claim seriously. But 3 out of 4 happens by pure guessing almost a quarter of the time, so it would prove nothing. Fisher used this story to open the second chapter of his book The Design of Experiments (1935), and the reasoning (how surprising would this result be if nothing but chance were at work?) is exactly the logic of the hypothesis tests in Chapter 9. According to people who were there, she got them all right.
d <- data.frame(x = 0:4, p = dhyper(0:4, 4, 4, 4), all = 0:4 == 4)
ggplot(d, aes(x, p, fill = all)) + geom_col(width = 0.5) +
scale_fill_manual(values = c("grey60", "orange"), guide = "none") +
labs(x = "milk-first cups correctly chosen, if guessing", y = "probability")
History: Ronald Fisher: A Founder, with a Troubling Side
Ronald Aylmer Fisher (1890–1962) did more than anyone else to create modern statistics. At Rothamsted he worked out how to design experiments using randomization, and he introduced or popularized variance, the analysis of variance, maximum likelihood (Chapter 8) and significance testing (Chapter 9). He was also one of the founders of modern evolutionary genetics. Medicine, agriculture and psychology still run on his methods.
Fisher was also, throughout his life, a committed eugenicist.
- As a student he helped found the Cambridge University Eugenics Society.
- The final chapters of his book The Genetical Theory of Natural Selection (1930) argue for policies to raise the birth rate of the "higher" social classes.
- From 1933 he held the Galton Chair of Eugenics at University College London and edited the Annals of Eugenics.
- In the early 1950s he disputed a UNESCO statement on race, arguing that human groups differ in their innate capacity for intellectual and emotional development.
- Late in life he argued that the evidence linking smoking to lung cancer might not show cause and effect, while working as a consultant to the tobacco industry.
In 2020 his old Cambridge college, Gonville and Caius, removed a stained-glass window that had honoured him.
How should we hold both sets of facts? The mathematics of randomization and likelihood is correct whoever discovered it, and it has saved a great many lives. The policies Fisher argued for didn't follow from that mathematics; they came from assumptions he brought to the data. His language is under review too. In 2019 the editors of a special issue of The American Statistician, the American Statistical Association's journal, called on scientists to stop using the phrase statistically significant (an editorial view, not official ASA policy), which Fisher's work had made central (Chapter 9 explains why). Clayton goes further, suggesting that researchers report a probability distribution for the quantity of interest instead.
Example 4.16: The Drug Seizure, Revisited ★ lecture example
Of 2,000 bags, 100 are fakes, and the lab tests a random sample of 20 (Example 3.11). Let be the number of fakes in the sample. (a) Find and . (b) Find and . (c) How close is the binomial approximation?
Name the model. Sampling without replacement from a finite population, counting "successes" (fakes): is hypergeometric with , , .
(a) By the formula,
dhyper(0, m = 100, n = 1900, k = 20) # Pr(X = 0)
1 - phyper(1, m = 100, n = 1900, k = 20) # Pr(X >= 2)
dbinom(0, 20, 0.05); 1 - pbinom(1, 20, 0.05) # binomial approximation
[1] 0.356686
[1] 0.2640626
[1] 0.3584859
[1] 0.2641605
(R's argument names are confusing: m is the number of successes, n the number of failures, and k the sample size.)
(b) The mean and variance are
(c) The binomial gives
A side-by-side comparison shows how close the two distributions are when the sample is a small fraction of the population:
d <- rbind(data.frame(x = 0:5, p = dhyper(0:5, 100, 1900, 20), model = "hypergeometric (exact)"),
data.frame(x = 0:5, p = dbinom(0:5, 20, 0.05), model = "binomial approximation"))
ggplot(d, aes(x, p, fill = model)) +
geom_col(position = "dodge", width = 0.6) +
scale_fill_manual(values = c("orange", "grey60")) +
labs(x = "fakes in a sample of 20", y = "probability", fill = NULL)
Example 4.17: How Many People? Capture–recapture ★ lecture example
A city wants to estimate how many different people sleep rough on its streets, a population that is hard to count directly. In a January outreach sweep, workers record (with consent) 50 different people. In a February sweep they meet 40 people, of whom 8 were also met in January. Estimate the size of the population.
The idea. January "marks" 50 people. If February's 40 are like a random sample from the whole population of people, the fraction of marked people in February's sample should be about the fraction of marked people in the population:
The model behind it. If the population has people, of whom are marked, the number of marked people in a random sample of is hypergeometric. For each possible , we can ask how probable the observed would be, and choose the that makes it most probable:
N <- 90:800
lik <- dhyper(8, m = 50, n = N - 50, k = 40)
N[which.max(lik)]
ggplot(data.frame(N, lik), aes(N, lik)) +
geom_line() +
geom_vline(xintercept = 250, linetype = "dashed") +
labs(x = "assumed population size N", y = "Pr(8 marked in sample)")
[1] 250
The peak is at (tied, in fact, with ), the same answer as before. Choosing the parameter value that makes the observed data most probable is called maximum likelihood, and it is the main estimation method of Chapter 8. Notice the long right tail: populations of 400 or more are not wildly implausible, so 250 comes with a lot of uncertainty.
Critical thinking: the assumptions. The calculation assumes the population doesn't change between sweeps (no one arrives or leaves), and that every person is equally likely to be met in February whether or not they were met in January. Both are doubtful. People who are easy to find in January are probably easy to find in February too; then February's sample over-represents marked people, the fraction 8/40 is too high, and is too low. Real studies use several sweeps and more elaborate models to deal with this.
Think About It: Who Is in the Sample?
Capture–recapture (Example 4.17) assumes that being "caught" the first time doesn't change your chance of being caught again. Think of a population of drug users estimated from two lists: people treated in hospitals and people arrested. Why might the assumption fail, and in which direction would the estimate be wrong?
The two lists are not independent samples: people with severe addiction are more likely both to be hospitalized and to be arrested, so the same people appear on both lists more often than chance would suggest. The overlap (8 people in Example 4.17) is then too big, and since the estimate divides by the overlap, it is too small: the hidden population is larger than the estimate. Researchers who use this method (to count drug users, victims of trafficking, or casualties of war) try to use lists that are as unrelated as possible, and use three or more lists to detect dependence. This is inference about a mechanism you can't see, and the answer is only as good as the sampling assumptions.
Key Takeaways
- Hypergeometric: successes in a sample of drawn without replacement from items with successes;
. - Mean , like the binomial; variance smaller by the factor
. - If the sample is under about 5% of the population, the binomial with is an excellent approximation.
- R:
dhyper(x, m, n, k)withmsuccesses,nfailures,kdrawn.
Lecture 11 — The Poisson model and choosing a model
4.7 Poisson: counting rare events
Many chances, each small
How many 911 calls arrive at a dispatch desk in an hour? How many typos are on a page, burglaries on a block in a year, cases of a rare disease in a county? In each case there are a huge number of opportunities for the event (thousands of people who might call), each with a tiny probability, independently. The count is binomial in principle, but we don't know or separately: we only know the average rate.
Here is the idea that leads to the Poisson distribution. Suppose calls arrive at an average rate of per hour. Split the hour into short slots, so short that at most one call can arrive in each. Each slot gets a call with probability , independently, so the number of calls is , with mean whatever is. Now let the slots get shorter and shorter.
Theorem: The Poisson Limit of the Binomial
Fix . If
Write out the binomial probability with and rearrange into three factors:
; , a standard limit from calculus; .
So the product tends to . ∎
Definition: Poisson Distribution
A random variable has the Poisson distribution with rate (or mean) , written , if
These probabilities add to 1 by the exponential series (Example 0.2): that is exactly the calculation we did in Chapter 0.
Theorem: Mean and Variance of the Poisson
If , then and .
Mean. The term is zero; for , cancel against and substitute :
Mean equals variance is the Poisson's fingerprint. It explains the insecticide data of Chapter 2 (Exercise 2.10), where counts with bigger averages were also more spread out. And it gives a quick check of whether real counts could be Poisson: compare their sample mean and variance.
Example 4.18: Death by Horse Kick ★ lecture example
In 1898 the Russian–German statistician Ladislaus Bortkiewicz published the number of soldiers killed by horse kicks in 10 corps of the Prussian cavalry over 20 years (1875–1894): 200 "corps-years" in all.
| deaths in a corps-year, deaths in a corps-year, x | 0 | 1 | 2 | 3 | 4 | 5+ |
|---|---|---|---|---|---|---|
| number of corps-years | 109 | 65 | 22 | 3 | 1 | 0 |
(a) Estimate , the average number of deaths per corps-year. (b) Compare the observed counts with what a Poisson distribution with that predicts. (c) Compare the sample mean and variance.
Why might Poisson fit? Each corps had many soldiers, each with a tiny chance of a fatal kick in a year, more or less independently: many chances, each small.
(a) The total number of deaths is
(b) The expected number of corps-years with deaths is
x <- 0:4
observed <- c(109, 65, 22, 3, 1)
lambda <- sum(x * observed) / 200
lambda
expected <- 200 * dpois(x, lambda)
round(data.frame(x, observed, expected), 1)
[1] 0.61
x observed expected
1 0 109 108.7
2 1 65 66.3
3 2 22 20.2
4 3 3 4.1
5 4 1 0.6
ggplot(data.frame(x, observed, expected), aes(x, observed)) +
geom_col(width = 0.5) +
geom_point(aes(y = expected), colour = "orange", size = 3.5) +
labs(x = "deaths in a corps-year", y = "number of corps-years")
The agreement is remarkable: 109 vs 108.7, 65 vs 66.3, 22 vs 20.2, 3 vs 4.1, 1 vs 0.6.
(c) The sample variance of the 200 counts (computed as in Chapter 2) is 0.611, almost exactly the mean 0.61, as a Poisson distribution predicts.
deaths <- rep(x, observed) # the 200 individual counts
c(mean = mean(deaths), var = var(deaths))
mean var
0.6100000 0.6109548
Bortkiewicz called this the law of small numbers: rare events, scattered over many independent opportunities, follow the Poisson distribution, even something as grim and haphazard as a horse kick.
The two goals. The Poisson model predicts how many corps-years should have 0, 1, 2, ... deaths if kicks are random and independent. Comparing that prediction with the data is a piece of inference: the close agreement is evidence that nothing more systematic (a particularly dangerous corps, a bad year) was going on.
Example 4.19: Were the Flying Bombs Aimed? ★ lecture example
In 1944 and 1945 Germany fired V-1 flying bombs at London. People in the city noticed that some districts seemed to be hit again and again while others were spared, and wondered whether the bombs could be aimed at particular targets. After the war, the actuary R. D. Clarke divided an area of south London into 576 small squares of a quarter of a square kilometre each, and counted the hits in each square. There were 537 hits in all:
| hits in a square, hits in a square, x | 0 | 1 | 2 | 3 | 4 | 5 or more |
|---|---|---|---|---|---|---|
| number of squares | 229 | 211 | 93 | 35 | 7 | 1 |
If the bombs fell at random, with no aiming, the number of hits per square should be Poisson. Does the Poisson model fit?
Why Poisson if random? Each of the 537 bombs had a small chance (1 in 576) of landing in any particular square, independently of the others: many chances, each small. So the hits in a square would be close to , which is approximately with
Expected counts. The expected number of squares with hits is
lambda <- 537 / 576
observed <- c(229, 211, 93, 35, 7, 1)
expected <- 576 * c(dpois(0:4, lambda), 1 - ppois(4, lambda)) # last group: 5 or more
data.frame(hits = c("0", "1", "2", "3", "4", "5+"), observed, expected = round(expected, 1))
hits observed expected
1 0 229 226.7
2 1 211 211.4
3 2 93 98.5
4 3 35 30.6
5 4 7 7.1
6 5+ 1 1.6
d <- data.frame(hits = factor(c("0", "1", "2", "3", "4", "5+"), levels = c("0", "1", "2", "3", "4", "5+")),
observed, expected)
ggplot(d, aes(hits, observed)) +
geom_col(width = 0.5) +
geom_point(aes(y = expected), colour = "orange", size = 3.5) +
labs(x = "hits in a square", y = "number of squares")
The fit is excellent: 229 vs 226.7, 211 vs 211.4, 93 vs 98.5, 35 vs 30.6, 7 vs 7.1, 1 vs 1.6. The clusters that Londoners noticed are exactly what random scattering produces: with 576 squares, about 39 should get 3 or more hits by chance alone. The data give no evidence that the bombs could be aimed at specific districts.
The lesson. Randomness is clumpy (remember the coin-faking widget in Section 1.6). People see patterns, such as "cancer clusters", "hot streaks" and "crime waves", in data that are perfectly consistent with chance. Before explaining a cluster, compare it with what the Poisson distribution says chance alone would produce.
Source: R. D. Clarke (1946), "An application of the Poisson distribution", Journal of the Institute of Actuaries 72, 481.
Rates over time and space
The Poisson rate scales with the size of the window. If 911 calls arrive at 4.5 per hour, then in 20 minutes they arrive at per 20 minutes, and in a day at per day. Events that occur one at a time, independently, at a constant average rate, form a Poisson process: the number of events in any window of length is , and counts in non-overlapping windows are independent.
Example 4.20: Calls at a Dispatch Desk ★ lecture example
A 911 dispatch desk receives calls at an average rate of 4.5 per hour during a weekday afternoon, and calls arrive independently. (a) What is the probability of no calls in an hour? (b) The desk has two dispatchers, who can comfortably handle up to 7 calls an hour. What is the probability of 8 or more calls in an hour? (c) What is the probability of a 20-minute stretch with no calls at all?
Name the model. Many potential callers, each unlikely to call in a given hour, independently, at an average rate: calls per hour.
(a)
(b)
dpois(0, lambda = 4.5) # (a)
1 - ppois(7, lambda = 4.5) # (b) Pr(X >= 8)
dpois(0, lambda = 4.5 * 20 / 60) # (c) a 20-minute window: rate 1.5
round(dpois(0:12, 4.5), 3) # the PMF
[1] 0.011109
[1] 0.08658647
[1] 0.2231302
[1] 0.011 0.050 0.112 0.169 0.190 0.171 0.128 0.082 0.046 0.023 0.010
[12] 0.004 0.002
So
(c) In 20 minutes the rate is , so
d <- data.frame(x = 0:12, p = dpois(0:12, 4.5), busy = 0:12 >= 8)
ggplot(d, aes(x, p, fill = busy)) +
geom_col(width = 0.6) +
scale_fill_manual(values = c("grey60", "orange"), labels = c("up to 7", "8 or more")) +
labs(x = "calls in an hour", y = "probability", fill = NULL)
Causal Inference: Regression to the Mean: Hot Spots That Cool Down on Their Own
A police department identifies the 10 blocks with the most burglaries last year as "hot spots" and sends extra patrols. This year, burglaries on those blocks fall by 25%. Did the patrols work?
Not necessarily. Counts like burglaries vary by Poisson chance even when nothing changes. A block that had an unusually high count last year was probably partly unlucky, and next year its luck is likely to be closer to average, patrols or no patrols. Choosing units because their outcome was extreme guarantees that, on average, they'll look less extreme next time. This is regression to the mean, an effect Francis Galton called "regression towards mediocrity" in 1885–86 (the history box in Section 5.3 explains where it came from). In the simulation below, the "patrols" do nothing at all.
The selection is the problem: last year's count caused the block to be chosen, and last year's count is related to this year's only through the block's true rate. A fair test needs a comparison group: randomly choose which hot spots get the patrols (Chapter 1), and compare treated and untreated hot spots in the same year. Real hot-spot policing studies that did exactly this did find genuine (if smaller) effects; studies that only compared before and after could not tell them apart from regression to the mean.
History: Poisson, Bortkiewicz and the Law of Small Numbers
Siméon-Denis Poisson derived the distribution in 1837, as the limit of the binomial, in a book on the probability of judgments in criminal and civil cases: he wanted to know how often juries would convict the innocent. It attracted little attention until Ladislaus Bortkiewicz showed in Das Gesetz der kleinen Zahlen (The Law of Small Numbers, 1898) how well it described rare events in large populations, from horse kicks to child suicides. Today it describes radioactive decay, network traffic, insurance claims and mutations in DNA.
Think About It: Randomness or a Cause?
A town of 20,000 people has 9 cases of a rare childhood cancer in five years, when the national rate would predict about 3. Residents suspect a chemical plant. Using Poisson reasoning, explain why this is genuinely surprising for this town, but why it might not be surprising that some town in the country has a cluster like this. What would you want to know next?
For this town, the count would be about , and 1 - ppois(8, 3) : very unusual. But there are thousands of towns of this size, and among, say, 5,000 towns we'd expect about
Key Takeaways
- Poisson : counts of rare events with many independent opportunities;
. - It is the limit of as .
- Mean = variance = . Rates scale with the window: in a window of length .
- Units chosen for extreme counts tend to look less extreme next time: regression to the mean.
- R:
dpois,ppois,qpois,rpois.
4.8 Choosing the right model
The hardest part of a problem is usually not the arithmetic but deciding which distribution fits. Here are the five named distributions side by side.
Start with the mechanism: what is being counted, and how are the trials run? This flowchart asks the questions in order.
| distribution | the story | values |
|---|---|---|
| successes in independent trials, same | ||
| failures before the 1st success | ||
| failures before the th success | ||
| hypergeometric | successes in drawn without replacement from items with successes | |
| count of rare events at average rate |
| distribution | mean | variance | PMF in R |
|---|---|---|---|
dbinom(x, n, p) |
|||
dgeom(x, p) |
|||
dnbinom(x, r, p) |
|||
| hypergeometric | dhyper(x, M, N-M, n) |
||
dpois(x, lambda) |
Idea: Algorithm: Which Distribution?
- What is being counted? Write $X = $ "the number of ...". If it isn't a count, it isn't one of these.
- Is there a fixed number of trials?
- Yes, drawn with replacement or from a huge population, independent, same : binomial.
- Yes, drawn without replacement from a small, known population: hypergeometric.
- Are we waiting for something? Counting failures until the 1st success: geometric; until the th: negative binomial.
- Is there only a rate, with no natural "number of trials", for events in time or space? Poisson.
- Check the assumptions, especially independence, and say which ones are doubtful.
Example 4.21: Which Distribution? ★ lecture example
For each situation, define , name its distribution with parameters, and compute the probability asked for.
- A detective calls witnesses from a list; each, independently, has information with probability 0.2. What is the probability the first 4 calls find nothing and the 5th succeeds?
- A jury of 6 is chosen at random from a pool of 50 people, of whom 5 are retired police officers. What is the probability the jury includes exactly 2 of them?
- A forensic lab receives an average of 2.5 urgent requests per day, arriving independently. What is the probability of 5 or more on a given day?
- Of a company's emails, 2% are phishing attempts. In a random sample of 50 emails from its huge inbox, what is the probability there are none?
We wait for the first success: = failed calls before the first useful witness . "First 4 fail, 5th succeeds" is :
. A fixed sample drawn without replacement from a small population: = officers on the jury, hypergeometric with , , .
(The sample is 12% of the population, so the binomial would not be a safe approximation here.) Events at a rate, with no fixed number of trials: .
. A fixed number of emails from a huge population, independent, same :
. . (A Poisson with gives : close, as the limit theorem promises.)
dgeom(4, 0.2) # 1
dhyper(2, m = 5, n = 45, k = 6) # 2
1 - ppois(4, 2.5) # 3
dbinom(0, 50, 0.02); dpois(0, 1) # 4, and its Poisson approximation
[1] 0.08192
[1] 0.09376239
[1] 0.108822
[1] 0.3641697
[1] 0.3678794
Check Yourself
Is there a fixed number of yes/no trials, or a count of events at an average rate?
A count of rare events at a rate: Poisson, with
Is the sampling with or without replacement? Is the sample a small fraction of the population?
Without replacement, and 10 is a quarter of the 40 pills: hypergeometric with , , .
Is the number of calls fixed in advance, or does it keep going until something happens? How many successes are needed?
Waiting for the 3rd success: negative binomial with , ; the expected number of failed calls is
Strictly, sampling is without replacement. But how big is the sample compared with the population?
A fixed number of independent-enough trials with the same : binomial,
Key Takeaways
- Start by writing $X = $ "the number of ...".
- Fixed trials with replacement: binomial; without replacement from a small population: hypergeometric; waiting: geometric or negative binomial; a rate: Poisson.
- Every model rests on assumptions, usually independence. Name them, and ask what happens if they fail.
Prediction and inference in this chapter
Every distribution in this chapter is a model of a mechanism with a few parameters, and every example used it in one of two directions.
- Prediction (parameters known, outcome unknown): the expected cost of overbooking, the chance a guesser passes a quiz, the number of boxes needed to collect six toys, the number of calls a dispatch desk must handle. Expected values give the best guess under squared loss; standard deviations and quantiles say how far off it may be; and the best decision (how many tickets, how many dispatchers) minimizes an expected loss.
- Inference (outcome observed, mechanism uncertain): was Paul the octopus guessing? Could Muriel Bristol really taste the difference? Were the V-1 bombs aimed? How big is a hidden population? In each case we asked how probable the observed data would be under a simple "nothing special is going on" mechanism, and found it either plausible (the bombs, the horse kicks) or surprising (all four cups right). The capture–recapture example went one step further and chose the parameter value that made the data most probable: maximum likelihood.
Chapters 8 and 9 turn these informal arguments into estimates with margins of error and into formal tests. They will need one more ingredient first: how averages of random variables behave, which is the subject of Chapters 6 and 7.
4.9 Interludes
Interlude (Optional): Moment Generating Functions
The moment generating function (MGF) of a random variable is for the values of where the sum is finite. It looks like an odd thing to compute, but it packs all the moments into one function. Expanding
Three examples.
- Bernoulli:
. - Binomial: is a sum of independent Bernoullis, and for independent random variables
(Chapter 6), so . Differentiating, . - Poisson:
.
Two powerful facts. First, an MGF (when it exists near ) determines the distribution uniquely. Second, the MGF of a sum of independent random variables is the product of their MGFs. Together they give slick proofs. For example, if and are independent, then
Why it matters: MGFs are the main tool for proving the Central Limit Theorem in Chapter 7.
Interlude (Optional): Entropy: How Surprising Is a Random Variable?
Section 2.6 met Shannon's entropy, a measure of how unpredictable a categorical variable is. It applies to any discrete random variable:
For a Bernoulli trial,
p <- seq(0.001, 0.999, by = 0.001)
H <- -p * log2(p) - (1 - p) * log2(1 - p)
ggplot(data.frame(p, H), aes(p, H)) + geom_line() +
labs(x = "success probability p", y = "entropy H (bits)")
It is largest, 1 bit, at , and zero when the outcome is certain, just like the variance , though entropy and variance are not the same thing: entropy doesn't care what the values are, only how probable they are.
Shannon proved that is the smallest possible average number of bits needed to record outcomes of , which is the foundation of every compression format from ZIP to MP3. And a password chosen uniformly from possibilities has entropy bits: about 52 bits for 8 characters from 94 symbols (Example 3.7). Security experts measure password strength in exactly these bits, and a password people actually choose has far fewer.
Why it matters: entropy turns "how uncertain?" into a number, and underlies information theory, compression, cryptography and the cross-entropy loss used to train classifiers.
Bayesian Inference: Learning a Success Probability
In Example 4.10 we knew the false-positive rate . Usually we don't, and must learn it from data. The Bayesian approach treats the unknown like the suspects in Chapter 3's detective story. Suppose could be any of , all equally plausible at first (the prior). We then see 7 successes in 10 independent trials. For each candidate value of , the likelihood of the data is the binomial probability . Multiply prior by likelihood and rescale:
p_grid <- seq(0, 1, by = 0.1)
prior <- rep(1 / 11, 11)
likelihood <- dbinom(7, size = 10, prob = p_grid)
posterior <- prior * likelihood / sum(prior * likelihood)
round(posterior, 3)
d <- rbind(data.frame(p = p_grid, prob = prior, which = "prior"),
data.frame(p = p_grid, prob = posterior, which = "posterior, 7 of 10"))
d$which <- factor(d$which, levels = c("prior", "posterior, 7 of 10"))
ggplot(d, aes(p, prob)) + geom_col(width = 0.06) + facet_wrap(~ which) +
labs(x = "candidate value of p", y = "probability")
[1] 0.000 0.000 0.001 0.010 0.047 0.129 0.236 0.293 0.221 0.063 0.000
The posterior piles up around 0.7, the observed fraction, but still gives real weight to 0.6 and 0.8: ten trials can't pin down exactly. More data would narrow it further. Chapter 5 replaces the grid of 11 candidates with every value between 0 and 1, which leads to the beta distribution.
4.10 Exercises
Each exercise has a hint and an answer. Start every word problem by writing $X = $ "the number of ..." and naming its distribution.
Exercises
A PMF by hand. Roll two fair dice and let be the larger of the two numbers. (a) Find the PMF of by counting outcomes. (b) Find . (c) Find using the CDF.
Use the 6 × 6 grid (the random-variable widget in Section 3.8 has a "larger of the two dice" option). How many of the 36 outcomes have a maximum of exactly 1? Of exactly 2? Look for the pattern .
(a)
for : that is . (b) . (c) ; equivalently both dice are at most 3, . Expected value and variance. A random variable takes the values , 0 and 2 with probabilities 0.3, 0.5 and 0.2. Find , , and .
Compute and first, then use the shortcut formula and the rules for .
; ; . ; . Insurance. A phone insurance policy costs $120 a year. In a year, 4% of phones are lost or stolen (the insurer pays $900) and another 10% are damaged (the insurer pays $250). (a) Find the insurer's expected profit per policy. (b) Find the standard deviation of its profit. (c) Explain why the insurer cares about the expected value but a customer might not.
The insurer's profit takes three values: , and . Write its PMF, then compute and as in Examples 4.5 and 4.8.
Profit (prob 0.86), (0.04), (0.10). (a)
. (b) , so and . (c) The insurer sells thousands of policies, so by the Law of Large Numbers its average profit per policy will be very close to $59. A customer buys one policy and faces one outcome; they pay $59 on average to avoid a possible $900 loss they might not be able to afford. Binomial. A fingerprint examiner makes an error on 3% of comparisons, independently. In a week she makes 40 comparisons. (a) What is the probability of no errors? (b) Of at least 2 errors? (c) What are the mean and standard deviation of the number of errors? (d) Is independence plausible here? Explain.
. For (b), , which is 1 - pbinom(1, 40, 0.03)in R.(a) . (b)
. (c) Mean , SD . (d) Doubtful: errors may cluster, for example on difficult partial prints, at the end of a long day, or on cases with misleading context information, so one error makes others more likely. Geometric. A password-guessing program tries passwords from a list of common passwords in random order, and each guess independently has a 1-in-50 chance of being right for a given account. (a) What is the expected number of wrong guesses before success? (b) What is the probability it needs more than 100 guesses in total? (c) The program has already made 100 wrong guesses. What is the probability it needs more than another 100?
counts wrong guesses. "More than 100 guesses in total" means the first 100 are all wrong. For (c), use memorylessness. (a) wrong guesses (50 guesses in all, on average). (b)
. (c) By memorylessness, also : the 100 failures so far don't make success any closer. (In reality, guessing without repeating passwords from a finite list isn't memoryless, but the model says each guess is a fresh independent chance.) Hypergeometric. An evidence locker holds 30 bags, of which 8 have been tampered with. An auditor inspects 5 bags chosen at random. (a) What is the probability she finds no tampered bags? (b) At least one? (c) Compare (a) with the binomial approximation and explain the difference.
, , . In R:
dhyper(0, m = 8, n = 22, k = 5). The binomial would use .(a)
. (b) . (c) The binomial gives , noticeably higher. The sample is 1/6 of the population, and each untampered bag drawn makes the next draw more likely to be tampered, so missing every tampered bag is less likely than the binomial suggests. Poisson. A website receives login attacks at an average rate of 3 per minute, independently. (a) What is the probability of no attacks in a given minute? (b) Of more than 6 in a minute? (c) Of at least 10 in a 2-minute window?
One minute: . Two minutes: . "More than 6" is .
(a) . (b)
1 - ppois(6, 3). (c)1 - ppois(9, 6).Poisson approximation. A rare blood type occurs in 0.4% of people. A blood drive collects 500 donations. Find the probability of at least 3 donations with the rare type (a) exactly, with the binomial, and (b) with the Poisson approximation. Why is the approximation good here?
Binomial:
. Poisson: . (a)
1 - pbinom(2, 500, 0.004). (b) ;1 - ppois(2, 2). The approximation is excellent because is large and is small: many chances, each rare, exactly the setting of the Poisson limit theorem.Is it Poisson? R's
InsectSprayscounts insects on plots. For spray C, the 12 counts are 0, 1, 7, 2, 3, 1, 2, 1, 3, 0, 1, 4. (a) Compute the sample mean and variance. (b) Is a Poisson model plausible? (c) Using a Poisson with equal to the sample mean, how many of the 12 plots would you expect to have 0 insects? Compare with the data.x <- InsectSprays$count[InsectSprays$spray == "C"], thenmean(x)andvar(x). For (c), compute12 * dpois(0, mean(x)).(a) Mean , variance . (b) The variance is nearly twice the mean, so the counts are more variable than a Poisson (called overdispersion), largely because of the plot with 7 insects; with only 12 counts, though, the evidence is weak. (c) plots expected, and 2 were observed: reasonably close.
Linearity with indicators. At a party, 30 guests check their coats, and the coats are returned at random. (a) What is the expected number of guests who get their own coat back? (b) A city has 200 intersections, and each has a camera that works on a given day with probability 0.97, not necessarily independently. What is the expected number of working cameras, and why don't you need independence?
Write each count as a sum of indicators, as in Example 4.7. Linearity of expectation doesn't require independence.
(a) Each guest gets their own coat with probability , so the expected number is . (b)
. holds whatever the dependence; independence would matter for the variance (for example, a citywide power cut would knock out many cameras at once). Which model? For each, define , name the distribution and its parameters, and state one assumption that might fail. (a) The number of jurors, out of 12, who have served on a jury before, if 30% of the jury pool has. (b) The number of murders in a city next month, which averages 25 per month. (c) The number of houses a burglar tries before finding an unlocked one, if 10% of houses are unlocked. (d) The number of women on a 5-person panel chosen at random from 9 men and 6 women.
Use the algorithm in Section 4.8: fixed trials or waiting? With or without replacement from a small group? Or just a rate?
(a) ; jurors aren't independent draws if the pool is small (then hypergeometric). (b) ; murders can cluster (a single incident with several victims, retaliation), breaking independence. (c) ; a burglar doesn't choose houses at random, and unlocked houses may cluster on certain streets. (d) Hypergeometric with , , ; assumes the panel really is chosen at random.
Regression to the mean. A school district names its 5 lowest-scoring schools (out of 100) as "failing" and gives them extra tutoring. Next year, their average score rises noticeably. (a) Give a reason this could happen even if the tutoring had no effect. (b) Design a better way to evaluate the tutoring.
Test scores vary by chance from year to year. Why were these 5 schools chosen? Think about the hot-spots widget in Section 4.7.
(a) The schools were chosen because their scores were unusually low. Part of a low score is bad luck (a difficult year, a few absent students), and next year's luck is likely to be closer to average, so their scores would tend to rise anyway: regression to the mean. (b) Among the low-scoring schools, randomly choose which ones get tutoring and compare the change in scores between tutored and untutored schools over the same year.
How long should a quiz be? A teacher wants a true/false quiz on which a student who guesses every answer has less than a 5% chance of scoring 70% or more. Using quizzes of 10, 20 or 30 questions, which is the shortest that works?
A guesser's score is . "70% or more" of 10 questions is at least 7 right, so compute
= 1 - pbinom(6, 10, 0.5), and similarly for 20 (at least 14) and 30 (at least 21).10 questions:
. 20 questions: , just too high. 30 questions: . So 30 questions. More questions make it harder to do well by luck, because the guesser's fraction correct concentrates around 0.5 (the Law of Large Numbers again). Are great discoveries Poisson? Using R's
discoveries(Example 4.2), (a) compare the mean and variance of the yearly counts. (b) Compute the number of years out of 100 that a Poisson distribution with the same mean predicts for 0 to 6 discoveries, and compare with the data. (c) Suggest a reason for any mismatch.d <- as.numeric(discoveries); thenmean(d),var(d)andround(100 * dpois(0:6, mean(d)), 1). Compare withtable(d). Remember the Poisson's fingerprint.(a) Mean 3.1, variance 5.08: much bigger than the mean, so the counts are overdispersed. (b) Poisson predicts about 4.5, 14.0, 21.6, 22.4, 17.3, 10.7 and 5.6 years with 0 to 6 discoveries, against 9, 12, 26, 20, 12, 7 and 6 observed; it predicts too few years with 0 and with 7 or more (3.9 predicted, 8 observed). (c) The Poisson assumes a constant rate, but discoveries came in bursts (eras of rapid progress, and quieter periods such as wartime), so the rate itself varied from year to year. A varying rate makes counts more spread out than a single Poisson. The negative binomial is often used for such overdispersed counts.
Settling in Catan. In the board game Settlers of Catan, two dice are rolled every turn, and a settlement collects one resource whenever the total matches the number on an adjacent tile. (a) A settlement touches tiles numbered 6, 8 and 9. What is the expected number of resources it collects per roll? (b) Over 60 rolls? (c) Compare a settlement on tiles 2, 3 and 12. Why do experienced players avoid it?
Write the number collected per roll as a sum of three indicators, one per tile.
; use the dice-total distribution from Example 3.22 for the others, then linearity. (a)
resources per roll. (b) . (c) per roll, about 6.7 in 60 rolls: less than a third as productive. (The game prints the "hot" numbers 6 and 8 in red for this reason.)