Analyze A/B Test Results

Table of Contents

Introduction

Part I - Probability

In [1]:
import pandas as pd
import numpy as np
import statsmodels.api as sm
import random
import matplotlib.pyplot as plt
%matplotlib inline
#We are setting the seed to assure you get the same answers on quizzes as we set up
random.seed(42)
/opt/conda/lib/python3.6/site-packages/statsmodels/compat/pandas.py:56: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead.
  from pandas.core import datetools

1. Now, read in the ab_data.csv data. Store it in df.

a. Read in the dataset and take a look at the top few rows here:

In [2]:
df = pd.read_csv('ab_data.csv')
df.head()
Out[2]:
user_id timestamp group landing_page converted
0 851104 2017-01-21 22:11:48.556739 control old_page 0
1 804228 2017-01-12 08:01:45.159739 control old_page 0
2 661590 2017-01-11 16:55:06.154213 treatment new_page 0
3 853541 2017-01-08 18:28:03.143765 treatment new_page 0
4 864975 2017-01-21 01:52:26.210827 control old_page 1

b. Use the cell below to find the number of rows in the dataset.

In [3]:
df.shape
Out[3]:
(294478, 5)

c. The number of unique users in the dataset.

In [4]:
df['user_id'].nunique()
Out[4]:
290584

d. The proportion of users converted.

In [5]:
df['converted'].sum()/df['user_id'].nunique()
Out[5]:
0.12126269856564711

e. The number of times the new_page and treatment don't match.

In [6]:
treatment = df.query('group == "treatment"')
new_page = df.query('landing_page == "new_page"')

treatment_old = treatment.query('landing_page != "new_page"')
new_control = new_page.query('group != "treatment"')

print(treatment_old.shape[0] + new_control.shape[0])
3893

f. Do any of the rows have missing values?

In [7]:
df.isnull().sum()
Out[7]:
user_id         0
timestamp       0
group           0
landing_page    0
converted       0
dtype: int64

2. For the rows where treatment does not match with new_page or control does not match with old_page, we cannot be sure if this row truly received the new or old page. Use Quiz 2 in the classroom to figure out how we should handle these rows.

a. Now use the answer to the quiz to create a new dataset that meets the specifications from the quiz. Store your new dataframe in df2.

In [8]:
treatment_new = (df['group'] == "treatment") & (df['landing_page'] == "new_page")
control_old = (df['group'] == "control") & (df['landing_page'] == "old_page")

df2 = df[treatment_new | control_old]
print ("Number of rows are : ", df2.shape[0])
df2.head()
Number of rows are :  290585
Out[8]:
user_id timestamp group landing_page converted
0 851104 2017-01-21 22:11:48.556739 control old_page 0
1 804228 2017-01-12 08:01:45.159739 control old_page 0
2 661590 2017-01-11 16:55:06.154213 treatment new_page 0
3 853541 2017-01-08 18:28:03.143765 treatment new_page 0
4 864975 2017-01-21 01:52:26.210827 control old_page 1
In [9]:
# Double Check all of the correct rows were removed - this should be 0
df2[((df2['group'] == 'treatment') == (df2['landing_page'] == 'new_page')) == False].shape[0]
Out[9]:
0

3. Use df2 and the cells below to answer questions for Quiz3 in the classroom.

a. How many unique user_ids are in df2?

In [10]:
df2['user_id'].nunique()
Out[10]:
290584

b. There is one user_id repeated in df2. What is it?

In [11]:
df2[df2.duplicated('user_id')].user_id
Out[11]:
2893    773192
Name: user_id, dtype: int64

c. What is the row information for the repeat user_id?

In [12]:
df2[df2.duplicated('user_id')]
Out[12]:
user_id timestamp group landing_page converted
2893 773192 2017-01-14 02:55:59.590927 treatment new_page 0

d. Remove one of the rows with a duplicate user_id, but keep your dataframe as df2.

