…
…
Statistics and Data Analysis Fundamentals · Lesson 27 / 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.
According to an industry report, a reasonable return rate in e-commerce is 5%, and management aims for this number. At Bazaar, 64 of 885 orders were returned in six months, which is 7.2%. The logistics manager objects: "This difference could be chance, because a store with a true rate of 5% can also see 64 returns in some six-month periods." In this lesson you will test this objection with a simulation.
By the end of this lesson you will take a chart and two sentences to the logistics manager. The chart shows 10,000 separate six-month periods of a store whose true return rate is exactly 5%: in every period there are 885 orders, and the chart shows how many returns each period had. Bazaar's 64 returns sit at the far right of this chart, in an almost empty region:
periods · Simulation with the number of orders in Bazaar orders.csv, seed 42 (fictional sample data)
| — | number of periods |
|---|---|
| 20–23 | 4 |
The two sentences you will write under the chart are these: "A store with a true return rate of 5% sees 64 or more returns in 885 orders in only 16 of 10,000 six-month periods, which is 1 or 2 times in about 1,000 periods. Bazaar's data does not fit the 5% claim."
In this lesson you will:
In lesson 25 you saw that samples drawn from the same population give different results. Even a store with a true return rate of exactly 5% does not see exactly 5% returns in every six-month period; some periods give 4%, others 6%. So "7.2% is larger than 5%" proves nothing on its own. The real question is this: how far can chance push the rate away from 5%? Is 7.2% inside the usual limits of this push, or outside?
To make this question concrete, let's look at two claims. The first is about all orders, the second only about orders from desktop:
import pandas as pd orders = pd.read_csv("orders.csv") orders["returned"] = orders["status"] == "returned" print("All orders:", orders["returned"].sum(), "/", len(orders), "=", round(orders["returned"].mean(), 3)) desktop = orders[orders["device"] == "desktop"] print("Desktop:", desktop["returned"].sum(), "/", len(desktop), "=", round(desktop["returned"].mean(), 3))
OutputAll orders: 64 / 885 = 0.072
Desktop: 23 / 369 = 0.062Both rates are higher than 5%. But is the evidence equally strong in both? How much you can trust a rate depends on two things: how far it is from 5%, and how many orders it is based on. Remember from lesson 25: the larger the sample, the less the rates move. Before you start calculating, test your intuition:
For all orders there are 64 returns in 885 (7.2%), and for desktop there are 23 returns in 369 (6.2%). Which one is stronger evidence against the claim "the true return rate is 5%"?
We want to answer this prediction with a number, not with intuition. For that, we first need to turn the word "chance" into an exact model.
The first step in testing a claim is to write it as two opposite sentences. The null hypothesis (H₀ for short, read "H zero") is the "boring" claim that we test: "there is no difference", "nothing has changed", "the rate is as stated". In our case, H₀: the true return rate is 0.05. This is exactly what the logistics manager defends: 7.2% is only an effect of chance, and Bazaar is really a 5% store.
The alternative hypothesis (H₁) is the claim we look for evidence for. Management's concern is that the return rate is above the target, so H₁: the true return rate is greater than 0.05. The direction of H₁ comes from the question itself; it is not chosen by looking at the data.
Why do we build H₀ from the "boring" claim? Because we can run a simulation under it. "The rate is 0.05" is an exact number; like in lesson 23, we can use a generator that counts each order as a return with probability 0.05 and produce thousands of six-month periods. "The rate is greater than 0.05" is not an exact model: is it 0.06, 0.08, or 0.2? There is no single number to simulate. So the method works the other way around: we assume H₀ is true and look at how much the data contradicts this assumption.
The courtroom comparison explains one more thing: H₀ is not what we try to prove. A court does not try to prove innocence; it looks at whether guilt can be proven. In the same way, we do not ask "is 5% true?"; we ask "does the data fit 5%, or does it put it under pressure?" Match the four claims below as H₀ or H₁. Hint: sentences that say "no difference", "did not change", or "exactly this much" are H₀; the change or direction we want to prove is H₁.
In a test, is each claim a null hypothesis (H₀) or an alternative (H₁)?
For each row, pick its match from the list, then check.
Now we turn H₀ into a simulation. The question is: if the true return rate were exactly 0.05, how many returns would we see in a six-month period of 885 orders? A single six-month period says nothing, so we produce thousands of periods and look at the distribution of the results. The null distribution is the simulated distribution of the results that data of the same size would give if H₀ were true. Think of it as the parallel universes of the 5% store: in every universe the same store, the same 885 orders, and the same true rate of 5%; the only difference is chance.
One more prediction before we simulate. Picture the shape of this distribution:
We simulate six-month periods with 885 orders for a store whose true return rate is exactly 5%. How many returns appear in each period?
Let's start with the hand-made simulation from lesson 23. Every row is one six-month period and every column is one order: we build a table of random numbers with 10,000 rows and 885 columns. If a number is below 0.05, that order counts as a return. The row sums are the number of returns in each period.
import numpy as np rng = np.random.default_rng(42) returned_grid = rng.random((10_000, 885)) < 0.05 simulated = returned_grid.sum(axis=1) print(simulated[:8]) print("Mean:", simulated.mean())
Output[50 31 47 50 38 45 47 44]
Mean: 44.225The first eight "parallel periods" gave 50, 31, 47, 50, 38, 45, 47, and 44 returns. All of them come from the same 5% store; the difference is purely chance. The mean is 44.2, very close to the expected 44.25. The variable is called simulated because these are not real results; they are results produced under H₀.
Follow what happens inside this table with a small example, step by step. Think of the list below as 10 numbers from a random generator; each number is one order. The loop compares each number with the threshold and counts the returns. After you watch it, change threshold from 0.05 to 0.2: how does the number of returns change with the same numbers?
Run the code line by line: see which line runs next, the variable boxes and the output.
numbers = [0.31, 0.04, 0.77, 0.12, 0.66, 0.02, 0.91, 0.45, 0.18, 0.58] threshold = 0.05 returns = 0 for x in numbers: if x < threshold: returns = returns + 1 print(x, "-> returned") else: print(x, "-> delivered") print("Returns in this tiny six-month period:", returns)
With a threshold of 0.05, only 0.04 and 0.02 were counted as returns: 2 returns. With a threshold of 0.2, 0.12 and 0.18 join them: 4 returns. The threshold is the rate in H₀; changing the chance model means changing this one number.
The hand-made way shows clearly what happens, but it produces 8.85 million random numbers. Because the process is exactly binomial (a fixed 885 trials, a probability of 0.05 in each, independent of each other), the shortcut from lesson 23 does the same job in one line: rng.binomial(885, 0.05, size=10_000).
import numpy as np rng = np.random.default_rng(42) simulated = rng.binomial(885, 0.05, size=10_000) print(simulated[:8]) print("Mean:", simulated.mean(), "| standard deviation:", round(simulated.std(), 1)) print("Middle 95%:", np.percentile(simulated, [2.5, 97.5])) print("Min:", simulated.min(), "| max:", simulated.max())
Output[52 33 37 43 44 36 41 33]
Mean: 44.2365 | standard deviation: 6.5
Middle 95%: [32. 57.]
Min: 22 | max: 71These four lines are the ID card of the null distribution. The mean is 44.2 returns and the standard deviation is 6.5 returns. The middle 95% of the 10,000 periods is between 32 and 57 returns; we took the percentiles from lesson 15 with np.percentile. The most extreme results are 22 and 71. The first eight values are not the same as in the hand-made table; the two methods use the numbers from the generator in different ways. The shape of the distribution is the same, though. You will see the bell shape from lesson 26 here too.
There is a common misunderstanding here: "A 5% store sees exactly 44 returns in 885 orders." No: 44 is only the middle of the distribution. A store whose true rate is exactly 5% can see 38 or 52; these are ordinary results. Now draw the null distribution yourself. ax.axvline (you used it in lesson 25) draws a red vertical line at the place of the observed 64:
Try it now· not graded; doesn't affect progress
The red line is at the right end of the histogram, where the bars almost end. To turn this into a number, we ask: how many of the 10,000 results in the null distribution are equal to or more extreme than the observed 64? Because H₁ says "the rate is greater than 5%", "more extreme" here means "more returns", that is, the right tail of the histogram. We call this the share of results as extreme as the observed one: the proportion of results in the null distribution that are equal to or more extreme than the observed value. If it is small, the data does not fit H₀. In lesson 28 you will learn the well-known name of this number.
import numpy as np rng = np.random.default_rng(42) simulated = rng.binomial(885, 0.05, size=10_000) observed = 64 extreme = simulated >= observed print("64 or more:", extreme.sum(), "trials") print("Share:", extreme.mean())
Output64 or more: 16 trials
Share: 0.0016In only 16 of the 10,000 parallel periods did the 5% store see 64 or more returns: the share is 0.0016. simulated >= observed is the same pattern as "at least k" in lesson 23: it gives True/False for every trial, and its mean is the share of True values. The logistics manager's sentence "a 5% store can also see 64 returns in some six-month periods" is technically true, but the word "some" means 16 in 10,000. Chance can produce this result; it produces it very rarely.
How does the share change when the observed value changes? Below, change the observed number of returns on the same null distribution. For each value, picture where the red line moves in the histogram:
The null distribution stays the same (true rate 5%, 885 orders, 10,000 simulations). How does the share of "as many or more than observed" change when the observed number of returns changes?
Pick a value; predict the output first, then look.
1import numpy as np2observed = 643rng = np.random.default_rng(42)4simulated = rng.binomial(885, 0.05, size=10_000)5share = (simulated >= observed).mean()6print("Observed:", observed, "returns")7print("Share of results as extreme as observed:", share)
Observed: 64 returns Share of results as extreme as observed: 0.0016
Faded lines didn't run with this value. 50 returns (5.6%) is seen in a 5% store in one of every five periods: not surprising. At 55 returns the share falls to 0.06; at 64 it is 0.0016, and at 70 it is 2 in 10,000. As the observed value moves to the right, the tail gets thinner and the share gets small quickly.
Now let's ask the same question for desktop. 369 orders, 23 returns. H₀ is the same again: the true rate is 0.05. Only the number of trials and the observed value change:
import numpy as np rng = np.random.default_rng(42) simulated_desktop = rng.binomial(369, 0.05, size=10_000) print("Mean:", simulated_desktop.mean()) print("Share of 23 or more:", (simulated_desktop >= 23).mean())
OutputMean: 18.4165
Share of 23 or more: 0.1631A 5% store sees 18.4 returns on average in 369 orders, and in 16% of the periods it sees 23 or more returns: roughly one period in six. The 6.2% of desktop is a result that chance produces often. So the answer to the first prediction question turned into numbers: for all orders the share is 0.0016, for desktop it is 0.16. Does this mean that the true rate of desktop is really 5%?
For desktop the share is 0.16. Which conclusion is correct?
One last misunderstanding about simulation: "The result changes a little with every seed and every number of trials, so no decision can be made." Let's run the same code with three different numbers of trials:
import numpy as np for trials in [1_000, 10_000, 100_000]: rng = np.random.default_rng(42) simulated = rng.binomial(885, 0.05, size=trials) print(trials, (simulated >= 64).mean())
Output1000 0.001
10000 0.0016
100000 0.00248The share moves between 0.001, 0.0016, and 0.0025. Even though the third decimal changes, all three say the same thing: "a few in a thousand, very rare". If the decision is not at a limit that would change when the second decimal of the share changes, the noise of the simulation does not change the result. If the share goes back and forth between 0.04 and 0.06, you increase the number of trials; the law of large numbers from lesson 23 works here too. In this lesson we use 10,000 trials in the explanation and 5,000 in the exercises so that the browser is not strained.
The share is calculated; now we need to turn it into a correct sentence. The correct pattern is this: "If the true rate were 5%, the share of seeing 64 or more returns in 885 orders would be about 0.0016." The sentence starts with "if", because the whole simulation was built by assuming H₀ is true. This number tells how surprising the data is under H₀.
Reversing this pattern is the most common mistake: "The probability that the 5% claim is true is 0.0016." This sentence is wrong. The simulation did not answer "is H₀ true?"; it answered "how often does this data appear if H₀ is true?" These are not the same thing: "the probability that the street is wet if it is raining" and "the probability that it has rained if the street is wet" are different numbers (conditional probability in lesson 24). In lesson 28 we will go through these wrong readings one by one; for now, memorize the correct pattern and use it in every report.
The whole method has five steps. Put the lines in the right order:
Put the five steps of testing a claim with a simulation in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The same method works for every rate claim, not only returns. A basketball player says "I make 70% of my free throws." His coach watches 20 of his throws in one practice, and the player makes 10 (50%). This time the claim we look for evidence for is that the player is worse than he says: H₀: p = 0.7; H₁: p < 0.7. The direction changed, so "more extreme" now means "fewer hits", and the tail is on the left: simulated <= 10.
import numpy as np rng = np.random.default_rng(42) simulated = rng.binomial(20, 0.7, size=10_000) print("Mean hits:", simulated.mean()) print("Share of 10 or fewer:", (simulated <= 10).mean())
OutputMean hits: 14.0145
Share of 10 or fewer: 0.0483A player who is truly a 70% shooter makes 14 hits on average in 20 throws; he sees 10 or fewer hits in about 5% of practices. The correct sentence: "If the player were truly a 70% shooter, the share of seeing 10 or fewer hits in 20 throws would be about 0.048." This number is much larger than Bazaar's 0.0016. It is surprising, but it is a result that could be seen once in twenty practices. What would you do if you were the coach?
The coach saw the simulation: a player who is truly a 70% shooter sees 10 or fewer hits in 20 throws in about 5% of practices. He asks for your decision.
Pick an option and see what happens. There are no points; you can try the other options too.
There is an important detail here: we chose the direction before looking at the data, according to the question. The coach wondered "is the player worse than he says?", so we looked at the left tail. At Bazaar, management wondered "is the return rate above the target?", so we looked at the right tail. H₁ decides the tail.
In this lesson you learned to calculate the share and to put it into the correct sentence. But there is still an open question: is 0.048 "small"? 0.0016 is small, and 0.16 is not; who decides the limit between them, and how? That is the topic of the next lesson.
When we split the orders by carrier, we can ask the same question. Is the return rate for orders shipped with Arrow Express consistent with the 5% claim? We calculate the number of orders and the observed returns from the data; we do not write them as fixed numbers:
import pandas as pd import numpy as np orders = pd.read_csv("orders.csv") arrow = orders[orders["carrier"] == "Arrow Express"] n = len(arrow) observed = (arrow["status"] == "returned").sum() rng = np.random.default_rng(42) simulated = rng.binomial(n, 0.05, size=10_000) print("Arrow Express:", n, "orders,", observed, "returns") print("Share:", (simulated >= observed).mean())
OutputArrow Express: 350 orders, 29 returns
Share: 0.0067If the true return rate for Arrow Express orders were 5%, the share of seeing 29 or more returns in 350 orders would be about 0.007: the data does not fit the 5% claim. This result does not say that the carrier is the cause of the returns; the claim types from lesson 3 apply here too. Maybe Arrow Express carries more Clothing parcels.
You think a friend's coin is rigged toward heads: 60 heads came up in 100 flips. H₀: the probability of heads is 0.5; H₁: greater than 0.5.
import numpy np
rng = np.random.default_rng(42)
simulated = rng.binomial(100, 0.5, size=10_000)
(, (simulated >= 60).mean())
(, (simulated >= 55).mean())Counting the tail from the wrong side. H₁ says "the rate is greater than 5%", but the analyst counts the results "less than or equal to the observed one":
import numpy as np rng = np.random.default_rng(42) simulated = rng.binomial(885, 0.05, size=10_000) print("Share:", (simulated <= 64).mean())
OutputShare: 0.99890.9989 means "almost all results are below 64"; so it tells in reverse how extraordinary the observed value is. Because the code gives no error, the mistake is not noticed, and the analyst reaches the exact opposite conclusion: "the share is very large, so the data fits 5%". The correct way is to count the tail in the direction of H₁: simulated >= 64 for "greater than" (share 0.0016), and simulated <= observed for "less than".
rng.binomial(885, 0.05, size=10_000)); if the observed value is in the middle of this distribution, chance produces it easily, and if it is at the end, chance produces it rarely.(simulated >= 64).mean() = 0.0016) and is reported in the pattern "if H₀ were true, the share of seeing a result this extreme would be ..."; a small share says the data and H₀ do not fit, and a large share does not prove H₀.Next lesson: You will learn when a share counts as "small", the language of the decision, and the most common ways this number is misread.
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.
| 24–27 |
|---|
| 30 |
| 28–31 | 163 |
|---|
| 32–35 | 640 |
|---|
| 36–39 | 1515 |
|---|
| 40–43 | 2275 |
|---|
| 44–47 | 2334 |
|---|
| 48–51 | 1726 |
|---|
| 52–55 | 866 |
|---|
| 56–59 | 323 |
|---|
| 60–63 | 108 |
|---|
| 64–67 | 9 |
|---|
| 68–71 | 7 |
|---|
Output60 or more heads: 0.0297
55 or more heads: 0.1803If the coin were fair, the share of seeing 60 or more heads in 100 flips would be about 0.03; 55 or more heads would be seen once in every five trials. 60 heads puts the fairness of the coin under real pressure; 55 heads does not.