Sub topic 7
Choosing and running a hypothesis test
This chapter assumes you can read a boxplot, know the mean and standard deviation, and have already written your suspected cause as a testable prediction. It also assumes you have checked the measurement system and stratified the data. Here you pick a statistical test that matches your data and run it in Python. The next chapter covers p-values and error risk in more detail.
What a hypothesis test does
A hypothesis test asks one question: if the suspected cause had no effect, how surprising would the data be?
- The null hypothesis (H0) says the cause has no effect. For example, "mean cycle time is the same under both setups."
- The alternative hypothesis (H1) says it does. For example, "mean cycle time differs between the setups."
- The p-value is the probability of seeing a difference at least as large as yours if H0 were true.
- The significance level (alpha) is the cutoff you set before looking at the data. A common choice is 0.05.
If p is below alpha, you reject H0. The data are then hard to explain by chance alone. If p is above alpha, you fail to reject H0. That means you found no evidence of an effect. It does not prove the cause is innocent.
Step 1: Classify your Y and your X
The right test depends on two things: the type of your output (Y) and the type of your suspected cause (X).
- Continuous Y is a measurement such as cycle time, weight, or temperature. You compare means or spreads.
- Discrete Y is a count or a yes/no result, such as defective or good. You compare proportions or counts.
- X with two groups is something like old setup versus new setup.
- X with three or more groups is something like machines 1, 2 and 3.
| Y (output) | X (suspected cause) | Typical test | Python function |
|---|---|---|---|
| Continuous | 2 groups | Welch two-sample t-test | `stats.ttest_ind(a, b, equal_var=False)` |
| Continuous | 3 or more groups | One-way ANOVA | `stats.f_oneway(a, b, c)` |
| Continuous | 2 groups, skewed data or outliers | Mann-Whitney U | `stats.mannwhitneyu(a, b)` |
| Discrete (defect or not) | 2 or more groups | Chi-square test of independence | `stats.chi2_contingency(table)` |
| Continuous | Continuous | Correlation or regression (later chapter) | `stats.linregress(x, y)` |
Step 2: Check the assumptions
Every test assumes something about the data. A test run on data that breaks its assumptions can give a misleading p-value.
- Independence. Each observation must not influence another. Ten readings from the same part are not ten independent parts. Time-ordered process data often has autocorrelation, where one reading predicts the next. Check a run chart before you test.
- Rough normality for t-tests and ANOVA. The tests work on means, so moderate departures from normal are tolerable with 20 or more points per group. Heavy skew, outliers, or very small samples are the problems. Look at a histogram or boxplot first.
- Spread. Standard t-tests assume equal variances. Welch's version does not, so use it by default.
- Expected counts for chi-square. The test needs expected counts of about 5 or more in every cell. With fewer, use Fisher's exact test (
stats.fisher_exact) for a 2x2 table.
Step 3: Compare two means with a Welch t-test
Suppose you suspect a new setup raised the cycle time. The prediction is that mean cycle time is higher under the suspected setup. You collected eight units under each setup.
import numpy as np
from scipy import stats
# Cycle times in minutes, collected under the old and the suspected setup
setup_old = np.array([12.1, 11.8, 12.4, 12.0, 12.6, 11.9, 12.3, 12.2])
setup_suspect = np.array([13.0, 12.8, 13.4, 12.9, 13.1, 13.5, 12.7, 13.2])
# Welch's t-test does not assume equal variances in the two groups
result = stats.ttest_ind(setup_old, setup_suspect, equal_var=False)
print(f"t = {result.statistic:.2f}, p = {result.pvalue:.4f}")
alpha = 0.05
if result.pvalue < alpha:
print("Evidence that mean cycle time differs between the setups.")
else:
print("No evidence of a difference in mean cycle time.")The means are about 12.16 and 13.08 minutes. The p-value comes out far below 0.05, so you reject H0. The t statistic is negative because the first group has the lower mean. Its sign tells you the direction, and its size tells you how many standard errors apart the means are.
Report the size of the difference as well as the p-value. Here it is about 0.9 minutes. A p-value says only that a difference is unlikely to be chance. It does not say the difference is large enough to matter for your Y. If your customer requirement is a 5-minute change, 0.9 minutes may not explain the problem.
Step 4: Compare three or more means with ANOVA
If the suspected cause has three or more levels, such as three machines, running several t-tests inflates your false-alarm risk. With three pairwise tests at alpha 0.05 each, the chance of at least one false positive is about 14%. One-way ANOVA tests all groups at once. Its H0 is that all group means are equal.
from scipy import stats
machine_1 = [12.1, 11.8, 12.4, 12.0, 12.6, 11.9]
machine_2 = [12.3, 12.2, 12.5, 12.0, 12.4, 12.1]
machine_3 = [13.0, 12.8, 13.4, 12.9, 13.1, 13.5]
f_result = stats.f_oneway(machine_1, machine_2, machine_3)
print(f"F = {f_result.statistic:.2f}, p = {f_result.pvalue:.4f}")
# If ANOVA rejects H0, a post-hoc test shows which machines differ
if f_result.pvalue < 0.05:
tukey = stats.tukey_hsd(machine_1, machine_2, machine_3)
print(tukey)ANOVA only tells you that at least one mean differs. The Tukey post-hoc test then compares each pair while controlling the overall error rate. Here it should single out machine 3. stats.tukey_hsd needs SciPy 1.8 or later.
Step 5: Compare defect rates with chi-square
When Y is defective or good, you compare counts, not means. The prediction might be that shift B produces a higher defect proportion than shift A. The data go into a contingency table, which is a grid of counts with one row per group and one column per outcome.
import numpy as np
from scipy import stats
# Rows: shift A, shift B. Columns: defective units, good units
table = np.array([
[18, 182],
[41, 159],
])
chi2, p, dof, expected = stats.chi2_contingency(table)
print(f"chi2 = {chi2:.2f}, dof = {dof}, p = {p:.4f}")
print("Expected counts if shift had no effect:")
print(expected)The observed defect rates are 9% for shift A (18 of 200) and 20.5% for shift B (41 of 200). If shift had no effect, the table would show about 29.5 defects in each shift, and that is what expected prints. The test measures how far the observed table is from that one. The statistic comes out near 9.6 and the p-value near 0.002, so you reject H0.
For a 2x2 table, SciPy applies a continuity correction by default. It makes the test slightly more cautious. You can leave it on.
Always read the table next to the p-value. Compare the observed counts with the expected ones to see where the gap is. Here shift B has more defects than expected and shift A has fewer.
Step 6: Choose a non-parametric test when the data are not well behaved
Cycle times, repair times, and waiting times are often right-skewed. A few very long values pull the mean up and break the normality assumption. The Mann-Whitney U test compares two groups without assuming a normal shape. It works on the ranks of the values instead of the values themselves.
import numpy as np
from scipy import stats
# Repair times in minutes: skewed, with one long outlier in each group
before = np.array([14, 15, 13, 16, 14, 15, 48, 14])
after = np.array([19, 21, 18, 22, 20, 55, 19, 21])
u = stats.mannwhitneyu(before, after, alternative="two-sided")
print(f"U = {u.statistic:.1f}, p = {u.pvalue:.4f}")The trade-off is a small loss of power when the data really are normal. When in doubt about normality and the sample is small, Mann-Whitney is a safe choice.
Common errors
- Choosing the test after seeing the result. Fix the test, alpha, and direction of the prediction before you look at the data. Trying several tests and reporting the one that "worked" invites false positives.
- Using a paired design as if it were two independent groups. If you measured the same units before and after a change, use a paired test (
stats.ttest_rel). Treating them as independent wastes information. - Treating "not significant" as "no effect". With small samples, a real difference can go undetected. The sample size chapter covers this.
- Mistaking statistical significance for practical importance. With thousands of records, a trivial difference can give a tiny p-value. Check the size of the difference against what matters to the process.
- Testing non-independent data. Repeated readings from one part or one setup run count as one piece of evidence, not many.
Putting it together
- State H0 and H1 from your prediction.
- Classify Y and X, then choose the test from the table.
- Check independence, normality or counts, and spread.
- Run the test and record the statistic, the p-value, and the size of the difference.
- Compare the p-value with the alpha you set in advance.
- Look at the data again, using the boxplot or the expected counts, to confirm the result matches what you see.
A rejected H0 shows that the groups differ. It does not yet show that your suspected cause produced the difference. Later chapters cover that step.
Exercise
You compare the defect rate across three production lines. Line 1 has 12 defects in 300 units, line 2 has 15 in 300, and line 3 has 33 in 300. Which test do you choose, what is the null hypothesis, and what should you do before trusting the result?
Show answer
Y is a defect count, so use a chi-square test of independence on a 3x2 table (defective and good counts per line). H0 says the defect proportion is the same on all three lines. Before trusting it, check that every expected count is at least about 5 (here the expected defects are about 20 per line, so this holds) and that the units are independent observations. If the test rejects H0, compare observed and expected counts to see which line differs. Here line 3 has far more defects than expected.
Exercise
A colleague runs a Welch t-test on 40 cycle times from machine A and 40 from machine B and gets p = 0.03 with alpha set at 0.05. The mean difference is 0.02 minutes, and the customer tolerance is 2 minutes. What do you conclude?
Show answer
The difference is statistically significant, so you reject H0. It is not practically important: 0.02 minutes is tiny compared with a 2-minute tolerance, so it is very unlikely to explain the process problem. You would look for another cause.