In [13]:
df2.drop_duplicates(subset="user_id", keep ='first', inplace=True)
print ("Number of rows are : ", df2.shape[0])
Number of rows are :  290584
/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  """Entry point for launching an IPython kernel.

4. Use df2 in the cells below to answer the quiz questions related to Quiz 4 in the classroom.

a. What is the probability of an individual converting regardless of the page they receive?

In [14]:
(df2['converted']==1).mean()
Out[14]:
0.11959708724499628

b. Given that an individual was in the control group, what is the probability they converted?

In [15]:
(df2.query('group == "control"')['converted']== 1).mean()
Out[15]:
0.1203863045004612

c. Given that an individual was in the treatment group, what is the probability they converted?

In [16]:
(df2.query('group == "treatment"')['converted']== 1).mean()
Out[16]:
0.11880806551510564

d. What is the probability that an individual received the new page?

In [17]:
(df2['landing_page']=="new_page").mean()
Out[17]:
0.50006194422266881

e. Consider your results from parts (a) through (d) above, and explain below whether you think there is sufficient evidence to conclude that the new treatment page leads to more conversions.

No because this is just the average, we need to do a simulation over a large sample.

Part II - A/B Test

Notice that because of the time stamp associated with each event, you could technically run a hypothesis test continuously as each observation was observed.

However, then the hard question is do you stop as soon as one page is considered significantly better than another or does it need to happen consistently for a certain amount of time? How long do you run to render a decision that neither page is better than another?

These questions are the difficult parts associated with A/B tests in general.

1. For now, consider you need to make the decision just based on all the data provided. If you want to assume that the old page is better unless the new page proves to be definitely better at a Type I error rate of 5%, what should your null and alternative hypotheses be? You can state your hypothesis in terms of words or in terms of $p_{old}$ and $p_{new}$, which are the converted rates for the old and new pages.

$$H_0: p_{new} - p_{old} \leq 0 $$$$H_1: p_{new} - p_{old} > 0 $$

2. Assume under the null hypothesis, $p_{new}$ and $p_{old}$ both have "true" success rates equal to the converted success rate regardless of page - that is $p_{new}$ and $p_{old}$ are equal. Furthermore, assume they are equal to the converted rate in ab_data.csv regardless of the page.

Use a sample size for each page equal to the ones in ab_data.csv.

Perform the sampling distribution for the difference in converted between the two pages over 10,000 iterations of calculating an estimate from the null.

Use the cells below to provide the necessary parts of this simulation. If this doesn't make complete sense right now, don't worry - you are going to work through the problems below to complete this problem. You can use Quiz 5 in the classroom to make sure you are on the right track.

a. What is the conversion rate for $p_{new}$ under the null?

In [18]:
p_new = (df2.converted).mean()
p_new
Out[18]:
0.11959708724499628

b. What is the conversion rate for $p_{old}$ under the null?

In [19]:
p_old = (df2.converted).mean()
p_old
Out[19]:
0.11959708724499628

c. What is $n_{new}$, the number of individuals in the treatment group?

In [20]:
n_new = len(df2.query('group == "treatment"'))
n_new
Out[20]:
145310

d. What is $n_{old}$, the number of individuals in the control group?

In [21]:
n_old = len(df2.query('group == "control"'))
n_old
Out[21]:
145274

e. Simulate $n_{new}$ transactions with a conversion rate of $p_{new}$ under the null. Store these $n_{new}$ 1's and 0's in new_page_converted.

In [22]:
new_page_converted = np.random.choice([0, 1], size=n_new, p=[1-p_new, p_new])

f. Simulate $n_{old}$ transactions with a conversion rate of $p_{old}$ under the null. Store these $n_{old}$ 1's and 0's in old_page_converted.

In [23]:
old_page_converted = np.random.choice([0, 1], size=n_old, p=[1-p_old, p_old])

g. Find $p_{new}$ - $p_{old}$ for your simulated values from part (e) and (f).

In [24]:
p_new - p_old
Out[24]:
0.0

h. Create 10,000 $p_{new}$ - $p_{old}$ values using the same simulation process you used in parts (a) through (g) above. Store all 10,000 values in a NumPy array called p_diffs.

In [25]:
p_diffs = []
for _ in range(10000):
    new_page_converted = np.random.binomial(n_new,p_new)
    old_page_converted = np.random.binomial(n_old, p_old)
    diff = new_page_converted/n_new - old_page_converted/n_old
    p_diffs.append(diff)
In [26]:
# Convert to numpy array
p_diffs = np.array(p_diffs)

i. Plot a histogram of the p_diffs. Does this plot look like what you expected? Use the matching problem in the classroom to assure you fully understand what was computed here.

In [27]:
plt.hist(p_diffs, alpha = 0.5);

Yes, it looks liek what i expected. It looks like a normal distribution

j. What proportion of the p_diffs are greater than the actual difference observed in ab_data.csv?

In [28]:
# Create datadrame for with all new_page convert
convert_new_df = df2.query('converted == 1 & landing_page == "new_page"')

# Compute conversion rate for new page
convert_new = convert_new_df['user_id'].count()/n_new

# Create datadrame for with all old_page convert
convert_old_df = df2.query('converted == 1 & landing_page == "old_page"') 

# Compute conversion rate for old page
convert_old = convert_old_df['user_id'].count()/n_old

# Compute observed difference in conversion rates
obs_diff = convert_new - convert_old
obs_diff
Out[28]:
-0.0015782389853555567
In [29]:
# Simulate under the null hypothesis
null_vals = np.random.normal(0,p_diffs.std(), p_diffs.size)
In [30]:
# Plot under the null distribution
plt.hist(null_vals)

# Plot line for observed statistic
plt.axvline(x=obs_diff,color='red');
In [31]:
#Compute p-value
(null_vals > obs_diff).mean()
Out[31]:
0.90080000000000005

k. Please explain using the vocabulary you've learned in this course what you just computed in part j. What is this value called in scientific studies? What does this value mean in terms of whether or not there is a difference between the new and old pages?

In part j we computed the p-value.

The p-value 0.90 is greater than 0.05 confidence level.

90% of the null values are more extreme than the observed value(the statistic) in favour of the null hypothesis.

This means the results were not statistically significance and we fail to reject the null hypothesis. This means the difference between the new page and old page is not significant enough to launch the new page and they should keep the old page.

l. We could also use a built-in to achieve similar results. Though using the built-in might be easier to code, the above portions are a walkthrough of the ideas that are critical to correctly thinking about statistical significance. Fill in the below to calculate the number of conversions for each page, as well as the number of individuals who received each page. Let n_old and n_new refer the the number of rows associated with the old page and new pages, respectively.

In [32]:
import statsmodels.api as sm

convert_old = (df2.query('group == "control"')['converted']== 1).sum()
convert_new = (df2.query('group == "treatment"')['converted']== 1).sum()
n_old = len(df2.query('group == "control"'))
n_new = len(df2.query('group == "treatment"'))

m. Now use stats.proportions_ztest to compute your test statistic and p-value. Here is a helpful link on using the built in.

In [33]:
z_score, p_value = sm.stats.proportions_ztest([convert_new, convert_old], [n_new, n_old], alternative='larger') 
z_score, p_value
Out[33]:
(-1.3109241984234394, 0.90505831275902449)

n. What do the z-score and p-value you computed in the previous question mean for the conversion rates of the old and new pages? Do they agree with the findings in parts j. and k.?

A negative z-score indicates that the conversion rates are less the mean.

The p-value 0.905 grater that the 0.05 confidence level indicates it is not statiscally significant.

They agree with the findings in j and k

Part III - A regression approach

1. In this final part, you will see that the result you achieved in the A/B test in Part II above can also be achieved by performing regression.

a. Since each row is either a conversion or no conversion, what type of regression should you be performing in this case?

Logistic Regression

b. The goal is to use statsmodels to fit the regression model you specified in part a. to see if there is a significant difference in conversion based on which page a customer receives. However, you first need to create in df2 a column for the intercept, and create a dummy variable column for which page each user received. Add an intercept column, as well as an ab_page column, which is 1 when an individual receives the treatment and 0 if control.

In [34]:
df2['intercept'] = 1
df2['ab_page'] = pd.get_dummies(df2['group'])['treatment']
df2.head()
/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  """Entry point for launching an IPython kernel.
/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:2: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  
Out[34]:
user_id timestamp group landing_page converted intercept ab_page
0 851104 2017-01-21 22:11:48.556739 control old_page 0 1 0
1 804228 2017-01-12 08:01:45.159739 control old_page 0 1 0
2 661590 2017-01-11 16:55:06.154213 treatment new_page 0 1 1
3 853541 2017-01-08 18:28:03.143765 treatment new_page 0 1 1
4 864975 2017-01-21 01:52:26.210827 control old_page 1 1 0

