Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Section 3.3 — Introduction to hypothesis testing

This notebook contains the code examples from Section 3.3 Introduction to hypothesis testing of the No Bullshit Guide to Statistics.

I highly recommend that you use the notebook interactively. I’ve intentionally left empty code cells throughout the notebook, which you can use to try some commands on your own.

Notebook setup

Note: you may need to restart the kernel to use updated packages.
<Figure size 640x480 with 0 Axes>
datasets/ directory already exists.

\def\stderr#1{\mathbf{se}_{#1}} \def\stderrhat#1{\hat{\mathbf{se}}_{#1}} \def\Mean{\textbf{mean}} \def\Var{\textbf{var}} \def\Std{\textbf{std}} \def\Freq{\textbf{freq}} \def\RelFreq{\textbf{relfreq}} \def\CI#1{\textbf{CI}_{#1}} \def\CIL#1{\textbf{L}_{#1}} \def\CIU#1{\textbf{U}_{#1}} \def\ci#1{\textbf{ci}_{#1}} \def\cil#1{\textbf{l}_{#1}} \def\ciu#1{\textbf{u}_{#1}} \def\DMeans{\textbf{dmeans}} \def\Prop{\textbf{prop}} \def\DProps{\textbf{dprops}} \def\Err{ {\Large \varepsilon}} \def\calN{\mathcal{N}} \def\Tdist{\mathcal{T}} \def\Expon{\mathrm{Expon}}

(this cell contains the macro definitions like sex‾\stderr{\overline{\mathbf{x}}}, se^\stderrhat{}, mean\Mean, ...)

What is hypothesis testing?

  • An approach to formulating research questions as yes-no decisions and a procedure for making these decisions.

  • Hypothesis testing is a standardized procedure for doing statistical analysis (also uses stats jargon that makes everything look more convincing ;)

Definitions

Hypotheses

  • We formulate research question as two competing hypotheses:

    • Null hypothesis H0H_0 = no effect.

    • Alternative hypothesis HAH_A = an effect exists.

Test statistic

An estimator relevant for differentiating H0H_0 from HAH_A.

Sampling distribution of the test statistic under H0H_0

The p-value

The pp-value is the probability of observing statistic (or more extreme) under the null hypothesis.

0.6

The deviation from the parameter theta0 of 60% of the values in the list thetas0 are equal to or more extreme than the deviation of the observed test statistic θ^x=obs\hat{\theta}_{\mathbf{x}} = \tt{obs} form the parameter θ0=th0\theta_0 = \tt{th0}.

The logic of hypothesis testing

Overview of the hypothesis testing procedure

Here is the high-level overview of the hypothesis testing procedure:

  • inputs: sample statistics computed from the observed data

  • outputs: a decision that is one of: “reject the null hypothesis” or “fail to reject the null hypothesis”

hypothesis testing overview

In this notebook, we’ll use simulation to obtain the sampling distributions of the test statistic under the null hypothesis.

Court trial analogy

  • defendant innocent <-> null hypothesis

  • found guilty <-> reject null

  • acquitted <-> fail to reject the null

Interpreting the result of a hypothesis test

  • The implication of rejecting the null hypothesis is that there must be a difference between the population from which the sample was taken X∼N(μ,σ)X \sim \mathcal{N}(\mu,\sigma) and the theoretical model X0∼N(μX0,σX0)X_0 \sim \mathcal{N}(\mu_{X_0},\sigma_{X_0}).

    • Note that rejecting null hypothesis H0H_0 is not the same as “proving” the alternative hypothesis HAH_A is true; we have just shown that the data is unlikely to occur by chance under the null hypothesis.

    • Using statistics jargon, when we reject the hypothesis H0H_0 we say we’ve observed a “statistically significant” result, which sounds a lot more impressive than it actually is. The hypothesis testing procedure is just a simple check we perform to rule out the “occurred by chance” possibility.

  • The implication of failing to reject the null hypothesis is that the observed sample could have occurred by chance under H0H_0, so there is no need to search for an alternative hypothesis. Note that “failing to reject H0H_0” is not the same as “proving” the null hypothesis.

I know all this sounds super complicated and roundabout (an it is!), but you will get a hang of it with practice.

Effect size estimates

