…
…
Statistics and Data Analysis Fundamentals · Lesson 31 / 44 · Inference with formulas
PreviewIn this lesson you will
scipy / statsmodels calls, and explain through the standard error why the two sets of results are closebinomtest) or the Wilson interval when the condition does not holdYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
In the last four lessons you answered Bazaar's three questions with simulation: the 5% return-rate claim, the effect of the new checkout page on purchases, and the confidence interval for the return rate. Management liked the results but asks whether they must run 10,000 simulations every time or whether a ready-made formula exists. There is one, and in this lesson you will learn it, when you can trust it, and when you cannot.
At the end of the lesson you will fill in the table below. The left column has the numbers that simulation found in the last four lessons. You will find the middle column with one-line formula calls, and in the right column you will see the exact calculation, which makes no approximation at all:
| Question | Simulation (lessons 27–30) | Formula (this lesson) | Exact calculation |
|---|---|---|---|
| Is the return rate above 5%? (one-sided p) | 0.0016 (10,000 repeats) | 0.0012 | 0.0024 |
| Did the checkout page change purchases? (two-sided p) | 0.0135 (10,000 shuffles) | 0.0099 | |
| 95% interval for the return rate | 0.0554 to 0.0893 (bootstrap) | 0.0553 to 0.0894 |
The numbers are very close, but not the same. If you understand why they are close, you do not need to memorize the formula: the formula is a shortcut that predicts in advance what the simulation will do. If you understand why they are not identical, you will also know where the formula can go wrong.
In this lesson you will:
scipy and statsmodels.In lesson 29 you compared the return rates of mobile and desktop orders with a shuffle test. Let's ask the same question with the formula:
import pandas as pd from statsmodels.stats.proportion import proportions_ztest s = pd.read_csv("orders.csv") s["returned"] = s["status"] == "returned" g = s.groupby("device")["returned"].agg(["sum", "count"]) print(g) z, p = proportions_ztest([g.loc["mobile", "sum"], g.loc["desktop", "sum"]], [g.loc["mobile", "count"], g.loc["desktop", "count"]]) print("z =", round(z, 2), "| two-sided p =", round(p, 2))
Output sum count
device
desktop 23 369
mobile 41 516
z = 0.97 | two-sided p = 0.33The return rate is 7.9% on mobile and 6.2% on desktop. p = 0.33: if there were really no difference, a gap this big would appear in one comparison out of three. The right sentence is "there is not enough evidence of a difference in return rate between the two devices"; not "the two rates are equal". Because customers choose the device themselves, even if the difference were significant, the cause could not be tied to the device. In lesson 29 the shuffle test had made the same decision.
Giving proportions_ztest proportions instead of counts. The function wants the counts of successes and the group sizes; when you give it proportions, it runs without an error and returns a meaningless result:
from statsmodels.stats.proportion import proportions_ztest z, p = proportions_ztest([0.08, 0.13], [500, 500]) print("With proportions: p =", round(p, 4)) z, p = proportions_ztest([40, 65], [500, 500]) print("With counts: p =", round(p, 4))
OutputWith proportions: p = 0.9131
With counts: p = 0.0099In the first line the function thinks there are "0.08 successes" among 500 people; both rates look almost zero, and p = 0.91 comes out. The analyst reaches the opposite conclusion, "no difference". The correct way is to give the counts of successes (40 and 65); taking the counts from the data with agg(["sum", "count"]) prevents this mistake from the start.
stats.binomtest (exact p) and proportion_confint (estimate ± 1.96 × standard error), and for two proportions proportions_ztest and confint_proportions_2indep; at Bazaar the formula results are almost the same as simulation (return test 0.0012 / 0.0016, A/B 0.0099 / 0.0135, interval 0.0553–0.0894 / 0.0554–0.0893). When you compare two groups you build one interval for the difference; the overlap of two separate intervals is not a rule.binomtest for the test.Next lesson: you will build the same shortcut for means and see why estimating the spread from the data needs the t distribution.
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.
In lesson 27 you simulated a 5% store 10,000 times: each time 885 orders, and how many returns came in each. The histogram drew a bell around 44 returns, and its standard deviation was 6.5 returns. This width is not a coincidence. The standard error you met in lessons 25 and 26 is how much a statistic moves from sample to sample. For a proportion, this movement has a ready-made formula:
Standard error of a proportion = √(p × (1 − p) / n)
Here p is the proportion and n is the number of orders. For the 5% store, √(0.05 × 0.95 / 885) = 0.0073. So a store whose true rate is 5% will typically show a six-month return rate about 0.0073 above or below 0.05. Let's compare this with simulation. This time we divide the number of returns by the number of orders and work with proportions:
import math import numpy as np import pandas as pd s = pd.read_csv("orders.csv") returned = s["status"] == "returned" n = len(s) rng = np.random.default_rng(42) rates = rng.binomial(n, 0.05, size=10_000) / n print("Standard deviation of the simulated rates:", round(rates.std(), 4)) print("Formula √(0.05 × 0.95 / n):", round(math.sqrt(0.05 * 0.95 / n), 4)) print("Spread of one order's 'returned' column:", round(returned.std(), 4))
OutputStandard deviation of the simulated rates: 0.0073
Formula √(0.05 × 0.95 / n): 0.0073
Spread of one order's 'returned' column: 0.2592The first two lines are the same: the formula gave in one line the width that 10,000 simulations found. In lesson 27 you found 6.5 returns; 6.5 / 885 = 0.0073, the same number written as a proportion.
The third line shows an important confusion. The "returned" column of single orders (0 or 1) moves by 0.26: an order is either returned or not, so one order is very uncertain. The standard error of the rate is 0.0073: the proportion of 885 orders is much steadier than one order. Saying "the standard error is the standard deviation of the data" mixes up these two numbers. The difference comes from n: when the number of orders grows, the spread of the data stays the same (each order is still 0 or 1), but the standard error of the proportion gets smaller. Below, raise n from 885 to four times as much, 3540, and see what the two numbers do:
Try it now· not graded; doesn't affect progress
When n becomes four times larger, the standard error is cut in half, because n is inside the square root: √4 = 2. Keep this rule in mind; it will come back at the end of the lesson in a poll news story.
Now that we know the standard error, we can ask the question from lesson 27 without simulation: Bazaar's observed rate is 64 / 885 = 0.0723, and the claim is 0.05. The difference is 0.0223. Is this difference big? We cannot know from the number alone; we need to compare it with the typical movement of chance. Remember the z-score from lesson 16: (value − center) / spread. The same idea gets the name z statistic here:
z = (observed rate − claimed rate) / standard error = (0.0723 − 0.05) / 0.0073 = 3.05
The observed rate is 3.05 standard errors away from the claim. You know from lesson 26 that in a normal distribution about 99.7% of values stay within 3 standard deviations. In lesson 26 you also saw that the distribution of sample means is bell-shaped; a proportion is also a mean (the mean of 0s and 1s). So we can put a normal curve in the place of the null distribution and read the p-value from the tail area of that curve. Follow the code line by line, and watch the variable boxes at each line:
Run the code line by line: see which line runs next, the variable boxes and the output.
import math n = 885 returns = 64 p0 = 0.05 p_hat = returns / n se0 = math.sqrt(p0 * (1 - p0) / n) z = (p_hat - p0) / se0 # Area to the right of z on the normal curve (same number as stats.norm.sf(z)) p_value = 0.5 * math.erfc(z / math.sqrt(2)) print("Observed rate:", round(p_hat, 4)) print("Standard error:", round(se0, 4)) print("z =", round(z, 2)) print("One-sided p:", round(p_value, 4))
The lines are a shortened form of the five steps in lesson 27. H₀ is still "the true rate is 0.05" (p0). The null distribution is a normal curve instead of thousands of simulations: its center is p0, its width is se0. The place of the observed value is z. The p-value is the right tail of the curve. math.erfc in the last line is only there so the trace can run; in a real analysis you write stats.norm.sf(z), which you know from lesson 26, and it gives the same number. Before you see the result, make a prediction:
The observed rate is about 3 standard errors above the claim (z = 3.05) and H₁ is "the rate is above 5%". Around what value will the one-sided p-value be?
Now let's do the same calculation with real library calls. You know the line from scipy import stats from lesson 26. The new part is stats.binomtest: it calculates the exact p-value from the binomial distribution itself, without a normal approximation. The binomial (a fixed number of trials, the same probability in each) worked in simulation with rng.binomial in lesson 23; binomtest adds up the probabilities of the same model exactly, without generating any random numbers:
import math from scipy import stats n, returns, p0 = 885, 64, 0.05 p_hat = returns / n se0 = math.sqrt(p0 * (1 - p0) / n) z = (p_hat - p0) / se0 print("Observed rate:", round(p_hat, 4), "| standard error:", round(se0, 4)) print("z =", round(z, 2)) print("Formula p (normal curve):", round(stats.norm.sf(z), 4)) exact = stats.binomtest(returns, n, p0, alternative="greater") print("Exact p (binomtest):", round(exact.pvalue, 4))
OutputObserved rate: 0.0723 | standard error: 0.0073
z = 3.05
Formula p (normal curve): 0.0012
Exact p (binomtest): 0.0024binomtest takes four pieces of information: the number of successes (64), the number of trials (885), the rate in H₀ (0.05), and the direction of H₁. alternative="greater" means "greater than". As in lesson 28, the direction is chosen from the question, without looking at the data ("less" for "smaller than", "two-sided" for "different"). The result is an object; the p-value is in .pvalue.
Now look at the first row of the table: simulation 0.0016, formula 0.0012, exact calculation 0.0024. A common confusion is this: "The formula is more accurate than simulation; simulation is approximate." In fact, both are approximations. Simulation makes a finite number of random repeats; in lesson 27, when you raised the repeats to 100,000, you found 0.0025, and as the number of repeats grows, simulation gets close to the exact value (0.0024). The formula puts a smooth normal curve in the place of the binomial distribution; because the rate is close to 0, the true distribution is a little skewed to the right, and the curve estimates the right tail a little too thin. The exact one is binomtest. But all three numbers lead to the same decision: "a few in a thousand; the data do not fit the 5% claim." These differences do not matter unless the decision is near the boundary.
In lesson 30 the bootstrap interval for the return rate was 0.0554 to 0.0893. We can build the same interval with the formula. The rule from lesson 26 was: in a normal distribution, 95% of values are within about 2 standard deviations of the mean. The exact number is 1.96. So:
95% interval = observed rate ± 1.96 × standard error
This time we calculate the standard error with the observed rate: √(0.0723 × 0.9277 / 885) = 0.0087. In the test we used 0.05; in the interval we use 0.0723. Why? A test is a question that starts with "if H₀ were true"; we build the null distribution with the rate in H₀. Behind the interval there is no H₀; the best estimate we have is the observed rate. Saying "the same standard error is used for the test and the interval" misses this difference. The statsmodels library offers most statistical tests ready-made; proportion_confint gives the same interval in one line:
import math from statsmodels.stats.proportion import proportion_confint n, returns = 885, 64 p_hat = returns / n se = math.sqrt(p_hat * (1 - p_hat) / n) print("Return rate:", round(p_hat, 4), "| standard error:", round(se, 4)) print("By hand:", round(p_hat - 1.96 * se, 4), round(p_hat + 1.96 * se, 4)) low, high = proportion_confint(returns, n) print("statsmodels:", round(low, 4), round(high, 4))
OutputReturn rate: 0.0723 | standard error: 0.0087
By hand: 0.0553 0.0894
statsmodels: 0.0553 0.0894The formula gives 0.0553 to 0.0894 and the bootstrap gave 0.0554 to 0.0893: a difference in the fourth decimal place. Why so close? Because n is large (885) and the rate is far enough from 0; in this case the bootstrap distribution also draws an almost perfect bell, and the assumption of the formula holds. This interval is called the Wald interval; it is the default method of proportion_confint. 5% is outside the interval: the test had made the same decision. As you saw in lesson 30, the test and the interval look at the same data from two sides.
What decides the width of the interval? Keep the rate fixed and change the number of orders. The code keeps the observed rate at about 7.2% and sets the number of returns to match:
The return rate stays fixed at about 7.2%. How do the standard error and the 95% interval change when the number of orders (n) changes?
Pick a value; predict the output first, then look.
1import math2n = 8853returns = round(n * 0.0723)4p_hat = returns / n5se = math.sqrt(p_hat * (1 - p_hat) / n)6print(n, "orders,", returns, "returns | standard error:", round(se, 4))7print("95% interval:", round(p_hat - 1.96 * se, 4), round(p_hat + 1.96 * se, 4))
885 orders, 64 returns | standard error: 0.0087 95% interval: 0.0553 0.0894
Faded lines didn't run with this value. When n becomes four times larger (885 → 3540), the standard error is cut in half and the interval gets half as wide (from about ±0.017 to ±0.0085). With 100 orders the interval runs from 2% to 12%: 5% is inside, and so is 10%. An interval this wide says very little about the return rate.
In lesson 29, in the checkout page experiment, 65 of 500 visitors in group A (0.13) and 40 of 500 visitors in group B (0.08) made a purchase. The difference B − A = −0.05, and the shuffle test gave a two-sided p = 0.0135. In the formula the pattern is the same: z = (observed difference − difference in H₀) / standard error of the difference. Because H₀ says "no difference", the difference in H₀ is 0. The standard error of the difference combines the movement of the two groups. Under H₀ the rate of the two groups is the same, so this common rate is estimated by pooling the two groups: (65 + 40) / 1000 = 0.105. This is called the pooled proportion, and the standard error comes out as √(0.105 × 0.895 × (1/500 + 1/500)) = 0.0194. In lesson 29 the standard deviation of the shuffles was 0.0196: the same width again.
You do not need to do this calculation by hand. statsmodels has two functions: proportions_ztest runs the test, and confint_proportions_2indep builds an interval for the difference. Both want counts (the number of successes and the group size). The cell below counts the groups from the data and makes the two calls. First run it as it is, then change column to "added_to_cart":
Try it now· not graded; doesn't affect progress
For purchases the result is: z = −2.58, two-sided p = 0.0099, and the interval for the difference is −0.088 to −0.012. The shuffle in lesson 29 gave 0.0135, and the bootstrap interval in lesson 30 was also −0.088 to −0.012. For adding to cart, the difference of the same size gives p = 0.094; the shuffle in lesson 29 gave 0.106. The decisions overlap again: the difference in purchases is significant, and the one in adding to cart is not. The reason is the same as in lesson 29: the add-to-cart rate is around 30%, p × (1 − p) is larger there, so the standard error is larger too.
In proportions_ztest the order matters: the sign of z shows the direction of the first group minus the second. We wrote B first, so z is negative and the difference is B − A. For the two-sided p the order does not matter.
Let's stop here on one confusion. In some reports the intervals of the two groups are drawn separately and people say, "the intervals overlap, so there is no difference." Let's build two separate intervals for the purchase rates:
from statsmodels.stats.proportion import proportion_confint for name, successes in [("A", 65), ("B", 40)]: low, high = proportion_confint(successes, 500) print(name, round(successes / 500, 3), "interval:", round(low, 4), round(high, 4))
OutputA 0.13 interval: 0.1005 0.1595
B 0.08 interval: 0.0562 0.1038The lower end of A is 0.1005 and the upper end of B is 0.1038: the intervals overlap. Yet the difference test gave p = 0.0099 and the interval for the difference does not contain zero. There is no contradiction: the overlap of two separate intervals is not a decision rule for the difference. Having both rates at the extremes at the same time is much rarer than having one rate at its extreme; the standard error of the difference (0.0194) is smaller than the sum of the two separate standard errors (0.015 + 0.012 = 0.027).
The formula assumes that the distribution of sample proportions looks like a normal curve. This assumption does not always hold. If the rate is very close to 0 or 1 and n is small, the distribution piles up on one side and its tail stretches out on one side. The rough rule is this: n × p and n × (1 − p) should be at least 10, that is, both the number of successes and the number of failures should be at least 10. At Bazaar there are 885 × 0.0723 = 64 returns and 821 orders without a return: the condition holds easily.
Now a different case. Bazaar opened a new Beauty storefront; 3 of the first 20 orders were returned (0.15). Management wants an interval for this rate too:
import math from statsmodels.stats.proportion import proportion_confint n, returns = 20, 3 p_hat = returns / n print("n × p =", n * p_hat, "| n × (1 - p) =", n * (1 - p_hat)) se = math.sqrt(p_hat * (1 - p_hat) / n) print("Wald:", round(p_hat - 1.96 * se, 4), round(p_hat + 1.96 * se, 4)) low, high = proportion_confint(returns, n, method="wilson") print("Wilson:", round(low, 4), round(high, 4))
Outputn × p = 3.0 | n × (1 - p) = 17.0
Wald: -0.0065 0.3065
Wilson: 0.0524 0.3604The lower end of the formula interval is −0.0065: a negative return rate. This is an impossible number, and the clearest sign that the formula does not work here. The number of successes is 3, far below the 10 the condition asks for. In this case there are two tools. For the interval, the Wilson interval: it is still a formula, but it keeps the ends between 0 and 1 and behaves much better in small samples (method="wilson"). The result is 0.052 to 0.360: the rate can be 5% or 36%. For the test, binomtest: it does not use a normal approximation, so it does not need the condition. This is why "the formula works for every n" is wrong; checking the two products before you use the formula takes one second.
Match the right tool to the four cases:
Which tool fits each case?
For each row, pick its match from the list, then check.
An interval from the formula appears in the news every day, only under a different name. A mayoral election poll of 1,000 people was made in a city; the candidate has 52% of the votes. Under the news story, in small letters, it says "margin of error ± 3.1 points". Where does this number come from?
import math from scipy import stats from statsmodels.stats.proportion import proportion_confint n, yes = 1000, 520 p_hat = yes / n low, high = proportion_confint(yes, n) print("Vote share:", p_hat, "| 95% interval:", round(low, 3), round(high, 3)) print("Margin of error: ±", round(1.96 * math.sqrt(p_hat * (1 - p_hat) / n), 3)) z = (p_hat - 0.5) / math.sqrt(0.5 * 0.5 / n) print("'More than half' test: z =", round(z, 2), "| one-sided p =", round(stats.norm.sf(z), 3))
OutputVote share: 0.52 | 95% interval: 0.489 0.551
Margin of error: ± 0.031
'More than half' test: z = 1.26 | one-sided p = 0.103The "margin of error" is 1.96 × standard error itself: ± 3.1 points. The 95% interval is 48.9% to 55.1%; 50% is inside this interval. For the claim "the candidate has more than half the votes", the test says the same: z = 1.26, one-sided p = 0.103. If the true share were exactly 50%, in a poll of 1,000 people you would get 52% or more in about one poll out of ten. The condition holds (520 and 480, both well above 10), and the formula is reliable. The problem is not in the formula, it is in the headline:
The newspaper editor wants to run the headline "Candidate leads" on the poll result (1,000 people, candidate 52%, margin of error ± 3.1 points, 95% interval 48.9% to 55.1%). The editor asks the data team for an opinion.
Pick an option and see what happens. There are no points; you can try the other options too.
To cut the margin of error in half you need to make the sample four times larger, not twice; the square-root rule from section 1 works here too. This is one reason most national polls are made with 1,000 to 3,000 people: going from a margin of 3 points to 1.5 points costs four times as much.
The formula is a shortcut for simulation, if its condition holds. In this lesson you saw three tools for proportions: the z formula and binomtest for one proportion, proportion_confint for an interval (Wilson if the condition fails), and proportions_ztest and confint_proportions_2indep for two proportions. The same idea lies under all of them: the observed difference is measured in standard errors. One last check:
In a sample of 100 orders the return rate is 0.03 (3 returns). Can the formula interval (Wald) be used with confidence?
The same idea works for means: the standard error measures how much the mean moves. But there is a difference. For a proportion we could calculate the standard error from p; for a mean we also need to estimate the spread from the data, and this extra uncertainty needs a curve with slightly heavier tails than the normal curve, the t distribution. That is the topic of the next lesson.
A polling company wants to show a client how the margin of error changes with n. Let the rate stay around 52%:
import math for n in [1000, 4000, 16000]: margin = 1.96 * math.sqrt(0.52 * 0.48 / n) print(n, "people: ±", round(margin * 100, 2), "points")
Output1000 people: ± 3.1 points
4000 people: ± 1.55 points
16000 people: ± 0.77 pointsEvery four times more people cuts the margin of error in half. Even with 16,000 people the margin of error does not become zero; the standard error only approaches zero as n goes to infinity.