c. Use statsmodels to instantiate your regression model on the two columns you created in part b., then fit the model using the two columns you created in part b. to predict whether or not an individual converts.

In [35]:
log_mod = sm.Logit(df2['converted'], df2[['intercept', 'ab_page']])
results = log_mod.fit()
Optimization terminated successfully.
         Current function value: 0.366118
         Iterations 6

d. Provide the summary of your model below, and use it as necessary to answer the following questions.

In [36]:
results.summary()
Out[36]:
Logit Regression Results
Dep. Variable: converted No. Observations: 290584
Model: Logit Df Residuals: 290582
Method: MLE Df Model: 1
Date: Wed, 17 Apr 2019 Pseudo R-squ.: 8.077e-06
Time: 17:55:08 Log-Likelihood: -1.0639e+05
converged: True LL-Null: -1.0639e+05
LLR p-value: 0.1899
coef std err z P>|z| [0.025 0.975]
intercept -1.9888 0.008 -246.669 0.000 -2.005 -1.973
ab_page -0.0150 0.011 -1.311 0.190 -0.037 0.007

e. What is the p-value associated with ab_page? Why does it differ from the value you found in Part II?

Hint: What are the null and alternative hypotheses associated with your regression model, and how do they compare to the null and alternative hypotheses in Part II?

