…
…
Statistics and Data Analysis Fundamentals · Lesson 30 / 44 · Inference by simulation
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Bazaar's annual report has three lines: "Customer satisfaction is 3.93", "Our return rate is 7.2%", and, from lesson 29, "The new checkout page cut purchases by 5 points". Management asks: "With 300 other customers, or two other weeks, how much would these numbers change?" You have only one sample. In this lesson you will measure that wobble without running a new survey.
By the end of this lesson you will write the satisfaction line of the report like this: "In a survey of 300 customers, mean satisfaction was 3.93 (95% confidence interval 3.84 to 4.02)." The two numbers in the parentheses tell you how much the mean could move with another 300 customers. You will find these two numbers from a single sample, with simulation and no formula.
In this lesson you will:
A single number you compute from a sample is called a point estimate. The mean satisfaction of 300 customers, 3.93, is a point estimate. What we really want to know is the mean of all Bazaar customers, which lesson 25 called the parameter. A point estimate is almost never exactly equal to the parameter. With another 300 customers we might have found 3.90 or 3.97.
In lesson 25 you saw one way to measure this wobble: draw thousands of samples from the population, compute the mean of each, and look at how spread out those means are. In that lesson we treated the 885 orders as the population, because we had all of them. Real life is different. Bazaar did not survey all its customers, only 300 of them. We cannot draw new samples from the population. We have one sample.
In this lesson we will solve that problem and write the result as a confidence interval: next to the point estimate, two numbers wide enough to catch the parameter with high probability. "Satisfaction is 3.93" is a point. "Satisfaction is between 3.84 and 4.02 (95% confidence)" is an interval. The interval tells you both the estimate and how precise the estimate is.
If we cannot see the population, the best information we have about it is the sample itself. The satisfaction scores of 300 customers are like a small copy of the scores of all customers. If about 45% of the scores are 4, then about that share of the population gave a 4 too. This is where the bootstrap idea comes from: treat the sample as the population, and run lesson 25's "draw a new sample from the population" experiment on the sample itself. The statistician Bradley Efron proposed the method. Its name comes from the English phrase "pull yourself up by your own bootstraps": you get somewhere without outside help, here by measuring uncertainty with the data you already have and no new data.
One detail decides everything: the draw is made with replacement. From the n observations you have, you pick one, write it down, put it back, and repeat until you have n observations again. This new list is called a bootstrap sample. Because you put each one back, the same customer can come up several times, and some customers may not come up at all. What if we drew without replacement? Drawing 300 customers out of 300 without replacement takes the same 300 customers in a different order. The mean would be 3.93 every time, and we would see no wobble.
First, let's look inside one bootstrap sample with a tiny example (Example 1, outside the case). Five students' exam scores are [3, 5, 4, 2, 4], with a mean of 3.6. One bootstrap draw means picking five indexes between 0 and 4. The list picked below is the result of one such draw (we use a fixed list instead of a random generator so that we see the same trace every time). Step through the code and notice that index 2 comes up twice, and index 3 (the student who scored 2) never comes up.
Run the code line by line: see which line runs next, the variable boxes and the output.
scores = [3, 5, 4, 2, 4] picked = [2, 0, 2, 4, 1] new_sample = [] total = 0 for i in picked: value = scores[i] new_sample.append(value) total = total + value print("index", i, "-> score", value) print("Bootstrap sample:", new_sample) print("Its mean:", total / len(new_sample))
The bootstrap sample is [4, 3, 4, 4, 5], with a mean of 4.0. The original mean was 3.6. There is no new score in the new list: the existing scores simply repeat a different number of times. The student who scored 2 never came up in this draw, so the mean moved up. In another draw that student could come up twice, and the mean would move down. This movement imitates how much the mean could change if the sample were a different sample.
There is a common misunderstanding here: "The bootstrap creates new data and makes the sample bigger." It does not. A bootstrap sample is the same size as the original sample, and it contains only values from the original sample. Drawing 10,000 bootstrap samples does not find 10,000 new students. It shuffles the information of the same five students in 10,000 different ways.
The scores are [3, 5, 4, 2, 4]. In what range can the mean of any bootstrap sample (with replacement, 5 values) from this list fall?
Now let's do the same with the satisfaction scores of 300 customers (Example 2). In lesson 23 you saw that rng.choice(x, n) picks n values from the array x with replacement; with replacement is the default of choice. For a bootstrap sample, n is the length of the data itself: rng.choice(x, len(x)).
import numpy as np import pandas as pd a = pd.read_csv("survey.csv") x = a["satisfaction"] print("Data, first 10:", x.head(10).tolist()) print("Data mean:", round(x.mean(), 2)) rng = np.random.default_rng(42) sample = rng.choice(x, len(x)) print("Bootstrap, first 10:", sample[:10].tolist()) print("Bootstrap mean:", round(sample.mean(), 2))
OutputData, first 10: [4, 3, 3, 5, 3, 4, 3, 5, 4, 4]
Data mean: 3.93
Bootstrap, first 10: [4, 4, 4, 5, 5, 4, 4, 4, 4, 3]
Bootstrap mean: 3.97The first ten values of the bootstrap sample are not the same as the first ten of the data, because they were picked at random from the 300 customers. Some customers appear two or three times in this list, and some do not appear at all. Its mean is 3.97: close to the original 3.93, but not equal. Another bootstrap sample gives another mean. Running the cell again will not show this, because seed 42 produces the same draw every time. Change the seed:
Try it now· not graded; doesn't affect progress
One bootstrap mean says nothing. We look at thousands of them. The recipe is the same as the simulation in lesson 25: in a loop, draw a bootstrap sample 10,000 times and append the mean of each to a list. The distribution of these 10,000 means is called the bootstrap distribution. Then use the percentiles from lesson 15: between the 2.5th percentile and the 97.5th percentile lies the middle 95% of the 10,000 values. These two numbers are the percentile bootstrap interval.
import numpy as np import pandas as pd x = pd.read_csv("survey.csv")["satisfaction"] rng = np.random.default_rng(42) means = [] for i in range(10_000): sample = rng.choice(x, len(x)) means.append(sample.mean()) lower, upper = np.percentile(means, [2.5, 97.5]) print("Point estimate:", round(x.mean(), 2)) print("95% interval:", round(lower, 3), "-", round(upper, 3)) print("Standard deviation of the bootstrap means:", round(np.std(means), 3))
OutputPoint estimate: 3.93
95% interval: 3.837 - 4.02
Standard deviation of the bootstrap means: 0.047The report line is ready: "Mean satisfaction is 3.93 (95% confidence interval 3.84 to 4.02)." The 0.047 in the last line is also a familiar number. The standard deviation of the bootstrap means is an estimate, made from this data, of the standard error from lessons 25 and 26. You can also check it with the rule from lesson 26, "about 95% lies within ±2 standard errors": 3.93 ± 2 × 0.047 gives 3.836 to 4.024, very close to the percentile interval.
Now draw two histograms side by side in the same cell: on the left the raw scores of the 300 customers, on the right the 10,000 bootstrap means with two red vertical lines (the ends of the interval). Look at the axis scales. The raw scores spread from 2 to 5, while the bootstrap means form a narrow peak between 3.8 and 4.1. Then set the column variable to "recommend_score" (the 0–10 recommendation score).
Try it now· not graded; doesn't affect progress
The two histograms answer two different questions. The left one answers "which scores did customers give?": 14 customers gave a 2 and 79 gave a 5, and more than half of the customers are outside the 3.84 to 4.02 interval, because the scores are integers and only 4 is inside it. The right one answers "how much does the mean wobble?". A common misunderstanding appears right here: "The 95% interval covers 95% of the customers." It does not. The interval describes the mean, not individual customers. The scores of 300 customers can spread over a wide range, while their mean stays in a narrow interval.
95% is a choice. From the same bootstrap distribution, we take the 5th and 95th percentiles for a 90% interval, and the 0.5th and 99.5th percentiles for a 99% interval. The general rule: for confidence level C, cut (1 − C) / 2 from each tail.
import numpy as np import pandas as pd x = pd.read_csv("survey.csv")["satisfaction"] rng = np.random.default_rng(42) means = [] for i in range(10_000): means.append(rng.choice(x, len(x)).mean()) print("90%:", np.percentile(means, [5, 95]).round(2)) print("95%:", np.percentile(means, [2.5, 97.5]).round(2)) print("99%:", np.percentile(means, [0.5, 99.5]).round(2))
Output90%: [3.85 4.01]
95%: [3.84 4.02]
99%: [3.8 4.05]More confidence means a wider net. The 99% interval (3.80 to 4.05) is clearly wider than the 90% interval (3.85 to 4.01), because if you want the method to miss less often, you have to cast the net wider. This also shows a misunderstanding: "The narrower the interval, the better, so lowering the confidence level is fine." The 90% interval looks narrower and more "precise", but about 1 in 10 intervals built this way misses the true value. With 95% it is 1 in 20. The price of narrowness is being wrong more often.
The second thing that decides the width is the sample size. What would happen if the survey had only the first 75 customers?
import numpy as np import pandas as pd x = pd.read_csv("survey.csv")["satisfaction"] first75 = x.head(75) rng = np.random.default_rng(42) means = [] for i in range(10_000): means.append(rng.choice(first75, len(first75)).mean()) print("75 customers, mean:", round(first75.mean(), 2)) print("95% interval:", np.percentile(means, [2.5, 97.5]).round(2))
Output75 customers, mean: 4.03
95% interval: [3.84 4.21]With 75 customers the interval is 0.37 wide, and with 300 customers it is 0.18 wide. Four times the data gives about half the width: the √n rule from lessons 25 and 26 works here too. If you want a narrow interval, the most honest way is to collect more data.
Try the same two effects yourself on a small dataset outside the case (Example 3). A student wrote down their commute time in minutes on 12 workdays, with a mean of 38.3 minutes. The code below builds a bootstrap interval for the mean (not the median). Change the values of confidence and repeats and compare the ends:
How do the confidence level and the number of bootstrap repeats change the ends of the interval? (12 days of commute time, mean 38.3 min)
Pick a value; predict the output first, then look.
1import numpy as np2confidence = 0.953repeats = 100004times = [34, 41, 29, 38, 52, 36, 33, 45, 31, 39, 47, 35]5rng = np.random.default_rng(42)6means = []7for i in range(repeats):8 sample = rng.choice(times, len(times))9 means.append(sample.mean())10tail = (1 - confidence) / 2 * 10011lower, upper = np.percentile(means, [tail, 100 - tail])12print("Confidence:", confidence, "| repeats:", repeats)13print("Interval:", round(lower, 2), "-", round(upper, 2))
Confidence: 0.95 | repeats: 10000 Interval: 34.75 - 42.25
Faded lines didn't run with this value. The confidence level decides the width: at 90% the interval is about 6 minutes wide, at 99% about 10 minutes wide. The number of repeats moves the ends only a little (at most 0.25 minutes between 1,000 and 10,000); more repeats do not make the interval narrower, they only make the ends more stable. What would narrow the interval is more days (data). With 12 observations the interval is wide: the mean is about 38 minutes, but the true mean could be 35 or 42.
There is an important difference here: the number of bootstrap repeats (1,000 or 10,000) and the sample size (12 days or 300 customers) are different things. Increasing the repeats makes the calculation more careful, but it does not add information, and the width of the interval does not change. Increasing the sample size adds real new information and makes the interval narrower.
We have an interval: 3.84 to 4.02. What exactly does "95% confidence" say? The true mean satisfaction of all Bazaar customers is a fixed number. We do not know it, but it does not change. This fixed number is either between 3.84 and 4.02 or it is not, so saying "it is inside with 95% probability" has no meaning. What is uncertain is not the true value but the interval we built: a different sample would have given a different interval.
The correct interpretation belongs to the method: if you applied this method again and again, about 95% of the intervals you built would cover the true value. This is called the confidence level (or coverage) of the method. In everyday language, "between 3.84 and 4.02 with 95% confidence" is acceptable, as long as you remember that the "confidence" belongs to the method that built the interval, not to this one interval, and that the interval covers the mean, not the scores of individual customers.
What is the best way to interpret a "95% confidence interval"?
To test the sentence "95% of the intervals cover", we need to know the true value. We do not know it in the survey data, but we can use the trick from lesson 25 (Example 4). Let's treat the delivery times of the 851 delivered orders in orders.csv as the population. The population mean is 2.981 days, and this time we know the true value.
Then we imitate 100 times what happens in real life. We draw a sample of 50 orders from the population (with replacement, as in lesson 25). As if this sample were the only data we have, we build a bootstrap interval with 1,000 repeats from it, and check whether the interval covers 2.981. For the bootstrap, instead of a loop we use the size=(1000, n) pattern from lesson 25: each row is one bootstrap sample, and mean(axis=1) is the mean of each row. We draw the 100 intervals one below the other. The ones that miss the true value are red.
Try it now· not graded; doesn't affect progress
The two lines of output:
OutputTrue mean: 2.981
Intervals covering the true value: 95 / 100Each of the 100 horizontal lines in the chart is an interval built from a different sample of 50 orders. The vertical black line is the true mean. 95 of the lines cross the black line, and 5 (the red ones) lie entirely on one side of it. In real life you cannot know which interval is one of the misses, because you have only one line. What you know is that this method hits about 95% of the time in the long run. When we run the same code with 1,000 samples, the coverage comes out as 0.947.
When you change n, watch two things. The lines get shorter or longer: at n = 100 the intervals are narrower, and at n = 30 they are wider. But the coverage stays about the same (95 and 97). The sample size changes the width of the interval, while the confidence level decides how often the intervals hit. You also do not need exactly 95 out of 100. Seeing 93 or 97 in 100 intervals is normal, like seeing 47 heads instead of 50 in 100 coin tosses.
The strongest point of the bootstrap is that its recipe does not change: draw with replacement, compute the statistic, repeat thousands of times, take the percentiles. The statistic does not have to be a mean. Below are three different statistics (Example 5): the return rate, the difference in purchase rate in the A/B experiment from lesson 29, and the median order amount. For the difference between two groups, each group is resampled within itself: 500 draws from B's 500 sessions, 500 draws from A's 500 sessions, and the difference is again B − A as in lesson 29.
import numpy as np import pandas as pd s = pd.read_csv("orders.csv") o = pd.read_csv("sessions.csv") returned = (s["status"] == "returned").to_numpy() A = o.loc[o["group"] == "A", "purchased"].to_numpy() B = o.loc[o["group"] == "B", "purchased"].to_numpy() amount = s["amount"].to_numpy() rng = np.random.default_rng(42) rates, diffs, medians = [], [], [] for i in range(10_000): rates.append(rng.choice(returned, len(returned)).mean()) for i in range(10_000): b_mean = rng.choice(B, len(B)).mean() a_mean = rng.choice(A, len(A)).mean() diffs.append(b_mean - a_mean) for i in range(10_000): medians.append(np.median(rng.choice(amount, len(amount)))) print("Return rate:", round(returned.mean(), 4), np.percentile(rates, [2.5, 97.5]).round(4)) print("Purchase rate difference B - A:", (B.mean() - A.mean(), 3), np.percentile(diffs, [2.5, 97.5]).(3)) (, np.median(amount), np.percentile(medians, [2.5, 97.5]).(1))
OutputReturn rate: 0.0723 [0.0554 0.0893]
Purchase rate difference B - A: -0.05 [-0.088 -0.012]
Median amount: 44.95 [40.5 45. ]Let's turn each line into a report sentence. Return rate: 7.2%, with a 95% interval from 5.5% to 8.9%. The "5%" claim from lesson 27 falls outside this interval. A/B difference: −0.05, with an interval from −0.088 to −0.012. The whole interval is below zero: the drop with design B could be as small as 1 point or as large as 9 points, but "no difference" does not fit this data well. Median amount: $44.95, with an interval from $40.5 to $45.0.
Let's put one misunderstanding to rest: "Whether the interval contains zero (or the claimed value) has nothing to do with a test." It does. In lesson 27, for the 5% claim, the share of results as extreme as the observed one was 0.0016, and the interval also leaves 5% outside. In lesson 29, for the A/B difference we found a two-sided p = 0.0135 and rejected the "no difference" claim, and the interval also leaves zero outside. The test asks "is this claim consistent with the data?", and the interval asks "which values are consistent with the data?". They look at the same data from two sides, and they usually point the same way. The interval has an extra benefit: it tells you how large the difference could be.
The median interval may look odd: the upper end, 45.0, is almost exactly the point estimate, 44.95. Order amounts cluster at certain prices (the $44.95 products sell a lot). The median does not move smoothly. It jumps between these prices, and most bootstrap medians land on $44.95 or on a few lower prices. With data like this, the interval can lean to one side. That is fine. It only shows that an interval is not always symmetric around the point estimate.
Match the four intervals to the right report sentences:
Match each bootstrap interval (95%) to the right report sentence.
For each row, pick its match from the list, then check.
The bootstrap is powerful, but it is not magic. All of its information comes from the sample you have, and it cannot know what is not in the sample. Be careful in three situations.
A biased sample. Remember the volunteer survey from lesson 3: if only very happy or very angry customers answer, the sample does not represent the population. The bootstrap treats this sample as the population, so it builds the interval in the wrong place, and a narrow one too. Think of a school (Example 6, outside the case): someone asked only 40 students who are club members "Do you like your school?" and built a bootstrap interval. This interval describes the club members, not the whole school. Students who join a club may like the school more to begin with, and the bootstrap cannot fix that.
A small sample. You saw it in the 12-day commute example: with little data the interval is wide. More importantly, in a very small sample, the sample is not a good copy of the population, and the interval can come out narrower than it should be.
Skewed data and a small n. With very right-skewed data like order amounts, bootstrap intervals built from small samples cover less than 95%.
An advanced note: when we ran the coverage simulation from step 7 with order amounts (very right-skewed), the 95% intervals built from samples of 20 orders covered the true mean only 84% of the time in 1,000 trials. With samples of 200 orders, the coverage rose to 92%. The more skewed the data and the smaller the n, the more optimistic the percentile interval becomes. In lesson 32 you will see the t interval for the mean, built with a formula. For satisfaction that interval is 3.836 to 4.024, very close to the bootstrap interval.
Try a scenario to see how a report can take these limits into account:
You will write the satisfaction line of the annual report. You have a survey of 300 customers, a mean of 3.93, and a 95% bootstrap interval of 3.84 to 4.02 from 10,000 repeats. Management's target is 4. Which sentence do you write?
Pick an option and see what happens. There are no points; you can try the other options too.
You can now state a number not alone but as "a point estimate and how much it can wobble". In lessons 27, 28, and 29 you tested a claim by simulation. In this lesson you built the range of values consistent with the data by simulation. In lessons 31 and 32 you will find the same intervals and tests with formulas, and put them next to the simulation results.
Order amounts are very right-skewed, but there are 885 orders. The 95% bootstrap interval for the mean amount:
import numpy as np import pandas as pd s = pd.read_csv("orders.csv") t = s["amount"] rng = np.random.default_rng(42) means = [] for i in range(10_000): means.append(rng.choice(t, len(t)).mean()) print("Mean amount:", round(t.mean(), 1)) print("95% interval:", np.percentile(means, [2.5, 97.5]).round(1))
OutputMean amount: 75.5
95% interval: [69.3 82.5]Report sentence: "Across 885 orders, the mean amount is $75.5; the 95% bootstrap interval is $69.3 to $82.5." The interval is a little longer to the right of the point estimate (about $6 down, about $7 up): a few very large orders show up more than once in some bootstrap samples and pull the mean up. In lesson 25, the means of samples of 30 orders moved between about $50 and $110. With 885 orders the wobble is much smaller.
In the survey, mobile customers' satisfaction is a little higher than desktop customers'. Does the interval for this difference contain zero? Each group is resampled within itself, and the difference is mobile − desktop:
import numpy as np import pandas pd a = pd.read_csv() mobile = a.loc[a[] == , ].to_numpy() desktop = a.loc[a[] == , ].to_numpy() rng = np.random.default_rng(42) diffs = [] i (10_000): m = rng.choice(mobile, (mobile)).mean() d = rng.choice(desktop, (desktop)).mean() diffs.(m - d) (, (mobile), , (desktop)) (, (mobile.mean() - desktop.mean(), 3)) (, np.percentile(diffs, [2.5, 97.5]).(3))
Drawing the bootstrap sample without replacement. If you add replace=False to rng.choice, every "bootstrap sample" is the data itself (the same 300 scores in a different order):
import numpy as np import pandas as pd x = pd.read_csv("survey.csv")["satisfaction"] rng = np.random.default_rng(42) means = [] for i in range(10_000): sample = rng.choice(x, len(x), replace=False) means.append(sample.mean()) print("95% interval:", np.percentile(means, [2.5, 97.5]).round(2))
Output95% interval: [3.93 3.93]All 10,000 means are 3.93, and the interval collapses into a single point. The code raises no error, so the mistake is easy to miss, and the result can be read as "the interval is very narrow, so the result is certain". All of the bootstrap's wobble comes from drawing with replacement: the same customer showing up several times and some customers not showing up at all.
rng.choice(x, len(x))). The distribution of the statistic computed over thousands of bootstrap samples imitates how much the statistic would wobble with another sample, and it adds no new data.np.percentile(values, [2.5, 97.5]) for 95%, [5, 95] for 90%. Higher confidence gives a wider interval, more data gives a narrower one, and the same recipe works for a mean, a proportion, a median, and a difference between two groups.Next lesson: you will find the same interval and test for a proportion with a formula, and compare them with the bootstrap results.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
OutputMobile: 174 | desktop: 126
Difference: 0.044
95% interval: [-0.151 0.235]The difference is 0.044 points, but the interval runs from −0.15 to 0.23: it stretches to both sides of zero. Mobile customers could be a little less satisfied than desktop customers, or a little more. With this data we cannot say "satisfaction differs between the two devices", and we cannot say "it is the same" either, because the interval allows a difference of up to 0.2 points. Also, the device was not assigned at random (lesson 29), so even if we had found a real difference, this data could not tell us the cause.
rng.choice