Analyze A/B Test Results
This project will assure you have mastered the subjects covered in the statistics lessons. The hope is to have this project be as comprehensive of these topics as possible. Good luck!
Table of Contents
- Introduction
- Part I - Probability
- Part II - A/B Test
- Part III - Regression
Introduction
A/B tests are very commonly performed by data analysts and data scientists. It is important that you get some practice working with the difficulties of these
For this project, you will be working to understand the results of an A/B test run by an e-commerce website. Your goal is to work through this notebook to help the company understand if they should implement the new page, keep the old page, or perhaps run the experiment longer to make their decision.
As you work through this notebook, follow along in the classroom and answer the corresponding quiz questions associated with each question. The labels for each classroom concept are provided for each question. This will assure you are on the right track as you work through the project, and you can feel more confident in your final submission meeting the criteria. As a final check, assure you meet all the criteria on the RUBRIC.
Part I - Probability
To get started, let's import our libraries.
import pandas as pd
import numpy as np 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 np.random.seed(42)
1.
Now, read in the ab_data.csv
data. Store it in df
. Use your dataframe to answer the questions in Quiz 1 of the classroom.
a. Read in the dataset and take a look at the top few rows here:
df=pd.read_csv('ab_data.csv') df.head()
b. Use the below cell to find the number of rows in the dataset.
df.shape
c. The number of unique users in the dataset.
df['user_id'].nunique()
d. The proportion of users converted.
df['converted'].mean()
e. The number of times the new_page
and treatment
don't line up.
treatment_df=df[df['group']=='treatment'] a=sum(treatment_df['landing_page']!='new_page') new_page_df=df[df['landing_page']=='new_page'] b=sum(new_page_df['group']!='treatment') a+b
f. Do any of the rows have missing values?
df.info()
<font color= blue> No rows with missing values
2.
For the rows where treatment is not aligned with new_page or control is not aligned with old_page, we cannot be sure if this row truly received the new or old page. Use Quiz 2 in the classroom to provide 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.
<font color= blue> It's reasonable to use only rows where we feel confident about the data - so we will remove the conflicting rows
# Conflicting rows to drop
rows_to_drop1=df[((df['group']=='treatment') & (df['landing_page']!='new_page'))] rows_to_drop2=df[((df['group']!='treatment')&(df['landing_page']=='new_page'))] len(rows_to_drop1)+len(rows_to_drop2),len(df) df2=df.drop(rows_to_drop1.index) df2=df2.drop(rows_to_drop2.index) len(df2)
# 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]
3.
Use df2 and the cells below to answer questions for Quiz3 in the classroom.
a. How many unique user_ids are in df2?
df2['user_id'].nunique()
b. There is one user_id repeated in df2. What is it?
sum(df2.duplicated(subset='user_id')) list(df2[df2.duplicated(subset='user_id')]['user_id'])
c. What is the row information for the repeat user_id?
df2[df2.duplicated(subset='user_id')]
d. Remove one of the rows with a duplicate user_id, but keep your dataframe as df2.
#Since, there is consistency with this id,
#we can probably just choose either and remove.
#We shouldn't be counting the same user more than once.
df2.drop_duplicates(subset='user_id',inplace=True) len(df2)
4.
Use df2 in the below cells 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?
# No.of conversions / total no. of individuals
df2['converted'].mean()
b. Given that an individual was in the control
group, what is the probability they converted?
control_gp=df2[df2['group']=='control'] control_gp['converted'].mean()
c. Given that an individual was in the treatment
group, what is the probability they converted?
control_gp=df2[df2['group']=='treatment'] control_gp['converted'].mean()
d. What is the probability that an individual received the new page?
new_pg=df2[df2['landing_page']=='new_page'] len(new_pg)/len(df2)
e. Consider your results from a. through d. above, and explain below whether you think there is sufficient evidence to say that the new treatment page leads to more conversions.
<font color= blue> The probability of an individual in the treatment group converting is 0.120 and probability of an indiviual in the control group converting is 0.118 (almost equal). So, The old page conversion rate is better than the new page conversion rate by a very slight margin
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 poldpold and pnewpnew, which are the converted rates for the old and new pages.
<font color= blue>
H0:Pnew≤PoldH0:Pnew≤Pold<font color= blue>H1:Pnew>PoldH1:Pnew>Pold<font color= blue>alpha=0.05alpha=0.05
2.
Assume under the null hypothesis, pnewpnew and poldpold both have "true" success rates equal to the converted success rate regardless of page - that is pnewpnew and poldpold 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 convert rate for pnewpnew under the null?
P_new=df2['converted'].mean() P_new
b. What is the convert rate for poldpold under the null?
P_old=df2['converted'].mean() P_old
c. What is nnewnnew?
new_df=df2[df2['landing_page']=='new_page'] n_new=len(new_df) n_new
d. What is noldnold?
old_df=df2[df2['landing_page']=='old_page'] n_old=len(old_df) n_old
e. Simulate nnewnnew transactions with a convert rate of pnewpnew under the null. Store these nnewnnew 1's and 0's in new_page_converted.
# Simulating n_new 1's and 0's with P_new probability of success
np.random.seed(42) new_page_converted=np.random.binomial(n=1,p=P_new,size=n_new) (new_page_converted)
f. Simulate noldnold transactions with a convert rate of poldpold under the null. Store these noldnold 1's and 0's in old_page_converted.
# Simulating n_new 1's and 0's with P_old probability of success
old_page_converted=np.random.binomial(n=1,p=P_old,size=n_old) old_page_converted
g. Find pnewpnew - poldpold for your simulated values from part (e) and (f).
p_diff_obs=new_page_converted.mean() - old_page_converted.mean() p_diff_obs
h. Simulate 10,000 pnewpnew - poldpold values using this same process similarly to the one you calculated in parts a. through g. above. Store all 10,000 values in a numpy array called p_diffs.
p_diffs=[]
for i in range(10000): new_page_converted=np.random.binomial(n=1,p=P_new,size=n_new) old_page_converted=np.random.binomial(n=1,p=P_old,size=n_old) diff=new_page_converted.mean() - old_page_converted.mean() p_diffs.append(diff)
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.
plt.hist(p_diffs);
j. What proportion of the p_diffs are greater than the actual difference observed in ab_data.csv?
# Calculation of p value
new_conv=df2[df2['group']=='treatment']['converted'].mean() old_conv=df2[df2['group']=='control']['converted'].mean() act_diff=new_conv-old_conv p_diffs=np.array(p_diffs) pval = (p_diffs>act_diff).mean() pval
k. In words, explain 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?
<font color= blue> The value calculated is the p value. Given that the null hypothesis is true, the probability of observing our statistic, or one or more extreme in favor of the alternative is the p value.
In this case, the large p value suggests that we fail to reject the null. The conversion rate for the old page seems slightly better than or equal to the new 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.
import statsmodels.api as sm
convert_old = sum(old_df.converted) # count of 1's from new and old convert_new = sum(new_df.converted) n_old = len(old_df) n_new = len(new_df)
m. Now use stats.proportions_ztest
to compute your test statistic and p-value. Here is a helpful link on using the built in.
z_score, p_value = sm.stats.proportions_ztest([convert_new,convert_old], [n_new,n_old],alternative='larger') (z_score,p_value)
# Critical Z score value for a one tailed test at confidence level of 95%
from scipy.stats import norm
print(norm.ppf(1-0.05))
# Tells how significant z_score is:
print(norm.cdf(z_score))
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.?
<font color= blue> The p value agrees with the finding in part j, suggesting that we fail to reject the null. The conversion rate for the old page is slightly better than or equal to the new page.
The absolute value of the z-score for a value tells us how many standard deviations it is away from the mean. The Z score obtained here is lesser than the critical Z score, suggesting that we fail to reject the null
Part III - A regression approach
1.
In this final part, you will see that the result you acheived in the previous A/B test can also be acheived 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?
<font color = blue> 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 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.
df2['intercept']=1 df2[['control','treatment']]=pd.get_dummies(df2['group']) df2.head() df2.rename(columns={'treatment':'ab_page'},inplace=True)
c. Use statsmodels to import your regression model. Instantiate the model, and fit the model using the two columns you created in part b. to predict whether or not an individual converts.
from scipy import stats
stats.chisqprob = lambda chisq, df: stats.chi2.sf(chisq, df) import statsmodels.api as sm predictors=['intercept','ab_page'] logit_mod=sm.Logit(df2['converted'],df2[predictors]) results=logit_mod.fit()
d. Provide the summary of your model below, and use it as necessary to answer the following questions.
results.summary()
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 the Part II?
<font color = blue> p-value associated with ab_page is 0.19, which is different from the value found in PartII (0.9). But the larger p value still suggests the same inference that the old page is better than or equal to the new page.
<font color = blue> The previous p value computed was for a one sided test, whereas this one is two sided test. Hence there is a difference in the p value.
<font color = blue> The null and alternative in the regression case is:H0:Pnew=PoldH0:Pnew=PoldH1:Pnew≠PoldH1:Pnew≠Pold<font color = blue> Here the alternative is 'not equal' which is a two sided test, while in the A/B test our hypotheses were different (a one tailed test)
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 is a good idea to consider other factors that may help to avoid the Simpson's paradox. Taking other factors into account might bring to light things that we missed out, or another way of looking at the data and even imply different inferences. Change aversion and novelty effects may influence the rate of conversions. It would be good to create features that factor in these influences. The duration of the experiment is also a major factor. Potential disadvantages: generally, if too many terms are added with too little data we might not get convergence. But in this case since we have a lot of data convergence might not be a problem. Adding additional terms also makes interpretation of coefficients difficult.
g. Now along with testing if the conversion rate changes for different pages, also add an effect based on which country a user lives. You will need to read in the countries.csv dataset and merge together your datasets on the approporiate 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.
countries_df = pd.read_csv('./countries.csv') df_new = countries_df.set_index('user_id').join(df2.set_index('user_id'), how='inner') df_new.head()
### Effect of country and page on conversion
import statsmodels.api as sm
df_new[['CA','US']]=pd.get_dummies(df_new['country'])[['CA',"US"]] df_new['intercept']=1 Xvars=[ 'intercept','CA','US','ab_page'] lm = sm.Logit (df_new['converted'],df_new[Xvars ] ) results = lm.fit() results.summary()
<font color = blue> The baseline is UK.The p values for CA and US suggest that they are not statistically significant in determining conversions at an alpha of 0.05.
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.
### Model to look at interaction between page and country
df_new['intercept']=1 Xvars=[ 'intercept','CA','US'] lm = sm.Logit (df_new['ab_page'],df_new[Xvars ] ) results = lm.fit() results.summary()
<font color = blue> The p values for the countries are larger indicating that they are not very useful (not statistically significant).
Optional work
# Convert timestamp to datetime object
df2['timestamp']=pd.to_datetime(df['timestamp'],format='%Y-%m-%d %H:%M:%S') df2.dtypes
# Duration of experiment
sorted_time = df2['timestamp'].sort_values() sorted_time[0] - sorted_time[len(sorted_time)-1]
Conclusions
<font color = blue>
- By the one tailed hypothesis test results, we fail to reject the null hypothesis (old page is better than or equal to the new page) There is not a significant difference in the conversion rates between the old and new pages. So, the recommendation is to retain the old version of the page.
- The analysis and results are limited only based on available data - effects of change aversion and novelty effects may influence the results. Practical considerations may also need to be factored in while making decisions
- Logistic Regression also gives results that agree with the results of A/B testing. Country does not appear to be a very useful factor in the regression model. The fit of logistic regression models does not appear to be great from the Pseudo R square values - The model can be revised for better predictions
- The duration of the experiment is 14 days. The influence of time may be a major factor in determining the conclusions. It would be good to analyze the data for different subsets of time and look at how the conversion rates differ between control and treatment groups.
<font color = blue> References
- Project Walkthrough , Stack Overflow posts, Udacity Course content and slack forums