You may either submit your notebook through the workspace here, or you may work from your local machine and submit through the next page. Either way assure that your code passes the project RUBRIC. Please save regularly.
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!
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.
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
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 cell below to find the number of rows in the dataset.
df.info()
c. The number of unique users in the dataset.
df['user_id'].nunique()
d. The proportion of users converted.
converted= df['converted'].mean()
converted
e. The number of times the new_page
and treatment
don't match.
#create separate DFs for treatment vs control groups
#treatment group
treatment_df= df.query('group=="treatment"')
#control group
control_df= df.query('group=="control"')
#check total of treatments NOT matching to new_page
#get unique numbers
treatment_df.groupby(['landing_page']).user_id.nunique()
#check total of controls ARE matching to new_page
#get unique numbers
control_df.groupby(['landing_page']).user_id.nunique()
#formula for treatment=/= new_page
## treatment & old_page + control & new_page
notmatch= treatment_df.query('landing_page=="old_page"').nunique() + control_df.query('landing_page=="new_page"').nunique()
notmatch
f. Do any of the rows have missing values?
No
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.
Alternative solution
df2=df.query('group=="treatment" and landing_page=="new_page"')
df1=df.query('group=="control" and landing_page=="old_page"')
df2=df2.append(df1)
#create df2 where treatment&new_page + control&old_page are together
df2=treatment_df.query('landing_page=="new_page"')
df1=control_df.query('landing_page=="old_page"')
df2=df2.append(df1)
# 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?
#count of all unique user_id
df2['user_id'].nunique()
b. There is one user_id repeated in df2. What is it?
#add is_duplicated column to label dupes, find the dupe row
df2['is_duplicated'] = df2.duplicated(['user_id'])
df2[df2["is_duplicated"]]
c. What is the row information for the repeat user_id?
user_id: 773192
Group: Treatment
landing_page: new_page
Converted: 0/False
d. Remove one of the rows with a duplicate user_id, but keep your dataframe as df2.
#drop the dupe user_id, keeping the last entree in place
df2.drop_duplicates(['user_id'], inplace=True)
#check that there are no dupes
df2[(df2['is_duplicated']) == True].shape[0]
#drop the is_duplicated column as it is no longer needed
## the total rows should be df2['user_id'].nunique() == 290584
df2.drop(['is_duplicated'], axis=1, inplace=True)
df2
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?
#everyone who converted total
df2['converted'].mean()
b. Given that an individual was in the control
group, what is the probability they converted?
#everyone who converted in the control group aka old_page
df2.query('group== "control"')['converted'].mean()
c. Given that an individual was in the treatment
group, what is the probability they converted?
#everyone who converted in the treatment group aka new_page
df2.query('group== "treatment"')['converted'].mean()
obs_diff= df2.query('group== "treatment"')['converted'].mean() - df2.query('group== "control"')['converted'].mean()
obs_diff
d. What is the probability that an individual received the new page?
#find probability of receiving new_page
df2.groupby(['converted', 'landing_page']).count()
#the total of all of these lines should equal 290584
##add new_page of 0(not converted) and 1(converted) and divide over total lines
###this should be about 0.5 as this is a fair test between 2 values
(128046+17264)/290584
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.
There is not sufficient difference to conclude that the new treatment page leads to more conversions
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.
Pold = new_page =< old_page
Pnew = new_page > old_page
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?
p_new = float(df2.query('converted == 1')['user_id'].nunique())/float(df2['user_id'].nunique())
p_new
b. What is the conversion rate for $p_{old}$ under the null?
p_old = float(df2.query('converted == 1')['user_id'].nunique())/float(df2['user_id'].nunique())
p_old
c. What is $n_{new}$, the number of individuals in the treatment group?
#count of all unique user_id in treatment group
n_new= df2.query('group=="treatment"')['user_id'].nunique()
n_new
d. What is $n_{old}$, the number of individuals in the control group?
#count of all unique user_id in control group
n_old= df2.query('group=="control"')['user_id'].nunique()
n_old
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.
new_page_converted = np.random.binomial(n_new,p_new)
new_page_converted
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.
old_page_converted = np.random.binomial(n_old,p_old)
old_page_converted
g. Find $p_{new}$ - $p_{old}$ for your simulated values from part (e) and (f).
p_new - p_old
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.
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)
p_diffs = np.array(p_diffs)
p_diffs.mean()
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?
#calculate the p-value
(p_diffs > obs_diff).mean()
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?
We computed the "p-value" in part J. This is what is it called in scientific studies.
A p-value is the probability that the null hypothesis (the idea that a theory being tested is false) gives for a specific experimental result to happen.
An experiment must have a p-value of less than 0.05 for the experiment to be considered evidence of the alternative hypothesis; a low p-value means a higher chance of the new hypothesis being true.
According to the p-value found, we cannot reject the null hypothesis. In other words, there is no difference between the new and old pages.
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
# control
convert_old = sum((df2.group == 'control') & (df2.converted == 1))
# treatment
convert_new = sum((df2.group == 'treatment') & (df2.converted == 1))
n_old = sum(df2.group == 'control')
n_new = sum(df2.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.
z_score, p_value = sm.stats.proportions_ztest([convert_new, convert_old], [n_new, n_old], alternative='larger')
z_score, p_value
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.?
The Z score is a test of statistical significance that helps you decide whether or not to reject the null hypothesis; they are measures of standard deviation
The z-score found is -1 standard deviations below the mean. According to the p-value found, we cannot reject the null hypothesis. In other words, there is no difference between the new and old pages.
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?
It is a binary classification case, so you should use 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.
df2['ab_page'] = pd.get_dummies(df2['group'])['treatment']
df2.tail()
#result
print(df2['ab_page'].mean())
print(df2['converted'].mean())
print(df2.groupby('ab_page').mean()['converted'])
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.
df2['intercept'] = 1
log_mod = sm.Logit(df2['converted'], df2[['intercept', 'ab_page']])
results = log_mod.fit()
d. Provide the summary of your model below, and use it as necessary to answer the following questions.
results.summary()
np.exp(-0.0150)
1-np.exp(-0.0150)
Conversion is 0.98 times as likely for users who landed on the treatment page
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?
pvalue for ab_page is 0.190
The hypotheses for the regression model are:
Hnull = new_page > old_page
Halt = new_page <= old_page
The hypotheses for Part II are:
Hnull == Pold = new_page <= old_page
Halt == Pnew = new_page > old_page
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 important to consider other things such as timestamp (length spent on page). This helps to identify if someone meant to click on that page or not, otherwise known as "bounce rate".
Disadvantages to adding other terms and metrics into the regression model could include
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.
#read in countries
import statsmodels.api as sms;
countries_df= pd.read_csv('countries.csv')
countries_df.head()
#create df3 where you join df2 with the countries_df. we will join where user_id are the same
df3= df2.join(countries_df.set_index('user_id'), on='user_id')
#see how this looks
df3.head(3)
#making sure that we have the same rows of data as df2
df3.info()
#how many different countries and (what are they) does this df3 have?
df3.country.unique()
#add in dummy values for the countries
country_dummies = pd.get_dummies(df3['country'])
df3 = df3.join(country_dummies)
df3.head()
#Fit a linear model using all three countries to predict the conversion
#Don't forget an intercept.
df3['intercept'] = 1
lm = sm.OLS(df3['ab_page'], df3[['intercept', 'CA', 'UK', 'US']])
results = lm.fit()
results.summary()
#fit an appropriate linear model for using abs_page to predict the conversion from
# a country. Use CA as your baseline.
lm2 = sm.OLS(df3['ab_page'], df3[['intercept', 'UK', 'US']])
results2 = lm2.fit()
results2.summary()
plt.hist(df3.query("US == 1")['ab_page'], alpha = 0.3, label = 'US');
plt.hist(df3.query("CA == 1")['ab_page'], alpha = 0.3, label = 'CA');
plt.legend();
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.
Congratulations! You have reached the end of the A/B Test Results project! You should be very proud of all you have accomplished!
Tip: Once you are satisfied with your work here, check over your report to make sure that it is satisfies all the areas of the rubric (found on the project submission page at the end of the lesson). You should also probably remove all of the "Tips" like this one so that the presentation is as polished as possible.
Before you submit your project, you need to create a .html or .pdf version of this notebook in the workspace here. To do that, run the code cell below. If it worked correctly, you should get a return code of 0, and you should see the generated .html file in the workspace directory (click on the orange Jupyter icon in the upper left).
Alternatively, you can download this report as .html via the File > Download as submenu, and then manually upload it into the workspace directory by clicking on the orange Jupyter icon in the upper left, then using the Upload button.
Once you've done this, you can submit your project by clicking on the "Submit Project" button in the lower right here. This will create and submit a zip file with this .ipynb doc and the .html or .pdf version you created. Congratulations!
from subprocess import call
call(['python', '-m', 'nbconvert', 'Analyze_ab_test_results_notebook.ipynb'])