1. A/B Testing¶
In modern data analytics, deciding whether two numerical samples come from the same underlying distribution is called A/B testing. The name refers to the labels of the two samples, A and B.
We will develop the method in the context of an example. The data come from a sample of newborns in a large hospital system. We will treat it as if it were a simple random sample though the sampling was done in multiple stages. Stat Labs by Deborah Nolan and Terry Speed has details about a larger dataset from which this set is drawn.
1.1. Smokers and Nonsmokers¶
The table births
contains the following variables for 1,174 mother-baby pairs: the baby’s birth weight in ounces, the number of gestational days, the mother’s age in completed years, the mother’s height in inches, pregnancy weight in pounds, and whether or not the mother smoked during pregnancy.
births = pd.read_csv(path_data + 'baby.csv')
births.head(10)
Birth Weight | Gestational Days | Maternal Age | Maternal Height | Maternal Pregnancy Weight | Maternal Smoker | |
---|---|---|---|---|---|---|
0 | 120 | 284 | 27 | 62 | 100 | False |
1 | 113 | 282 | 33 | 64 | 135 | False |
2 | 128 | 279 | 28 | 64 | 115 | True |
3 | 108 | 282 | 23 | 67 | 125 | True |
4 | 136 | 286 | 25 | 62 | 93 | False |
5 | 138 | 244 | 33 | 62 | 178 | False |
6 | 132 | 245 | 23 | 65 | 140 | False |
7 | 120 | 289 | 25 | 62 | 125 | False |
8 | 143 | 299 | 30 | 66 | 136 | True |
9 | 140 | 351 | 27 | 68 | 120 | False |
One of the aims of the study was to see whether maternal smoking was associated with birth weight. Let’s see what we can say about the two variables.
We’ll start by selecting just Birth Weight
and Maternal Smoker
. There are 715 non-smokers among the women in the sample, and 459 smokers.
smoking_and_birthweight = births[['Maternal Smoker', 'Birth Weight']]
#smoking_birthweight = smoking_and_birthweight.groupby('Maternal Smoker').count()
smoking_birthweight1 = smoking_and_birthweight.groupby(["Maternal Smoker"]).agg(
count=pd.NamedAgg(column="Maternal Smoker", aggfunc="count")
)
smoking_birthweight1.reset_index()
Maternal Smoker | count | |
---|---|---|
0 | False | 715 |
1 | True | 459 |
smoker = births[births['Maternal Smoker'] == False]
non_smoker = births[births['Maternal Smoker'] == True]
Let’s look at the distribution of the birth weights of the babies of the non-smoking mothers compared to those of the smoking mothers. To generate two overlaid histograms, we will use hist
with the optional group
argument which is a column label or index. The rows of the table are first grouped by this column and then a histogram is drawn for each one.
unit = ''
fig, ax = plt.subplots(figsize=(10,5))
ax.hist(smoker['Birth Weight'], density=True,
label='Maternal Smoker = True',
color='blue',
alpha=0.8,
ec='white',
zorder=5)
ax.hist(non_smoker['Birth Weight'], density=True,
label='Maternal Smoker = ',
color='gold',
alpha=0.8,
ec='white',
zorder=10)
y_vals = ax.get_yticks()
y_label = 'Percent per ' + (unit if unit else 'unit')
x_label = ''
ax.set_yticklabels(['{:g}'.format(x * 100) for x in y_vals])
plt.ylabel(y_label)
plt.xlabel(x_label)
plt.title('')
ax.legend(bbox_to_anchor=(1.04,1), loc="upper left")
plt.show()
The distribution of the weights of the babies born to mothers who smoked appears to be based slightly to the left of the distribution corresponding to non-smoking mothers. The weights of the babies of the mothers who smoked seem lower on average than the weights of the babies of the non-smokers.
This raises the question of whether the difference reflects just chance variation or a difference in the distributions in the larger population. Could it be that there is no difference between the two distributions in the population, but we are seeing a difference in the samples just because of the mothers who happened to be selected?
1.2. The Hypotheses¶
We can try to answer this question by a test of hypotheses. The chance model that we will test says that there is no underlying difference in the popuations; the distributions in the samples are different just due to chance.
Formally, this is the null hypothesis. We are going to have to figure out how to simulate a useful statistic under this hypothesis. But as a start, let’s just state the two natural hypotheses.
Null hypothesis: In the population, the distribution of birth weights of babies is the same for mothers who don’t smoke as for mothers who do. The difference in the sample is due to chance.
Alternative hypothesis: In the population, the babies of the mothers who smoke have a lower birth weight, on average, than the babies of the non-smokers.
1.2.1. Test Statistic¶
The alternative hypothesis compares the average birth weights of the two groups and says that the average for the mothers who smoke is smaller. Therefore it is reasonable for us to use the difference between the two group means as our statistic.
We will do the subtraction in the order “average weight of the smoking group \(-\) average weight of the non-smoking group”. Small values (that is, large negative values) of this statistic will favor the alternative hypothesis.
The observed value of the test statistic is about \(-9.27\) ounces.
means_table = smoking_and_birthweight.groupby('Maternal Smoker').mean()
means_table = means_table.reset_index()
means_table
Maternal Smoker | Birth Weight | |
---|---|---|
0 | False | 123.085315 |
1 | True | 113.819172 |
means = means_table['Birth Weight']
observed_difference = means[1] - means[0]
observed_difference
-9.266142572024918
We are going compute such differences repeatedly in our simulations below, so we will define a function to do the job. The function takes three arguments:
the name of the table of data
the label of the column that contains the numerical variable whose average is of interest
the label of the column that contains the Boolean variable for grouping
It returns the difference between the means of the True
group and the False
group.
def difference_of_means(table, label, group_label):
reduced = table[[label, group_label]]
means_table = reduced.groupby(group_label).mean()
means = means_table[label]
return means[1] - means[0]
To check that the function is working, let’s use it to calculate the observed difference between the means of the two groups in the sample.
difference_of_means(births, 'Birth Weight', 'Maternal Smoker')
-9.266142572024918
That’s the same as the value of observed_difference
calculated earlier.
1.2.2. Predicting the Statistic Under the Null Hypothesis¶
To see how the statistic should vary under the null hypothesis, we have to figure out how to simulate the statistic under that hypothesis. A clever method based on random permutations does just that.
If there were no difference between the two distributions in the underlying population, then whether a birth weight has the label True
or False
with respect to maternal smoking should make no difference to the average. The idea, then, is to shuffle all the labels randomly among the mothers. This is called random permutation.
Take the difference of the two new group means: the mean weight of the babies whose mothers have been randomly labeled smokers and the mean weight of the babies of the remaining mothers who have all been randomly labeled non-smokers. This is a simulated value of the test statistic under the null hypothesis.
Let’s see how to do this. It’s always a good idea to start with the data.
smoking_and_birthweight.head(10)
Maternal Smoker | Birth Weight | |
---|---|---|
0 | False | 120 |
1 | False | 113 |
2 | True | 128 |
3 | True | 108 |
4 | False | 136 |
5 | False | 138 |
6 | False | 132 |
7 | False | 120 |
8 | True | 143 |
9 | False | 140 |
There are 1,174 rows in the table. To shuffle all the labels, we will draw a random sample of 1,174 rows without replacement. Then the sample will include all the rows of the table, in random order.
We can use the Table method sample
with the optional with_replacement=False
argument. We don’t have to specify a sample size, because by default, sample
draws as many times as there are rows in the table.
smoking_and_birthweight2 = smoking_and_birthweight.copy()
shuffled_labels = smoking_and_birthweight2.sample(len(smoking_and_birthweight2), replace = False)
shuffled_labels = np.array(shuffled_labels['Maternal Smoker'])
smoking_and_birthweight2['Shuffled Label'] = shuffled_labels
original_and_shuffled = smoking_and_birthweight2
original_and_shuffled.head(10)
Maternal Smoker | Birth Weight | Shuffled Label | |
---|---|---|---|
0 | False | 120 | False |
1 | False | 113 | False |
2 | True | 128 | False |
3 | True | 108 | True |
4 | False | 136 | True |
5 | False | 138 | True |
6 | False | 132 | False |
7 | False | 120 | False |
8 | True | 143 | False |
9 | False | 140 | False |
Each baby’s mother now has a random smoker/non-smoker label in the column Shuffled Label
, while her original label is in Maternal Smoker
. If the null hypothesis is true, all the random re-arrangements of the labels should be equally likely.
Let’s see how different the average weights are in the two randomly labeled groups.
shuffled_only = original_and_shuffled.drop(columns=['Maternal Smoker'])
shuffled_group_means = shuffled_only.groupby('Shuffled Label').mean()
shuffled = shuffled_group_means.reset_index()
shuffled.head(10)
Shuffled Label | Birth Weight | |
---|---|---|
0 | False | 119.458741 |
1 | True | 119.468410 |
The averages of the two randomly selected groups are quite a bit closer than the averages of the two original groups. We can use our function difference_of_means
to find the two differences.
difference_of_means(original_and_shuffled, 'Birth Weight', 'Shuffled Label')
0.009668327315395686
difference_of_means(original_and_shuffled, 'Birth Weight', 'Maternal Smoker')
-9.266142572024918
But could a different shuffle have resulted in a larger difference between the group averages? To get a sense of the variability, we must simulate the difference many times.
As always, we will start by defining a function that simulates one value of the test statistic under the null hypothesis. This is just a matter of collecting the code that we wrote above. But because we will later want to use the same process for comparing means of other variables, we will define a function that takes three arguments:
the name of the table of data
the label of the column that contains the numerical variable
the label of the column that contains the Boolean variable for grouping
It returns the difference between the means of two groups formed by randomly shuffling all the labels.
def one_simulated_difference(table, label, group_label):
births1 = table.copy()
shuffled_labels = births1.sample(len(births1), replace = False)
shuffled_labels = np.array(shuffled_labels[group_label])
births1['Shuffled Label'] = shuffled_labels
original_and_shuffled = births1
shuffled_only = original_and_shuffled.drop(columns=['Maternal Smoker'])
shuffled_group_means = shuffled_only.groupby('Shuffled Label').mean()
table1 = shuffled_group_means.reset_index()
return difference_of_means(table1, label, 'Shuffled Label')
Run the cell below a few times to see how the output changes.
one_simulated_difference(births, 'Birth Weight', 'Maternal Smoker')
-0.094071941130764
1.2.3. Permutation Test¶
Tests based on random permutations of the data are called permutation tests. We are performing one in this example. In the cell below, we will simulate our test statistic – the difference between the averages of the two groups – many times and collect the differences in an array.
differences = np.array([])
repetitions = 5000
for i in np.arange(repetitions):
new_difference = one_simulated_difference(births, 'Birth Weight', 'Maternal Smoker')
differences = np.append(differences, new_difference)
differences
The array differences
contains 5,000 simulated values of our test statistic: the difference between the mean weight in the smoking group and the mean weight in the non-smoking group, when the labels have been assigned at random.
1.2.4. Conclusion of the Test¶
The histogram below shows the distribution of these 5,000 values. It is the empirical distribution of the test statistic simulated under the null hypothesis. This is a prediction about the test statistic, based on the null hypothesis.
test_conclusion = pd.DataFrame({'Difference Between Group Means':differences})
print('Observed Difference:', observed_difference)
unit = ''
fig, ax = plt.subplots(figsize=(10,5))
ax.hist(test_conclusion, density=True, color='blue', alpha=0.8, ec='white')
y_vals = ax.get_yticks()
y_label = 'Percent per ' + (unit if unit else 'unit')
x_label = 'Diference Between Group Means'
ax.set_yticklabels(['{:g}'.format(x * 100) for x in y_vals])
plt.ylabel(y_label)
plt.xlabel(x_label)
plt.title('Prediction Under the Null Hypothesis');
plt.show()
Observed Difference: -9.266142572024918
Notice how the distribution is centered around 0. This makes sense, because under the null hypothesis the two groups should have roughly the same average. Therefore the difference between the group averages should be around 0.
The observed difference in the original sample is about \(-9.27\) ounces, which doesn’t make an appearance on the horizontal scale of the histogram. The observed value of the statistic and the predicted behavior of the statistic under the null hypothesis are inconsistent.
The conclusion of the test is that the data favour the alternative over the null. The average birth weight of babies born to mothers who smoke is less than the average birth weight of babies born to non-smokers.
If you want to compute an empirical P-value, remember that low values of the statistic favor the alternative hypothesis.
empirical_P = np.count_nonzero(differences <= observed_difference) / repetitions
empirical_P
0.0
The empirical P-value is 0, meaning that none of the 5,000 permuted samples resulted in a difference of -9.27 or lower. This is only an approximation. The exact chance of getting a difference in that range is not 0 but it is vanishingly small.
1.2.5. Another Permutation Test¶
We can use the same method to compare other attributes of the smokers and the non-smokers, such as their ages. Histograms of the ages of the two groups show that in the sample, the mothers who smoked tended to be younger.
smoking_and_age = births[['Maternal Smoker', 'Maternal Age']]
unit = ''
fig, ax = plt.subplots(figsize=(10,5))
ax.hist(smoker['Maternal Age'], density=True, label='Maternal Smoker = True', color='blue', alpha=0.8, ec='white', zorder=5)
ax.hist(non_smoker['Maternal Age'], density=True, label='Maternal Smoker = False', color='gold', alpha=0.8, ec='white', zorder=10)
y_vals = ax.get_yticks()
y_label = 'Percent per ' + (unit if unit else 'unit')
x_label = ''
ax.set_yticklabels(['{:g}'.format(x * 100) for x in y_vals])
plt.ylabel(y_label)
plt.xlabel(x_label)
plt.title('')
ax.legend(bbox_to_anchor=(1.04,1), loc="upper left")
plt.show()
The observed difference between the average ages is about \(-0.8\) years.
observed_age_difference = difference_of_means(births, 'Maternal Age', 'Maternal Smoker')
observed_age_difference
-0.8076725017901509
Remember that the difference is calculated as the mean age of the smokers minus the mean age of the non-smokers. The negative sign shows that the smokers are younger on average.
Is this difference due to chance, or does it reflect an underlying difference in the population?
As before, we can use a permutation test to answer this question. If the underlying distributions of ages in the two groups are the same, then the empirical distribution of the difference based on permuted samples will predict how the statistic should vary due to chance.
age_differences = np.array([])
repetitions = 5000
for i in np.arange(repetitions):
new_difference = one_simulated_difference(births, 'Maternal Age', 'Maternal Smoker')
age_differences = np.append(age_differences, new_difference)
The observed difference is in the tail of the empirical distribution of the differences simulated under the null hypothesis.
mean_differences = pd.DataFrame({'Difference Between Group Means':age_differences})
unit = ''
print('Observed Difference:', observed_age_difference)
fig, ax = plt.subplots(figsize=(8,5))
ax.hist(mean_differences, density=True, alpha=0.8, ec='white', zorder=5)
ax.scatter(observed_age_difference, 0, color='red', s=30, zorder=10).set_clip_on(False)
y_vals = ax.get_yticks()
y_label = 'Percent per ' + (unit if unit else 'unit')
x_label = 'Difference Between Group Means'
ax.set_yticklabels(['{:g}'.format(x * 100) for x in y_vals])
plt.ylabel(y_label)
plt.xlabel(x_label)
plt.title('Prediction Under the Null Hypothesis');
plt.show()
Observed Difference: -0.8076725017901509
The empirical P-value of the test is the proportion of simulated differences that were equal to or less than the observed difference. This is because low values of the difference favor the alternative hypothesis that the smokers were younger on average.
empirical_P = np.count_nonzero(age_differences <= observed_age_difference) / 5000
empirical_P
0.012
The empirical P-value is around 1% and therefore the result is statistically significant. The test supports the hypothesis that the smokers were younger on average.