The effect size Δ\Delta measures the magnitude of the deviation of the observed statistic from the expected theoretical value. For example, in a test that compare the sample mean x‾\overline{\mathbf{x}} to a theoretical mean μX0\mu_{X_0}, we can use Δ=μ−μX0\Delta = \mu - \mu_{X_0} to measure the deviation of the unknown mean μ\mu from the theoretical mean μX0\mu_{X_0}. We can obtain an effect size estimate by computing Δ^=x‾−μX0\widehat{\Delta} = \overline{\mathbf{x}} - \mu_{X_0}.

Another way to report effect size is to construct a confidence interval, which takes into account the variability of the data. A confidence interval tells us a range of values where we believe the true value of Δ\Delta falls. The functions ci_mean and ci_var from the ministats module can help us with confidence interval calculations.

Simulation tests

Let’s start with a description of the problem. We want to compare a sample of observations from an unknown population to a fully specified theoretical model.

TODO: import from text

Test for the mean

We’ll now discuss hypothesis tests based on the sample mean. We’re interested in distinguishing between the competing hypotheses:

HA:μ≠μX0andH0:μ=μX0,H_A: \mu \neq \mu_{X_0} \qquad \text{and} \qquad H_0: \mu = \mu_{X_0},

where μ\mu is the mean of the unknown population X∼N(μ,σ)X \sim \mathcal{N}(\mu,\sigma) from which the sample x\mathbf{x} was taken, and μX0\mu_{X_0} is the mean of the theoretical model X0∼N(μX0,σX0)X_0 \sim \mathcal{N}(\mu_{X_0}, \sigma_{X_0}).

Kombucha bottling process

We’ll use the kombucha scenario for all the examples in this section. Recall, the probability distirbution of the kombucha volume is described by the theoretical model K0∼N(μK0=1000,σK0=10)K_0 \sim \mathcal{N}(\mu_{K_0} = 1000, \sigma_{K_0}=10) when the production line is working as expected.

Since μK0\mu_{K_0} and σK0\sigma_{K_0} are known, we can use simulation to obtain the sampling distribution of any test statistic.

Computer model for the kombucha volumes under H0H_0

Let’s look at a random sample of size n=40n=40 from the distribution under the null hypothesis.

array([1004.97, 998.62, 1006.48, 1015.23, 997.66, 997.66, 1015.79, 1007.67, 995.31, 1005.43, 995.37, 995.34, 1002.42, 980.87, 982.75, 994.38, 989.87, 1003.14, 990.92, 985.88, 1014.66, 997.74, 1000.68, 985.75, 994.56, 1001.11, 988.49, 1003.76, 993.99, 997.08, 993.98, 1018.52, 999.87, 989.42, 1008.23, 987.79, 1002.09, 980.4 , 986.72, 1001.97])

We can obtain the sampling distribution of the mean by repeatedly generating samples like this, and computing the mean from each of them.

Sampling distribution of the mean under the null

We can generate the sampling distribution of the mean K‾0\overline{\mathbf{K}}_0 by running a simulation using the helper function gen_sampling_dist. We supply three parameters for the simulation:

  1. the computer model under H0H_0

  2. the estimator function

  3. the sample size

In our case, 1. is rvK0, 2. is the function mean, and 3. n=40.

<Figure size 700x200 with 1 Axes>

The sampling distribution K‾0=kbars40\overline{\mathbf{K}}_0 = \tt{kbars40} tells us the variability of the sample means we can expect to observe when H0H_0 is true.

Example 1S: test for the mean of Batch 04

We want to check whether Batch~04 is “regular” or “irregular” by comparing the mean volume of this batch μ\mu to the mean of the theoretical model μK0=1000\mu_{K_0} = 1000;ml. We formulate the following competing hypotheses:

HA:μ≠μK0andH0:μ=μK0.H_A: \mu \neq \mu_{K_0} \qquad \text{and} \qquad H_0: \mu = \mu_{K_0}.

In words, the null hypothesis describes a regular batch, where the mean of the batch is equal to the mean of the model μK0=1000\mu_{K_0}=1000. The two-sided alternative hypothesis states that the mean volume of Batch~04 differs from the expected mean μK0\mu_{K_0}, and it includes both positive or negative deviations.

Let’s start by loading the sample k04\mathbf{k}_{04} from Batch 04 of the kombucha dataset.

40
1003.8335

The mean volume calculated from the sample ksample04 is 3.83 ml higher than the expected mean μK0=1000\mu_{K_0} = 1000 ml. Is this a big difference or not? How likely is such deviation to occur by chance under the null hypothesis?

Sampling distribution of the mean under the null hypothesis

