…
…
Statistics and Data Analysis Fundamentals · Lesson 33 / 44 · Inference with formulas
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.
In the A/B experiment, the old checkout page (A) turned 13% of 500 visitors into buyers, and the new design (B) turned 8%. The product team has prepared a fix for the new design and wants to try it quickly with 100 people per group: "If no difference shows up, we will say the fix does not work." Is that sentence right, and if a difference does show up, how do we know it matters?
In the last six lessons you built all the tools for testing a claim: the null distribution, the p-value, the permutation test, the bootstrap interval, and the formula shortcuts for the same calculations. Every test ends with a decision: "reject H₀" or "fail to reject H₀". In this lesson we step back and look at that decision itself. Wherever a decision is made, it can be wrong. If you do not know how a test can be wrong, you cannot read its result correctly.
At the end of the lesson you will take this design table to the product team. The table asks: if the real effect of the fix were as big as the difference in lesson 29 (13% against 8%), how often would a test catch it, depending on the number of people per group?
| People per group | Probability of catching the difference (power) |
|---|---|
| 100 | 0.21 |
| 250 | 0.45 |
| 500 | 0.73 |
| 1,000 | 0.96 |
In this lesson you will:
Remember the court comparison from lesson 28. H₀ was the defendant's innocence, and the court rejected it only when the evidence was strong. A court can be wrong in two different ways: it can convict an innocent person, or it can let a guilty person go free. Both errors are bad, but they are not the same error, and there is no way to bring both to zero at once. If you raise the bar for evidence, you convict fewer innocent people but more guilty people go free. If you lower the bar, the opposite happens.
A statistical test can be wrong in the same two ways. If there is really no difference (H₀ is true) and the test says "there is a difference" and rejects H₀, this is called a Type I error: a false alarm. If there is really a difference (H₀ is false) and the test misses it and stays at "fail to reject", this is called a Type II error: a missed difference. You can see the four possible cases in one table:
| Really no difference (H₀ true) | Really a difference (H₀ false) | |
|---|---|---|
| Test: H₀ rejected ("there is a difference") | Type I error (false alarm) | Correct decision |
| Test: H₀ not rejected ("no evidence") | Correct decision | Type II error (missed difference) |
You never see the columns of this table: if you knew whether there was really a difference, you would not need a test. All you see is the row, which is the decision of the test. So the question is: in each column, how likely is the test to land in the wrong row?
You already know the probability of a Type I error: it is α. In lesson 28 you defined α as "the threshold chosen before the test". Now let's see its second meaning with a simulation. We will build a world where the two groups are really exactly the same: 10% of visitors buy in both A and B. An experiment like this is called an A/A test, because both groups really see the same page. In this world we will run a 500-person-per-group experiment 10,000 times, apply the two-proportion z-test from lesson 31 to each one, and count how many come out "significant".
For this we will write a function. power(pa, pb, n) takes the real proportions of the two groups and the group size. Inside, rng.binomial produces, for each of the 10,000 experiments, how many people bought in A and in B (as in lessons 23 and 25). The next three lines do for 10,000 tests at once what proportions_ztest from lesson 31 does for a single test: the pooled proportion of the two groups, the standard error of the difference, and z. stats.norm.sf (lesson 26) gives the area to the right of z; multiplying it by two gives the two-sided p-value. The last line counts how many of the p-values fall below α. alpha=0.05 and reps=10_000 in the parameter list are default values: if you do not write them when you call the function, these values are used.
import numpy as np from scipy import stats def power(pa, pb, n, alpha=0.05, reps=10_000): rng = np.random.default_rng(42) xa = rng.binomial(n, pa, size=reps) xb = rng.binomial(n, pb, size=reps) pooled = (xa + xb) / (2 * n) se = np.sqrt(pooled * (1 - pooled) * 2 / n) z = (xa - xb) / n / se p = 2 * stats.norm.sf(np.abs(z)) return (p < alpha).mean() for n in [100, 500, 1000]: print("n =", n, "| share of tests that came out significant:", power(0.10, 0.10, n))
Outputn = 100 | share of tests that came out significant: 0.0532
n = 500 | share of tests that came out significant: 0.049
n = 1000 | share of tests that came out significant: 0.0531Although the two groups were really the same, about 5% of the 10,000 tests still came out "significant". Whether the group size is 100 or 1,000, this share stays around α. This is the second meaning of α: the rate of coming out significant when there is no difference, which is the probability of a Type I error. Choosing α = 0.05 means "I accept giving a false alarm in about 5 of every 100 cases where there is no difference." A bigger sample does not lower this rate. The only way to lower it is to make α smaller.
Run the function yourself. First look at the A/A test, then change the proportions:
Try it now· not graded; doesn't affect progress
Match the four cases with their names:
The real situation and the decision of an A/B test are given below. Which result does each one match?
For each row, pick its match from the list, then check.
Now let's move to the other column of the table: there is really a difference. In the experiment in lesson 29, A's proportion was 13% and B's was 8%. Let's build a world where the real proportions are exactly these, and run 10,000 experiments with 500 people per group. How many of them catch the difference? We call the same function and only change the proportions:
import numpy as np from scipy import stats def power(pa, pb, n, alpha=0.05, reps=10_000): rng = np.random.default_rng(42) xa = rng.binomial(n, pa, size=reps) xb = rng.binomial(n, pb, size=reps) pooled = (xa + xb) / (2 * n) se = np.sqrt(pooled * (1 - pooled) * 2 / n) z = (xa - xb) / n / se p = 2 * stats.norm.sf(np.abs(z)) return (p < alpha).mean() g = power(0.13, 0.08, 500) print("Power:", g) print("Share of tests that missed the difference:", round(1 - g, 4))
OutputPower: 0.7292
Share of tests that missed the difference: 0.2708With a real difference of 5 points, about 73% of the 10,000 tests caught it and 27% missed it. This 73% is called the power of the test: the probability that the test finds a real difference significant. The share that missed it (27%) is the probability of a Type II error; together with power it always adds up to 1. So even if a real difference of this size exists, one in every four tests with 500 people per group stays at "no evidence".
Why? You know from lesson 25 that a sample proportion moves a little in every experiment. Even if the real difference is 5 points, in some experiments A comes out low by chance and B comes out high, and the observed difference shrinks to 2 points. A difference that small gets lost inside the null distribution. Three things decide power: how big the difference itself is (the effect size), how many people there are in each group (n), and how strict the threshold is (α). A big difference, a big n, and a looser α raise power.
The team wanted to run the test with 100 people per group. Before calculating, estimate:
With real proportions of 13% and 8%, power with 500 people per group is about 0.73. Roughly what would power be with 100 people per group?
Check your estimate; then set n to 50 and 2000 and see how power changes:
Try it now· not graded; doesn't affect progress
Let's try the same difference with different group sizes. This code produces the table from the start of the lesson:
import numpy as np from scipy import stats def power(pa, pb, n, alpha=0.05, reps=10_000): rng = np.random.default_rng(42) xa = rng.binomial(n, pa, size=reps) xb = rng.binomial(n, pb, size=reps) pooled = (xa + xb) / (2 * n) se = np.sqrt(pooled * (1 - pooled) * 2 / n) z = (xa - xb) / n / se p = 2 * stats.norm.sf(np.abs(z)) return (p < alpha).mean() for n in [100, 250, 500, 1000]: print("People per group", n, "| power:", power(0.13, 0.08, n))
OutputPeople per group 100 | power: 0.2101
People per group 250 | power: 0.4505
People per group 500 | power: 0.7292
People per group 1000 | power: 0.9571With 100 people per group, power is only 0.21; with 1,000 it is 0.96. The real difference is the same; only the strength of the flashlight changes. Now we can go back to the sentence in the case. The team said, "If no difference shows up with 100 people per group, we will say the fix does not work." But even if the fix really creates a difference of 5 points, a test with 100 people per group catches it in only one of every five tries. In this situation, the result "no difference showed up" often does not mean "the fix does not work". It only means "the test was small". The rule from lesson 28 becomes concrete here: failing to reject does not mean proven, and when power is low it says almost nothing.
This is why a test is designed before the data is collected. The answer to "how many people should we test?" comes from choosing the smallest difference you want to catch and the power you accept (often 80%). According to the table, to catch a difference like 13% against 8% with at least 80% probability, 500 people are not enough; 1,000 are enough. Change the group size and read the sentence "how many of every 10 tests catch it":
The real proportions are 13% and 8%. Change the number of people per group: how often does the test catch this difference?
Pick a value; predict the output first, then look.
1n = 1002# Precomputed power (10,000 simulations, seed 42; real proportions 13% and 8%)3power_table = {100: 0.2101, 250: 0.4505, 500: 0.7292, 1000: 0.9571}4g = power_table[n]5print("People per group", n, "| power:", g)6print("About", round(g * 10), "of every 10 tests catch the difference.")7if g >= 0.8:8 print("Power is above 80%: if no difference shows up, that tells you something.")9else:10 print("Power is below 80%: if no difference shows up, you cannot say 'no effect'.")
People per group 100 | power: 0.2101 About 2 of every 10 tests catch the difference. Power is below 80%: if no difference shows up, you cannot say 'no effect'.
Faded lines didn't run with this value. The real difference never changes; only the group size changes. With 100 people the test catches the difference about once in five tries, with 1,000 people almost every time. When power is low, the result "no difference showed up" carries little information.
Suppose the team ran the test with 100 people per group. The result is in; now comes the decision:
The product team tried the fix with 100 people per group. The purchase rate is a little higher on the page with the fix, but the two-proportion z-test gave p = 0.5. The team lead wants a decision sentence from you.
Pick an option and see what happens. There are no points; you can try the other options too.
Power has another side. If the sample is very large, the test catches even very small differences. This sounds good, but the word "significant" sets a trap. Let's test the same 1-point difference (13% against 12%) at three different group sizes with proportions_ztest from lesson 31:
from statsmodels.stats.proportion import proportions_ztest for n in [500, 5_000, 50_000]: bought_a = round(0.13 * n) bought_b = round(0.12 * n) z, p = proportions_ztest([bought_a, bought_b], [n, n]) print("n =", n, "| difference 1 point | p =", round(p, 6))
Outputn = 500 | difference 1 point | p = 0.632585
n = 5000 | difference 1 point | p = 0.13057
n = 50000 | difference 1 point | p = 2e-06The difference is the same in every row: 1 point. But the p-value falls from 0.63 to 0.000002. In the test with 50,000 people per group the result is "highly significant"; does that mean 1 point is big or important? No. The p-value does not measure the size of the difference. It measures how clearly it is seen. As the flashlight gets stronger, even a small speck of dust is seen clearly; the speck does not get bigger because of that.
Let's also see the opposite. A 5-point difference (13% against 8%) gives p = 0.50 with 50 people per group and p = 0.0099 with 500 people per group. A big effect can come out "not significant" in a small sample, and a small effect can come out "highly significant" in a big sample. So you cannot say anything about the size of an effect by looking at the p-value. You have to look at the difference itself. The difference itself (points, dollars, days), or the difference divided by the spread, is called the effect size.
A good report therefore answers three questions separately:
| Question | What to look at | A/B experiment (500 people per group) |
|---|---|---|
| Is there a difference? | p-value | p = 0.0099; hard to explain by chance |
| How big? | The difference and its confidence interval | 5 points (interval 1.2 to 8.8 points) |
| Does it matter? | The measure of the work: money, time, customers | About 500 sales of difference per 10,000 visitors a month |
Statistics cannot answer the third question. A 1-point increase can mean a lot of money on a site with millions of visitors; for a change that is expensive to apply, it can be unimportant. Statistics answers the first two questions; the third is a decision for a person who knows the work.
Try it yourself: first run the 1-point difference for the different values of n, then change pb to 0.08 to raise the difference to 5 points:
Try it now· not graded; doesn't affect progress
There are two results: (1) In a test with 50,000 people per group, a 1-point difference, p = 0.000002. (2) In a test with 500 people per group, a 5-point difference, p = 0.0099. Which one points to a bigger effect for the business?
For proportions, the difference is easy to read as "points". For means, the unit is sometimes meaningless: on a satisfaction scale, is 0.53 points big or small? If we compare it with the spread, we get a measure. Cohen's d divides the difference of two means by the common (pooled) standard deviation of the two groups: d = difference / pooled standard deviation. It is similar to the z-score in lesson 16: it tells you the difference as "how many standard deviations".
In lesson 32 you saw that the satisfaction of Arrow Express customers was 0.53 points higher than Caravan Freight's, and that the difference was highly significant (Welch p = 0.000015). Now let's ask how big this difference is. The pooled standard deviation is the square root of the average of the two groups' variances weighted by group size (the idea of the weighted mean from lesson 13):
import pandas as pd import numpy as np survey = pd.read_csv("survey.csv") arrow = survey.loc[survey["carrier"] == "Arrow Express", "satisfaction"] caravan = survey.loc[survey["carrier"] == "Caravan Freight", "satisfaction"] diff = arrow.mean() - caravan.mean() pooled_var = ((len(arrow) - 1) * arrow.var() + (len(caravan) - 1) * caravan.var()) / (len(arrow) + len(caravan) - 2) pooled_sd = np.sqrt(pooled_var) print("Difference:", round(diff, 2)) print("Pooled standard deviation:", round(pooled_sd, 3)) print("Cohen's d:", round(diff / pooled_sd, 2))
OutputDifference: 0.53
Pooled standard deviation: 0.821
Cohen's d: 0.65d = 0.65: between the means of the two groups there are about two thirds of a standard deviation. This means the two distributions are clearly shifted; even if individual customers still overlap a lot, the typical Arrow Express customer is noticeably more satisfied than the typical Caravan Freight customer. Follow the calculation step by step; then make Caravan Freight's standard deviation bigger and see how d gets smaller:
Run the code line by line: see which line runs next, the variable boxes and the output.
n_a = 130 sd_a = 0.798 n_c = 80 sd_c = 0.856 diff = 4.19 - 3.66 pooled_var = ((n_a - 1) * sd_a ** 2 + (n_c - 1) * sd_c ** 2) / (n_a + n_c - 2) pooled_sd = pooled_var ** 0.5 d = diff / pooled_sd print("Pooled sd:", round(pooled_sd, 3)) print("Cohen's d:", round(d, 2))
A rough scale is often used to interpret the result: d ≈ 0.2 small, 0.5 medium, 0.8 large. Think of this scale as a dictionary, not as a rule. The same 0.2 can be very big for the side effect of a drug and unimportant for the color of a web page. The difference between Gull Post and Caravan Freight is 0.13 points; d ≈ 0.16, which is small. In lesson 32 this difference also did not come out significant (Example 6 below).
There is a similar measure for proportions (Cohen's h); you will see it in the Advanced section. But in most business reports the clearest effect size is the difference in its own unit: "5 points", "0.53 satisfaction points", "1.6 days". Cohen's d is used to compare results with different units, or to answer "is this difference big?" using the spread.
So far we have always taken α as 0.05. But the costs of the two error types are often not equal, and choosing α is really a way of weighing these costs. Here is an example from outside Bazaar: a health screening. In a screening test, H₀ is "the person is healthy". A Type I error means telling a healthy person "a disease is suspected": the person worries for no reason and goes to an extra exam. A Type II error means telling a sick person "you are healthy": the chance of catching the disease early is lost. In the screening of a serious disease, a Type II error costs much more. This is why screening tests are set to be sensitive on purpose: they accept more false alarms to reduce missed diagnoses. The false alarms are then filtered out with a second, more precise test.
In a court, the opposite holds. H₀ is "the defendant is innocent", and convicting an innocent person (a Type I error) is the error society most wants to avoid. So the threshold is kept very high ("beyond a reasonable doubt"), and the cost of this is that some guilty people go free. The same question is asked in product experiments: what costs more, releasing a wrong change (Type I) or shelving a good one (Type II)? For a change that is hard and expensive to undo, α is chosen small; for a cheap trial that can be undone, raising power is more important.
Match which error costs more in each situation:
In every situation, H₀ is "no problem / innocent / normal". Which error type costs more?
For each row, pick its match from the list, then check.
Calculating power with a simulation works in every case, but each time it needs thousands of generated experiments. For proportions and means, there is a formula shortcut; the statsmodels library offers it ready-made. First you turn the difference into an effect size: for proportions this is Cohen's h (proportion_effectsize). Then the NormalIndPower tool does two jobs: it calculates the group size needed for a wanted power (solve_power), or the power at a given group size (power).
import numpy as np from statsmodels.stats.proportion import proportion_effectsize from statsmodels.stats.power import NormalIndPower h = proportion_effectsize(0.13, 0.08) analysis = NormalIndPower() required = analysis.solve_power(h, alpha=0.05, power=0.8) print("Effect size h:", round(h, 3)) print("Per group for 80% power:", int(np.ceil(required)), "people") print("Power with 500 people:", round(analysis.power(h, nobs1=500, alpha=0.05), 3))
OutputEffect size h: 0.164
Per group for 80% power: 583 people
Power with 500 people: 0.738The formula gives 0.738 for 500 people; the simulation found 0.729. Both answer the same question and give close results. For 80% power you need 583 people per group, which also fills the gap between 500 and 1,000 in the table.
There is a trap here. A power calculation is done before collecting data, and the difference you put into it is the smallest difference worth catching for the business ("an increase of at least 3 points is worth this change"). After the test is over, putting the observed difference into the formula and saying "the power of the test was 30%" gives no new information: this number is just another way of writing the p-value. For a test that came out non-significant, the power calculated with the observed difference always comes out low, and it says no more than "we could not have caught it anyway".
Now you can read a test result with three questions: is there a difference, how big, does it matter; and you know when "no difference showed up" says something and when it only shows a small test. So far you have always compared two groups. In the next lesson you will test whether two categorical variables, for example product category and order status, are related to each other.
You saw that the Arrow Express–Caravan Freight difference has d ≈ 0.65. Let's do the same calculation for Gull Post and Caravan Freight, and put the p-value of the Welch test from lesson 32 next to it.
import pandas as pd import numpy as np from scipy import stats survey = pd.read_csv("survey.csv") gull = survey.loc[survey["carrier"] == "Gull Post", "satisfaction"] caravan = survey.loc[survey["carrier"] == "Caravan Freight", "satisfaction"] diff = gull.mean() - caravan.mean() pooled_sd = np.sqrt(((len(gull) - 1) * gull.var() + (len(caravan) - 1) * caravan.var()) / (len(gull) + len(caravan) - 2)) p = stats.ttest_ind(gull, caravan, equal_var=False).pvalue print("Difference:", round(diff, 2), "| Cohen's d:", round(diff / pooled_sd, 2), "| Welch p:", round(p, 2))
OutputDifference: 0.13 | Cohen's d: 0.16 | Welch p: 0.31The difference is 0.13 points, d = 0.16 (small) and p = 0.31 (not significant). Two things must be said together here: there is no evidence that a difference exists, and even if there is one, the observed size is small. With groups of 90 and 80 people, the power to catch a difference of this size would also be low; saying "Gull Post and Caravan Freight are the same" would still be wrong.
"The test came out non-significant, so the fix has no effect." A non-significant result only says "this test could not show a difference"; if the power of the test is low, it often misses a real difference too. With 100 people per group, a real difference of 13% against 8% is caught in only about 21% of tests. The right sentence: "There is not enough evidence that a difference exists (p = 0.5); the power of this design is about 21%, so the result does not show that the fix does not work. It should be tried again with a bigger test."
Next lesson: You compared the proportions of two groups; now you will test with the chi-square test whether two categorical variables (for example product category and order status) are related.
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.
A school wants to try two exam preparation methods. With the old method the mean score is 70 and the standard deviation is 15; suppose the new method really gains 5 points (d = 5 / 15 ≈ 0.33). How many students per class are needed for the Welch test to catch this difference? In the simulation, each of the 10,000 experiments is one row; axis=1 applies the test to each row separately.
import numpy as np from scipy import stats rng = np.random.default_rng(42) for n in [20, 50, 100]: old = rng.normal(70, 15, size=(10_000, n)) new = rng.normal(75, 15, size=(10_000, n)) p = stats.ttest_ind(new, old, axis=1, equal_var=False).pvalue print("Students per class", n, "| power:", (p < 0.05).mean())
OutputStudents per class 20 | power: 0.1729
Students per class 50 | power: 0.3851
Students per class 100 | power: 0.6553With two classes of 20, power is only 0.17: even if the new method really gains 5 points, the experiment misses it most of the time. If the school says "we tried it in two classes, no difference showed up, the method does not work", it makes the same mistake as in the case. For 80% power, about 143 students are needed in each group (using the version of the calculation in the Advanced section for means).