The p-value associated with ab_page is 0.190.

It differs from the value in part II because our null hypothessi in this case is that the old page (control) is better that the new page (treatment).

$$H_0: p_{old} - p_{new} \leq 0 $$$$H_1: p_{old} - p_{new} > 0 $$

f. Now, you are considering other things that might influence whether or not an individual converts. Discuss why it is a good idea to consider other factors to add into your regression model. Are there any disadvantages to adding additional terms into your regression model?

It's a good idea to consider other factors to add to the regression model beacuse different variables could have diffeent influences on whether or not an individual converts while holding all other variables constant. Yes there are disadvantages to adding additional terms into the model.

g. Now along with testing if the conversion rate changes for different pages, also add an effect based on which country a user lives in. You will need to read in the countries.csv dataset and merge together your datasets on the appropriate rows. Here are the docs for joining tables.

Does it appear that country had an impact on conversion? Don't forget to create dummy variables for these country columns - Hint: You will need two columns for the three dummy variables. Provide the statistical output as well as a written response to answer this question.

In [37]:
# Create dummy variables for countries
country_df = pd.read_csv('countries.csv')
country_df[['CA','UK','US']] = pd.get_dummies(country_df['country'])

# Join country table with ab_data table
df3 = df2.set_index('user_id').join(country_df.set_index('user_id'))

# Fit model
df['intercept'] = 1

log_mod = sm.Logit(df3['converted'], df3[['intercept', 'ab_page', 'CA', 'UK']])
results = log_mod.fit()
results.summary()
Optimization terminated successfully.
         Current function value: 0.366113
         Iterations 6
Out[37]:
Logit Regression Results
Dep. Variable: converted No. Observations: 290584
Model: Logit Df Residuals: 290580
Method: MLE Df Model: 3
Date: Wed, 17 Apr 2019 Pseudo R-squ.: 2.323e-05
Time: 17:55:09 Log-Likelihood: -1.0639e+05
converged: True LL-Null: -1.0639e+05
LLR p-value: 0.1760
coef std err z P>|z| [0.025 0.975]
intercept -1.9893 0.009 -223.763 0.000 -2.007 -1.972
ab_page -0.0149 0.011 -1.307 0.191 -0.037 0.007
CA -0.0408 0.027 -1.516 0.130 -0.093 0.012
UK 0.0099 0.013 0.743 0.457 -0.016 0.036

None of the variables are statistically significant, so adding countries to the model does not appear to make an impact on conversion.

h. Though you have now looked at the individual factors of country and page on conversion, we would now like to look at an interaction between page and country to see if there significant effects on conversion. Create the necessary additional columns, and fit the new model.

Provide the summary results, and your conclusions based on the results.

In [38]:
# Calculate teh interaction between country and ab_page
df3['CA_page'] = df3['ab_page']*df3['CA']

df3['UK_page'] = df3['ab_page']*df3['UK']

#Fit model
log_mod = sm.Logit(df3['converted'], df3[['intercept', 'ab_page', 'CA', 'UK','CA_page','UK_page']])
results = log_mod.fit()
results.summary()
Optimization terminated successfully.
         Current function value: 0.366109
         Iterations 6
Out[38]:
Logit Regression Results
Dep. Variable: converted No. Observations: 290584
Model: Logit Df Residuals: 290578
Method: MLE Df Model: 5
Date: Wed, 17 Apr 2019 Pseudo R-squ.: 3.482e-05
Time: 17:55:10 Log-Likelihood: -1.0639e+05
converged: True LL-Null: -1.0639e+05
LLR p-value: 0.1920
coef std err z P>|z| [0.025 0.975]
intercept -1.9865 0.010 -206.344 0.000 -2.005 -1.968
ab_page -0.0206 0.014 -1.505 0.132 -0.047 0.006
CA -0.0175 0.038 -0.465 0.642 -0.091 0.056
UK -0.0057 0.019 -0.306 0.760 -0.043 0.031
CA_page -0.0469 0.054 -0.872 0.383 -0.152 0.059
UK_page 0.0314 0.027 1.181 0.238 -0.021 0.084

None of the variables are statistically significant, so the interaction between page and country does not appear to make an impact on conversion.

In [39]:
from subprocess import call
call(['python', '-m', 'nbconvert', 'Analyze_ab_test_results_notebook.ipynb'])
Out[39]:
0