To answer the above question, we need to know the sampling distribution of the mean for samples of size n=40n=40 under the null hypothesis H0H_0 (which we just learned how to do above).

Let’s run the simulation based on the using the function gen_sampling_dist with parameters:

  1. probability model rvK0 =K0∼N(μK0=1000,σK0=10)= K_0 \sim \mathcal{N}(\mu_{K_0}=1000,\sigma_{K_0}=10)

  2. the estimator function mean

  3. the sample size n = len(ksample04) = 40

To calculate the pp-value, we want to count how many values of sampling distribution kbars40 are equal or more extreme than the observed value k‾04=\overline{\mathbf{k}}_{04} = obsmean04 = 1003.8335.

In this context, “k‾04\overline{\mathbf{k}}_{04} or more extreme” means all values whose deviation from the mean μK0=1000\mu_{K_0} = 1000 is equal to or more extreme than the deviation of the observed mean k‾04\overline{\mathbf{k}}_{04} from μK0\mu_{K_0}.

Let’s start by computing the observed deviation ∣k‾04−μK0∣|\overline{\mathbf{k}}_{04} - \mu_{K_0}|.

3.833499999999958

Next we use the list-comprehension syntax to go through the list kbars40 and select only the values v whose absolute deviation from the mean abs(v-muK0) is equal to or greater than the observe deviation obsdev04.

[1004.786610717458, 995.7701787502498, 995.8232443556451]

The list tails contains the subset of the simulated means that satisfy the “k‾04\overline{\mathbf{k}}_{04} or more extreme” condition.

149

Out of the total of N=10000N=10000 simulated samples under H0H_0, only 149 satisfy this condition “k‾04\overline{\mathbf{k}}_{04} or more extreme.” That’s not a lot!

The pp-value is computed as he number of observations in the tails, divided by the total number of simulated observations.

TODO: mention proportion

0.0149

We can visualize the pp-value calculation by plotting a histogram of sampling distribution K‾0\overline{\mathbf{K}}_0 and highlighting the parts of the histogram that satisfy the “k‾04\overline{\mathbf{k}}_{04} or more extreme” condition.

<Figure size 700x200 with 1 Axes>

Note the pp-value calculation includes simulated observations in the left tail of the distribution: {K‾0≤996.17}\{ \overline{\mathbf{K}}_0 \leq 996.17 \}. This is because the alternative hypothesis is stated as μ≠μK0\mu \neq \mu_{K_0}, so we must consider both positive and negative deviations.

We can now make the decision by comparing the pp-value to the pre-determined threshold α\alpha, which is conventionally chosen α=0.05\alpha=0.05 (1 in 20). The pp-value is 0.015, which means k‾04=1003.83\overline{\mathbf{k}}_{04} = 1003.83 has only a 1.5% chance of occurring under the null hypothesis. The pp-value 0.015 tells us the observed mean obsmean04 = 1003.8335 is very unlikely to occur by chance under H0H_0, so our decision is to “reject the null hypothesis.” In other words, Batch 04 is irregular.

Effect size estimates

We were able to detect that Batch 04 differs from the expected distribution, but how big is the deviation? We can use the deviation from the expected mean Δ^=k‾04−μK0\widehat{\Delta} = \overline{\mathbf{k}}_{04} - \mu_{K_0} as an estimate of the effect size in this situation.

3.833499999999958

The point estimate Δ^=k‾04−μK0=3.83\widehat{\Delta} = \overline{\mathbf{k}}_{04} - \mu_{K_0} = 3.83 tells us how much the mean of the sample differs from the expected population mean μK0\mu_{K_0}, but it doesn’t tell us the uncertainty in this estimate.

Let’s calculate the 90% bootstrap confidence interval for the effect size ciΔ,0.9∗\ci{\Delta,0.9}^*. First let’s obtain a 90% obtain a confidence interval ciμ,0.9∗\ci{\mu,0.9}^* for the unknown population mean μ\mu. We can do this by calling the function ci_mean that we defined in Section 3.2 with the options alpha=0.1 and method="b".

[1001.7537499999999, 1005.8020250000002]

We can now convert the confidence interval ciμ,0.9∗=\ci{\mu,0.9}^* = cimu04 to a confidence interval for the effect size by subtracting the theoretical mean from both limits.

[1.7537499999998545, 5.802025000000185]

The confidence interval ciΔ,0.9∗=[1.75,5.80]\ci{\Delta,0.9}^* = [1.75, 5.80] tells us a range of plausible values for the true effect size (how irregular Batch 04 is) could be anywhere between 1.75ml and 5.8ml. This is much more interesting to know, since it tells us a whole range of plausible values. The interval estimate ciΔ,0.9∗=[1.75,5.80]\ci{\Delta,0.9}^* = [1.75, 5.80] takes into account the variability of the samples we used in the calculation.

Example 2S: test for the mean of Batch 01

Let’s repeat simulation test procedure on the sample k01\mathbf{k}_{01} which comes from Batch 01.

40
999.10375

We generate the sampling distribution of the mean for samples of size n=40n=40 under the null hypothesis H0H_0 by running a simulation using the function gen_sampling_dist.

Next we computed the observed deviation obsdev01 =∣k‾01−μK0∣=|\overline{\mathbf{k}}_{01} - \mu_{K_0}|, then select the values in kbars40 whose deviation from μK0\mu_{K_0} is greater than the observed deviation, and finally compute the pp-value as the proportion of values in the tails.

0.5711

The large pp-value tells us that the observed mean k‾01=999.10\overline{\mathbf{k}}_{01} = 999.10 is not unlikely under H0H_0. Using the terminology of hypothesis testing, we say the outcome of the hypothesis test is that we failed to reject H0:μ=μK0H_0: \mu = \mu_{K_0}. We have not seen any evidence that suggests that the mean of the population from which sample ksample01 was taken from differs from the mean of the theoretical model K0K_0.

In other words, Batch 01 is regular. Ship it!

<Figure size 700x200 with 1 Axes>

Test for the variance

Sampling distribution of the variance under the null

We can generate the the sampling distribution of the variance SK02S^2_{\mathbf{K}_0} by calling the helper function gen_sampling_dist.

<Figure size 700x200 with 1 Axes>

Example 3S: test for the variance of Batch 02

The sample of volume measurements k02\mathbf{k}_{02} from the Batch 02 of the kombucha bottling plant comes from an unknown population with variance σ2\sigma^2, which we can estimate by computing the sample variance sk022s^2_{\mathbf{k}_{02}}.

We want to check whether Batch 02 is a “regular” or “irregular” by comparing the variance of this batch, σ2\sigma^2, to the variance of the theoretical model σK02=100\sigma_{K_0}^2= 100. Specifically, we’re interested in detecting the case when the variance is higher than expected:

HA:σ2>σK02andH0:σ2≤σK02.H_A: \sigma^2 > \sigma_{K_0}^2 \qquad \text{and} \qquad H_0: \sigma^2 \leq \sigma_{K_0}^2.

Note the alternative hypothesis uses the “greater than” inequality, since we don’t mind batches with low variance.

20
124.31760105263139

We’ll now generate the sampling distribution of the variance for sample of size n=20n=20.

0.2132

The pp-value is greater than the cutoff value α=0.05\alpha = 0.05, so our decision is “fail to reject H0H_0.”

<Figure size 700x200 with 1 Axes>

Example 4S: test for the variance of Batch 08

40
169.9979220512824

We’ll now generate the sampling distribution of the variance for sample of size n=40n=40.

0.0041

The pp-value is very small, so our decision is to reject H0H_0.

Effect size estimates

We found the variance in the volumes in this batch is higher than the expected variance. Now let’s compute an estimate for the effect size Δ^=sk082/σK02\widehat{\Delta} = s^2_{\mathbf{k}_{08}} / \sigma_{K_0}^2.

1.699979220512824

This tells us the variance of k08\mathbf{k}_{08} is 70% higher in the theoretically expected variance σK02=100\sigma_{K_0}^2 = 100.

The bootstrap confidence interval for the effect size ciΔ,0.9∗\ci{\Delta,0.9}^* tells us a range of plausible values for the effect size. We can obtain ciΔ,0.9∗\ci{\Delta,0.9}^* by first computing a 90% bootstrap confidence interval for the variance ciσ2,0.9∗\ci{\sigma^2,0.9}^*.

[117.37369362820536, 217.98659930448775]

We can obtain a confidence interval for Δ=σ2/σK02\Delta = \sigma^2 / \sigma_{K_0}^2 by dividing the limits of ciσ2,0.9∗\ci{\sigma^2,0.9}^* by the theoretical variance σK02\sigma_{K_0}^2.

[1.1737369362820536, 2.1798659930448774]

The interval ciΔ,0.9∗=[1.17,2.18]\ci{\Delta,0.9}^* = [1.17, 2.18] tells us the observed sample variance in Batch 08 is somewhere between 1.17 and 2.18 times the expected variance σK02\sigma_{K_0}^2 under the null hypothesis.

Explanations

One-sided and two-sided tests

Selecting the tails of a distribution

The concept of statistics that are “equal or more extreme than θ^x\hat{\theta}_{\mathbf{x}}” is essential to the logic of hypothesis testing. We’ll need to perform this type of filtering any time we use numerical methods for hypothesis testing.

Let’s write a helper function that performs the selection of the tail values for us.

You should be familiar with the three types of tail values selections:

  • For right-tailed tests, we call tailvalues with the option alt="greater", which will select the subset of values in the list valuesH0 that are equal to or greater than the observed statistic obs.

  • Foe left-tailed test, we call tailvalues with the option alt="less", which selects the values that are equal to or less than the observed statistic obs.

  • For two-tailed tests, we select values observations whose deviation from the mean meanH0 is equal to or greater than the observed deviation obsdev.

One-sided pp-value calculation check

We can verify that the function tailvalues works as expected by reproducing the pp-value calculation from Example 3S. Reusing the variables n02=20 and obsvar02=sk022=124.32\tt{obsvar02} = s_{\mathbf{k}_{02}}^2 = 124.32 we calculated above, we can obtain the pp-value by calling the helper function tailvalues with the option alt="greater",then dividing by the total number of simulations:

0.2132

The result is identical to the pp-value pvalue02=0.2132\tt{pvalue02} = 0.2132 that we computed in Example 3S, so we know the function tailvalues works as expected for pp-value calculations of type (a), where we want to detect positive deviations from the expected distribution under H0H_0.

Two-sided pp-value calculation check

Reusing the values n04=40 and obsmean04=x‾04=1003.83\tt{obsmean04} = \overline{\mathbf{x}}_{04} = 1003.83 that we calculated earlier in Example 1S, we can obtain the pp-value by calling the function tailvalues with the option alt="two-sided" then divide by the total number of simulations:

0.015

The result is identical to the pp-value that we obtained in Example 1S, so we know the function tailvalues works as expected for pp-value calculations of type (c), where we want to detect both positive and negative deviations from the expected distribution under H0H_0.

Summary of the hypothesis testing procedure

The steps of the hypothesis testing procedure are as follows:

  • Step 1: Formulate two competing hypotheses H0H_0 and HAH_A.

  • Step 2: Choose an estimator relevant for distinguishing between the two hypotheses.

  • Step 3: Compute the test statistic θ^x\hat{\theta}_{\mathbf{x}} from the sample x\mathbf{x}.

  • Step 4: Obtain Θ^0\widehat{\Theta}_0, the sampling distribution of the test statistic under the null hypothesis.

  • Step 5: Decide whether to reject or fail to reject the null hypothesis H0H_0 based on the pp-value computed from the observed test statistic θ^x\hat{\theta}_{\mathbf{x}} under the sampling distribution Θ^0\widehat{\Theta}_0 assuming H0H_0 is true.

  • Step 6: Report your decision and calculate effect size estimates.

Discussion

Standardized effect size

It is sometimes useful to report the effect size using a “standardized” measure for effect sizes. Cohen’s dd is one such measure, and it is defined as the difference between the observed mean and an expected mean, divided by the sample standard deviation:

d=x‾−μ0sx.d = \frac{\overline{\mathbf{x}} - \mu_0}{ s_{\mathbf{x}} }.

For example, the sample k04\mathbf{k}_{04} from Batch 04 has mean k‾04=1003.83\overline{\mathbf{k}}_{04} = 1003.83, which corresponds to a “raw” deviation of 3.83 from the expected value μK0=1000\mu_{K_0}=1000. We divide the raw deviation (k‾04−μK0\overline{\mathbf{k}}_{04} - \mu_{K_0}) by the sample’s standard deviation sk04=7.85s_{\mathbf{k}_{04}}= 7.85 to obtain Cohen’s dd standardized effect size.

0.48820873453216374

We can interpret the value of Cohen’s dd obtained using this table of reference values, which was published in (Cohen YYYY TODO) and continues to be used as a reference to this day.

Cohen’s dEffect size
0.01very small
0.20small
0.50medium
0.80large

The standardized effect size for kombucha Batch 04 is d=0.488d=0.488, which we quantify as “medium” effect size according to the table of reference values.

The following helper function shows how to compute the Cohen’s dd for a given sample.

0.48820873453216374

Exercises