<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Victor Emeka Amanze on Medium]]></title>
        <description><![CDATA[Stories by Victor Emeka Amanze on Medium]]></description>
        <link>https://medium.com/@u.victoramanze345?source=rss-f19630666fb8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*K1yfv1C4byFE8akl</url>
            <title>Stories by Victor Emeka Amanze on Medium</title>
            <link>https://medium.com/@u.victoramanze345?source=rss-f19630666fb8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:16:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@u.victoramanze345/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Evaluate simple linear regression]]></title>
            <link>https://medium.com/@u.victoramanze345/evaluate-simple-linear-regression-cf9bdc1f3c54?source=rss-f19630666fb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf9bdc1f3c54</guid>
            <dc:creator><![CDATA[Victor Emeka Amanze]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 11:31:09 GMT</pubDate>
            <atom:updated>2023-09-18T11:31:09.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mSXK-onnEwvrOQjf.jpg" /></figure><p>this project will be using simple linear regression to explore relationship between two continious relationship</p><p>For this project, you are part of an analytics team that provides insights about marketing and sales. You have been assigned to a project that focuses on the use of influencer marketing, and you would like to explore the relationship between marketing promotional budgets and sales. The dataset provided includes information about marketing campaigns across TV, radio, and social media, as well as how much revenue in sales was generated from these campaigns. Based on this information, leaders in your company will make decisions about where to focus future marketing efforts, so it is critical to have a clear understanding of the relationship between the different types of marketing and the revenue they generate.</p><p>This activity will develop your knowledge of linear regression and your skills evaluating regression results which will help prepare you for modeling to provide business recommendations in the future.</p><p>we start by importing relevant libraries and packages</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><h3>Import the statsmodel module and the ols function</h3><p>Import the statsmodels.api Python module using its common abbreviation, sm, along with the ols() function from statsmodels.formula.api. To complete this, you will need to write the imports as well.</p><pre>import statsmodels.api as sm</pre><pre>from statsmodels.formula.api import ols</pre><p>now we load the dataset</p><pre>pd.read_csv(&quot;modified marketing and sales dataset.csv&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*3yf2u-jPW3UOb2Eg1xcPrg.png" /></figure><pre>data = pd.read_csv(&quot;modified marketing and sales dataset.csv&quot;)</pre><h3>Data exploration</h3><p>to also collapse sibling sections)” style=”display: inline-block; position: absolute; padding: 0px; outline: none; user-select: none; cursor: pointer; z-index: 0; line-height: 26px; width: 26px; height: 26px; -webkit-tap-highlight-color: transparent; box-sizing: border-box !important; color: var( — colab-primary-text-color); left: -30px; margin: 0px; top: calc(50% — 14px); transition: transform 0.2s ease 0s, -webkit-transform 0.2s ease 0s, -o-transform 0.2s ease 0s;”&gt;</p><h3>New Section</h3><h3>Familiarize yourself with the data’s features</h3><p>Start with an exploratory data analysis to familiarize yourself with the data and prepare it for modeling.</p><p>The features in the data are:</p><p>TV promotion budget (in millions of dollars) Social media promotion budget (in millions of dollars) Radio promotion budget (in millions of dollars) Sales (in millions of dollars) Each row corresponds to an independent marketing promotion where the business invests in TV, Social_Media, and Radio promotions to increase Sales.</p><p>The business would like to determine which feature most strongly predicts Sales so they have a better understanding of what promotions they should invest in in the future. To accomplish this, you’ll construct a simple linear regression model that predicts sales using a single independent variable.</p><h3>Question:</h3><p>What are some reasons for conducting an EDA before constructing a simple linear regression model?</p><h3>Potential reasons include:</h3><p>Understanding which variables are present in the data Reviewing the distribution of features, such as minimum, mean, and maximum values Plotting the relationship between the independent and dependent variables to visualize which feature is the best choice for X Identifying issues with the data, such as incorrect values (e.g., typos) or missing values</p><p>now we calculate the number of rows and column in the dataset</p><pre>data.shape</pre><p>(4572, 4)</p><h3>Explore the independent variables</h3><p>There are three continuous independent variables: TV, Radio, and Social_Media. To understand how heavily the business invests in each promotion type, use describe() to generate descriptive statistics for these three variables.</p><pre>data[[&#39;TV&#39;,&#39;Radio&#39;,&#39;Social_Media&#39;]].describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*jmEg5nsuMOBHGNL3eCnJDw.png" /></figure><h3>Explore the dependent variable</h3><p>Before fitting the model, ensure the Sales for each promotion (i.e., row) is present. If the Sales in a row is missing, that row isn’t of much value to the simple linear regression model.</p><p>Display the percentage of missing values in the Sales column in the DataFrame data</p><p>Calculate the average missing rate in the sales column.</p><pre>missing_sales = data.Sales.isna().mean()</pre><p>now Convert the missing_sales from a decimal to a percentage and round to 2 decimal places.</p><pre>missing_sales = round(missing_sales*100, 2)</pre><p>Display the results (missing_sales must be converted to a string to be concatenated in the print statement).</p><pre>print(&#39;Percentage of promotions missing Sales: &#39; +  str(missing_sales) + &#39;%&#39;)</pre><p>Percentage of promotions missing Sales: 0.13%</p><h3>Remove the missing data</h3><p>Remove all rows in the data from which Sales is missing.</p><p>subset the data to include rows where Sales is present.</p><pre>data = data.dropna(subset = [&#39;Sales&#39;], axis = 0)</pre><h3>Visualize the sales distribution</h3><p>Create a histogram to visualize the distribution of Sales.</p><pre>fig = sns.histplot(data[&#39;Sales&#39;])<br>fig.set_title(&#39;Distribution of Sales&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*RtdKikzflFkfJoeKPyoCGQ.png" /></figure><h3>Question:</h3><p>What do you observe about the distribution of Sales from the histogram above?</p><p>Generally, Sales are equally distributed between 25 and 350 million.</p><h3>Model building</h3><p>Create a pairplot to visualize the relationships between pairs of variables in the data. You will use this to visually determine which variable has the strongest linear relationship with Sales. This will help you select the X variable for the simple linear regression.</p><pre>sns.pairplot(data);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*6MJpq8NWKpwaM7qsHUKhPA.png" /></figure><h3>Question:</h3><p>Which variable did you select for X? Why?</p><p>TV clearly has the strongest linear relationship with Sales. You could draw a straight line through the scatterplot of TV and Sales that confidently estimates Sales using TV. Radio and Sales appear to have a linear relationship, but there is larger variance than between TV and Sales.</p><h3>Build and fit the model</h3><p>Replace the comment with the correct code. Use the variable you chose for X for building the model.</p><p>define the olx formula</p><pre>ols_formula = &#39;Sales ~ TV&#39;</pre><p>Create an OLS model.</p><pre>OLS = ols(formula = ols_formula, data = data)</pre><p>fit the model</p><pre>model = OLS.fit()</pre><p>Save the results summary.</p><pre>model_results = model.summary()</pre><p>Display the model results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*RsLIJRzgYKWhjRjpIgOHbQ.png" /></figure><h3>Check model assumptions</h3><p>To justify using simple linear regression, check that the four linear regression assumptions are not violated. These assumptions are:</p><p>Linearity</p><p>Independent Observations</p><p>Normality</p><p>Homoscedasticity</p><h3>Model assumption: Linearity</h3><p>The linearity assumption requires a linear relationship between the independent and dependent variables. Check this assumption by creating a scatterplot comparing the independent variable with the dependent variable.</p><p>Create a scatterplot comparing the X variable you selected above with the dependent variable.</p><pre>sns.scatterplot(x = data[&#39;TV&#39;], y = data[&#39;Sales&#39;]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*Aq42z_xqyF-LzGSBqFPl3Q.png" /></figure><h3>QUESTION:</h3><p>Is the linearity assumption met?</p><p>There is a clear linear relationship between TV and Sales, meeting the linearity assumption.</p><h3>Model assumption: Independence</h3><p>The independent observation assumption states that each observation in the dataset is independent. As each marketing promotion (i.e., row) is independent from one another, the independence assumption is not violated.</p><h3>Model assumption: Normality</h3><p>The normality assumption states that the errors are normally distributed.</p><p>Create two plots to check this assumption:</p><p>Plot 1: Histogram of the residuals</p><p>Plot 2: Q-Q plot of the residuals</p><p>start by calculating the residuals</p><pre>residuals = model.resid</pre><p>create a 1*2 plot figure</p><p>create a Q Q plot</p><pre>fig, axes = plt.subplots(1, 2, figsize = (8,4))<br>sns.histplot(residuals, ax=axes[0])<br>axes[0].set_xlabel(&quot;Residual Value&quot;)<br>axes[0].set_title(&quot;Histogram of Residuals&quot;)<br>sm.qqplot(residuals, line=&#39;s&#39;,ax = axes[1])<br>axes[1].set_title(&quot;Normal Q-Q plot&quot;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*wvvQ2ABHqydGaPZH2XAorA.png" /></figure><h3>Question: Is the normality assumption met?</h3><p>The histogram of the residuals are approximately normally distributed, which supports that the normality assumption is met for this model.The residuals in the Q-Q plot form a straight line, further supporting that the normality assumption is met.</p><h3>Model assumption: Homoscedasticity</h3><p>The homoscedasticity (constant variance) assumption is that the residuals have a constant variance for all values of X.</p><p>Check that this assumption is not violated by creating a scatterplot with the fitted values and residuals. Add a line at 𝑦=0 to visualize the variance of residuals above and below 𝑦=0 .</p><pre>fig = sns.scatterplot(x = model.fittedvalues, y = model.resid)<br>fig.set_xlabel(&quot;Fitted Values&quot;)<br>fig.set_ylabel(&quot;Residuals&quot;)<br>fig.set_title(&quot;Fitted Values v. Residuals&quot;)<br>fig.axhline(0)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*fU7d8DapqiSVCf2FEZWu9Q.png" /></figure><h3>QUESTION:</h3><p>Is the homoscedasticity assumption met?</p><p>The variance of the residuals is consistant across all 𝑋 . Thus, the assumption of homoscedasticity is met.</p><h3>Results and evaluation</h3><p>Display the OLS regression results If the linearity assumptions are met, you can interpret the model results accurately.</p><p>Display the OLS regression results from the fitted model object, which includes information about the dataset, model fit, and coefficients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*xuOB_PG6fOxQlrHSHoiVFg.png" /></figure><h3>Question:</h3><p>The R-squared on the top right of the output above measures the proportion of variation in the dependent variable (Y) explained by the independent variable (X). What is your intepretation of the model’s R-squared?</p><p>Using TV as X results in a simple linear regression model with 𝑅2=0.999 . In other words, TV explains 99.9% of the variation in Sales.</p><p>The R-squared value will depend on the variable selected for X.</p><h3>Interpret the model results</h3><p>With the model fit evaluated, you can assess the coefficient estimates and the uncertainty of these estimates.</p><h3>Question:</h3><p>Based on the model results displayed above, what do you observe about the coefficients?</p><p>When TV is used as the independent variable X, the coefficient for the Intercept is -0.1263 and the coefficient for TV is 3.5614.</p><h3>Question:</h3><p>How would you write the relationship between X and Sales in the form of a linear equation?</p><p>When TV is used as the independent variable X, the linear equation is:</p><p>𝑌=Intercept+Slope∗𝑋 Sales (in millions)=Intercept+Slope∗TV (in millions) Sales (in millions)=−0.1263+3.5614∗TV (in millions)</p><h3>Question:</h3><p>Based on this model, what is your interpretation of the relationship between X and Sales?</p><p>According to the model, when TV is used as the independent variable X, an increase of one million dollars for the TV promotional budget results in an estimated 3.5614 million dollars more in sales.</p><h3>Question:</h3><p>Why is it important to interpret the beta coefficients?</p><p>Beta coefficients allow you to estimate the magnitude and direction (positive or negative) of the effect of each independent variable on the dependent variable. The coefficient estimates can be converted to explainable insights, such as the connection between an increase in TV promotional budgets and sales mentioned above.</p><p>Measure the uncertainty of the coefficient estimates Model coefficients are estimated. This means there is an amount of uncertainty in the estimate. A p-value and 95% confidence interval are provided with each coefficient to quantify the uncertainty for that coefficient estimate.</p><p>Display the model results again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*I4p4E7u7d70YrQJxZ0AP8w.png" /></figure><h3>Question:</h3><p>Based on this model, what is your interpretation of the p-value and confidence interval for the coefficient estimate of X?</p><p>When TV is used as the independent variable, it has a p-value of 0.000 and a 95% confidence interval of [3.558,3.565] . This means there is a 95% chance the interval [3.558,3.565] contains the true parameter value of the slope. These results indicate little uncertainty in the estimation of the slope of X. Therefore, the business can be confident in the impact TV has on Sales.</p><h3>Question:</h3><p>Based on this model, what are you interested in exploring?</p><p>Potential areas to explore include:</p><p>Providing the business with the estimated sales given different TV promotional budgets Using both TV and Radio as independent variables Adding plots to help convey the results, such as using the seaborn regplot() to plot the data with a best fit regression line</p><h3>Question:</h3><p>What recommendations would you make to the leadership at your organization?</p><p>Of the three available promotion types (TV, radio, and social media), TV has the strongest positive linear relationship with sales. According to the model, an increase of one million dollars for the TV promotional budget will result in an estimated 3.5614 million dollars more in sales. This is a very confident estimate, as the p-value for this coefficient estimate is small. Thus, the business should prioritize increasing the TV promotional budget over the radio and social media promotional budgets to increase sales.</p><h3>Considerations</h3><h3>What are some key takeaways that you learned from this lab?</h3><p>Exploratory data analysis can be used to find a suitable X variable for a simple linear regression model. It’s important to check that simple linear regression assumptions are met before interpreting model results. R-squared is a useful measure of prediction error. It’s important to provide measures of uncertainty (e.g., p-values, confidence intervals) with any coefficient estimates.</p><h3>What findings would you share with others?</h3><p>Sales is relatively equally distributed between 25𝑎𝑛𝑑350 million across all promotions. In the data visualization, TV has the strongest linear relationship with sales. Radio and sales appear to have a moderate linear relationship, but there is larger variance than between TV and sales. Social media and sales appear to have a weak linear relationship. When TV is used as the independent variable, the R-squared for the simple linear regression model estimating sales is 0.999. When TV is used as the independent variable, the coefficient for the intercept is -0.1263 and the coefficient for TV is 3.5614. When TV is used as the independent variable, the slope of the coefficient for TV has a p-value of 0.000 and a 95% confidence interval of [3.558, 3.565].</p><h3>How would you frame your findings to stakeholders?</h3><p>Among TV, social media, and radio, TV had the strongest positive linear relationship with sales. The linear regression model estimates that 99.9% of the variation in sales is explained by the TV promotional budget. In other words, nearly all of the variation in sales can be explained by the TV promotional budget alone, making TV an excellent predictor of sales. According to the model, when TV is used as the independent variable X, an increase of one million dollars for the TV promotional budget would result in an estimated 3.5614 million more dollars in sales. The interval (3.558 million, 3.565 million) has a 95% probability of containing the true estimate of the increase in sales for a one million dollar increase in the TV promotional budget. Therefore, the estimate provided in the previous bullet is very confident.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf9bdc1f3c54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[USING A/B AND HYPOTHESIS TESTING TO DETERMINE WAYS TO IMPROVE THE WORK EXPERIENCE AND COMPENSATION…]]></title>
            <link>https://medium.com/@u.victoramanze345/using-a-b-and-hypothesis-testing-to-determine-ways-to-improve-the-work-experience-and-compensation-99b94b3ac157?source=rss-f19630666fb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/99b94b3ac157</guid>
            <dc:creator><![CDATA[Victor Emeka Amanze]]></dc:creator>
            <pubDate>Sat, 12 Aug 2023 09:39:48 GMT</pubDate>
            <atom:updated>2023-08-12T09:44:03.616Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>USING A/B AND HYPOTHESIS TESTING TO DETERMINE WAYS TO IMPROVE THE WORK EXPERIENCE AND COMPENSATION OF TAXI CAB DRIVERS.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*PZqHBE6QtMvteNVb" /></figure><p>Kindly engage my pages for more data science beginner friendly projects</p><p>GitHub @github.com/victoramanze</p><p>twitter <a href="https://twitter.com/_victor231">@_victor231</a></p><p>Linkedin @<a href="https://www.linkedin.com/in/victor-emeka-amanze-4a9913249/">in/victor-emeka-amanze-4a9913249</a></p><p>In this activity, you will explore the data provided and conduct A/B and hypothesis testing.</p><p>The purpose of this project is to demonstrate knowledge of how to prepare, create, and analyze A/B tests.</p><p>The goal is to apply descriptive and inferential statistics, probability distributions, confidence intervals, and hypothesis testing in Python</p><p>This activity has three parts:</p><h3><strong>Part 1: Imports and data loading</strong></h3><p>What data packages will be necessary for hypothesis testing?</p><h3><strong>Part 2: Conduct hypothesis testing</strong></h3><p>How did computing descriptive statistics help you analyze your data?</p><p>How did you formulate your null hypothesis and alternative hypothesis?</p><h3>Part 3: Communicate insights with Stakeholders</h3><p>What key business insight(s) emerged from your A/B test?</p><p>What business recommendations do you propose based on your results?</p><p>You are a data professional in a data analytics firm, called Automatidata. The current project for their newest client, the New York City Taxi &amp; Limousine Commission (New York City TLC) is reaching its midpoint, having completed a project proposal, Python coding work, and exploratory data analysis.</p><p>The team has reviewed the results of the exploratory data analysis and the executive summary that you prepared for the client, New York City TLC. A few days after the executive summary was presented to New York City TLC, Daichi Watanabe, the Automatidata project manager working on behalf of the New York City TLC project sent an email updating you and your Automatidata colleagues.</p><p>You additionally receive an email from the company’s Senior Data Analyst Luana Rodriquez with your next assignment.</p><p>Conduct an A/B test Now, you are trying to find ways to improve the work experience and compensation of taxi cab drivers.</p><p>In this activity, you will practice using statistics to analyze and interpret data. The activity covers fundamental concepts such as descriptive statistics and hypothesis testing.</p><p><strong>The purpose</strong> of this A/B test is to find ways to generate more revenue for taxi cab drivers.</p><p><strong>Remark:</strong> For the purpose of this exercise, assume that the sample data comes from an experiment in which customers are randomly selected and divided into two groups: 1) customers who are required to pay with credit card, 2) customers who are required to pay with cash. Without this assumption, we cannot draw causal conclusions about how payment method affects fare amount.</p><p><strong>The goal</strong> for this A/B test is to sample data and analyze whether there is a relationship between payment type and fare amount. For example: discover if customers who use credit cards pay higher fare amounts than customers who use cash.</p><h3>Part 1: Exploratory data analysis Explore the NYC Taxi dataset with Python using a Jupyter notebook. This includes:</h3><p>Computing descriptive statistics</p><h3>Part 2: Hypothesis testing with Python</h3><p>Conducting a two-sample hypothesis test Follow the instructions and answer the questions below to complete the activity. Then, you will complete an Executive Summary using the questions listed on the PACE Strategy Document.</p><p>Be sure to complete this activity before moving on. The next course item will provide you with a completed exemplar to compare to your own work.</p><pre>import pandas as pd<br>from scipy import stats</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hVOO97ihuIPISk8etblX6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*pcJ70VuNA82o36RDChKV7w.png" /></figure><pre>taxi_data = pd.read_csv(&quot;nyc taxi trip.csv&quot;, index_col = 0)</pre><h3>use descriptive statistics to conduct Exploratory Data Analysis.</h3><pre><br>taxi_data.describe(include=&#39;all&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VFqb6IJFltT7lSwXqZS4AQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*pH1UPtjX-rQ9_y2XgsYf_Q.png" /></figure><p>You are interested in the relationship between payment type and the total fare amount the customer pays. One approach is to look at the average total fare amount for each payment type.</p><pre>taxi_data.groupby(&#39;payment_type&#39;)[&#39;total_amount&#39;].mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*EwiDrfcvHnIGW9eu4isyyQ.png" /></figure><p>Based on the averages shown, it appears that customers who pay in credit card tend to pay a larger total fare amount than customers who pay in cash. However, this difference might arise from random sampling, rather than being a true difference in total fare amount. To assess whether the difference is statistically significant, you conduct a hypothesis test.</p><p>Hypothesis testing Before you conduct your hypothesis test, consider the following questions where applicable to complete your code response:</p><p>Recall the difference between the null hypothesis and the alternative hypotheses. What are your hypotheses for this data project? Answer: Null hypothesis: There is no difference in average total fare between customers who use credit cards and customers who use cash. Alternative hypothesis: There is a difference in average total fare between customers who use credit cards and customers who use cash Your goal in this step is to conduct a two-sample t-test. Recall the steps for conducting a hypothesis test:</p><p>State the null hypothesis and the alternative hypothesis Choose a signficance level Find the p-value Reject or fail to reject the null hypothesis Complete the following steps to conduct a two-sample t-test.</p><p>Note: For the purpose of this exercise, your hypothesis test is the main component of your A/B test.</p><p><strong>𝐻0 : </strong>There is no difference in the average total fare amount between customers who use credit cards and customers who use cash.</p><p><strong>𝐻𝐴 :</strong> There is a difference in the average total fare amount between customers who use credit cards and customers who use cash.</p><p>You choose 5% as the significance level and proceed with a two-sample t-test.</p><pre>credit_card = taxi_data[taxi_data[&#39;payment_type&#39;] == 1][&#39;total_amount&#39;]<br>cash = taxi_data[taxi_data[&#39;payment_type&#39;] == 2][&#39;total_amount&#39;]<br>stats.ttest_ind(a=credit_card, b=cash, equal_var=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*vRPCFxKEvUmfLz3Bf8uN4A.png" /></figure><p>Since the p-value is extremely small (much smaller than the significance level of 5%), you reject the null hypothesis. You conclude that there is a statistically significant difference in the average total fare amount between customers who use credit cards and customers who use cash.</p><p>Communicate insights with stakeholders Ask yourself the following questions:</p><p>What business insight(s) can you draw from the result of your hypothesis test? Consider why this A/B test project might not be realistic, and what assumptions had to be made for this pedagogical project. *Exemplar responses: *</p><p>The key business insight is that encouraging customers to pay with credit cards will likely generate more revenue for taxi cab drivers.</p><p>This project requires an assumption that passengers were forced to pay one way or the other, and that once informed of this requirement, they always complied with it. The data was not collected this way; so, an assumption had to be made to randomly group data entries to perform an A/B test. This dataset does not account for other likely explanations. For example, riders might not carry lots of cash, so it’s easier to pay for longer/farther trips with a credit card. In other words, it’s far more likely that fare amount determines payment type, rather than vice versa. The difference between average card payment fare and cash fare is inflated, because we use the total amount as the comparing variable. But cash fares all have tip values of $0, while card payments have non-zero values. A possible reason for this occurrence is because cash tips aren’t declared. In turn, this means that we capture tips in one group but not in the other. Instead, one should be comparing the fare_amount column.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99b94b3ac157" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[using SQL to analyze datasets for an e-commerce firm .]]></title>
            <link>https://medium.com/@u.victoramanze345/using-sql-to-analyze-datasets-for-an-e-commerce-firm-b412ea5c522c?source=rss-f19630666fb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b412ea5c522c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql-queries]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Victor Emeka Amanze]]></dc:creator>
            <pubDate>Sat, 05 Aug 2023 18:22:31 GMT</pubDate>
            <atom:updated>2023-08-06T08:59:42.407Z</atom:updated>
            <content:encoded><![CDATA[<h3>using SQL to analyze datasets for an e-commerce firm .</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*mlNO__jOYzpWHCMP.png" /></figure><p>Kindly engage my pages for more data science beginner friendly projects</p><p>GitHub @github.com/victoramanze</p><p>twitter <a href="https://twitter.com/_victor231">@_victor231</a></p><p>Linkedin @<a href="https://www.linkedin.com/in/victor-emeka-amanze-4a9913249/">in/victor-emeka-amanze-4a9913249</a></p><p>here we are using SQL to analyze and derive insight from an e-commerce online sales dataset</p><p>we have a few task to handle and more projects coming</p><p>**pull a list of users email addresses, but only for non deleted users</p><pre>SELECT <br>id AS user_id<br>,email_address<br>FROM dsv1069.users<br>WHERE deleted_at is NULL</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*88DDE3yv6QKTBHgB6pCxxw.png" /></figure><p>**count the number of sales in each category</p><pre>  SELECT<br>  category,<br>  COUNT(id) AS item_count<br> FROM dsv1069.items<br> GROUP BY category<br>   ORDER BY item_count DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*CAP9ynoovpchdiusbSEJVg.png" /></figure><p>**now we want to join the users table to the orders table</p><pre>SELECT *<br>FROM dsv1069.orders<br>JOIN dsv1069.users<br>ON orders.user_id = users.id</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*Do9VowwPjA4byl3QxiRF0A.png" /></figure><p>**count the numbers of viewed items event</p><pre>SELECT <br>COUNT(DISTINCT event_id) AS events<br>FROM dsv1069.events <br>WHERE event_name = &#39;view_item&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*0WGUVoXImB17jRio_Ya4eA.png" /></figure><p>**compute the number of items which have been ordered.</p><pre>SELECT<br> COUNT(DISTINCT orders.item_id) AS item_count<br> FROM dsv1069.orders</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*0KF03SBhq01a6VmWMN_v3Q.png" /></figure><p>**if a user has ordered something and when was the first purchase</p><pre>SELECT <br>users.id AS user_id,<br>MIN(orders.paid_at) AS min_paid_at<br>FROM <br>dsv1069.users <br>LEFT OUTER JOIN <br>dsv1069.orders<br>ON <br>orders.user_id = users.id<br>GROUP BY<br> users.id </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*HbgsPTMmcT7bwZkPledVYw.png" /></figure><p>Write a query to to format the view_item into a table with the appropraite column</p><pre>SELECT <br> event_id,<br> event_time,<br> user_id,<br> platform,<br> MAX(CASE WHEN parameter_name = &#39;item_id&#39;<br>     THEN CAST(parameter_value AS INT)<br>     ELSE NULL <br>     END) AS item_id,<br> MAX(CASE WHEN parameter_name = &#39;referrer&#39;<br>   THEN parameter_value ELSE NULL END) AS referrer<br>   FROM dsv1069.events <br>   WHERE <br>   event_name = &#39;view_item&#39;<br>   GROUP BY<br>   event_id,<br> event_time,<br> user_id,<br> platform</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*oG95f76y4-vBhYJWLxGiqw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b412ea5c522c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create & Access SQLite database using Python]]></title>
            <link>https://medium.com/@u.victoramanze345/create-access-sqlite-database-using-python-c9822d30beaf?source=rss-f19630666fb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9822d30beaf</guid>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-scientist]]></category>
            <dc:creator><![CDATA[Victor Emeka Amanze]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 14:37:01 GMT</pubDate>
            <atom:updated>2023-07-18T16:42:02.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/971/0*PEltdpC2GQrY8BXV.png" /></figure><p>Before we proceed <br>Kindly engage my pages for more data science beginner friendly projects</p><p>GitHub @github.com/victoramanze</p><p>twitter <a href="https://twitter.com/_victor231">@_victor231</a></p><p>Linkedin @<a href="https://www.linkedin.com/in/victor-emeka-amanze-4a9913249/">in/victor-emeka-amanze-4a9913249</a></p><h3>Objectives<a href="https://jupyterlab-3-labs-prod-jupyterlab-us-east-0.labs.cognitiveclass.ai/user/uvictoramanz/lab/tree/labs/authoride/IBMSkillsNetwork%2BDB0201EN/labs/FinalModule_Coursera_V5/Week4_Insert_Update_SQLite.ipynb#Objectives">¶</a></h3><p>After completing this lab you will be able to:</p><ul><li>Create a database</li><li>Create a table</li><li>Insert data into the table</li><li>Query data from the table</li><li>Retrieve the result set into a pandas dataframe</li><li>Close the database connection</li></ul><p>SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. SQLite is the most widely deployed SQL database engine in the world.</p><h3>Task 1: Create database using SQLite<a href="https://jupyterlab-3-labs-prod-jupyterlab-us-east-0.labs.cognitiveclass.ai/user/uvictoramanz/lab/tree/labs/authoride/IBMSkillsNetwork%2BDB0201EN/labs/FinalModule_Coursera_V5/Week4_Insert_Update_SQLite.ipynb#Task-1:-Create-database-using-SQLite">¶</a></h3><pre><br>#Install &amp; load sqlite3<br>#!pip install sqlite3  ##Uncomment the code to install sqlite3<br>import sqlite3</pre><pre># Connecting to sqlite<br># connection object<br>conn = sqlite3.connect(&#39;INSTRUCTOR.db&#39;)</pre><p>Cursor class is an instance using which you can invoke methods that execute SQLite statements, fetch data from the result sets of the queries. You can create Cursor object using the cursor() method of the Connection object/class.</p><pre><br># cursor object<br>cursor_obj = conn.cursor()</pre><h3>Task 2: Create a table in the database<a href="https://jupyterlab-3-labs-prod-jupyterlab-us-east-0.labs.cognitiveclass.ai/user/uvictoramanz/lab/tree/labs/authoride/IBMSkillsNetwork%2BDB0201EN/labs/FinalModule_Coursera_V5/Week4_Insert_Update_SQLite.ipynb#Task-2:-Create-a-table-in-the-database">¶</a></h3><p>In this step we will create a table in the database with following details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*luH6SBhnockd6ns5j1D9-g.png" /></figure><p>Before creating a table, let’s first if the table already exist or not. To drop the table from a database use <strong>DROP</strong> query. A cursor is an object which helps to execute the query and fetch the records from the database.</p><h3>Dont worry if you get this error:<a href="https://jupyterlab-3-labs-prod-jupyterlab-us-east-0.labs.cognitiveclass.ai/user/uvictoramanz/lab/tree/labs/authoride/IBMSkillsNetwork%2BDB0201EN/labs/FinalModule_Coursera_V5/Week4_Insert_Update_SQLite.ipynb#Dont-worry-if-you-get-this-error:">¶</a></h3><p>If you see an exception/error similar to the following, indicating that INSTRUCTOR is an undefined name, that’s okay. It just implies that the INSTRUCTOR table does not exist in the table — which would be the case if you had not created it previously.</p><p><strong>Exception: [IBM][CLI Driver][DB2/LINUXX8664] SQL0204N “ABC12345.INSTRUCTOR” is an undefined name. SQLSTATE=42704 SQLCODE=-204</strong></p><pre># Creating table<br>table = &quot;&quot;&quot; create table IF NOT EXISTS INSTRUCTOR(ID INTEGER PRIMARY KEY NOT NULL, FNAME VARCHAR(20), LNAME VARCHAR(20), CITY VARCHAR(20), CCODE CHAR(2));&quot;&quot;&quot;<br> <br>cursor_obj.execute(table)<br> <br>print(&quot;Table is Ready&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*CN5SGu95iSevvDN7ogWgEg.png" /></figure><h3>Task 3: Insert data into the table<a href="https://jupyterlab-3-labs-prod-jupyterlab-us-east-0.labs.cognitiveclass.ai/user/uvictoramanz/lab/tree/labs/authoride/IBMSkillsNetwork%2BDB0201EN/labs/FinalModule_Coursera_V5/Week4_Insert_Update_SQLite.ipynb#Task-3:-Insert-data-into-the-table">¶</a></h3><p>In this step we will insert some rows of data into the table.</p><p>The INSTRUCTOR table we created in the previous step contains 3 rows of data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*MrEfJm9eb36OzlwtNwcWSg.png" /></figure><p>We will start by inserting just the first row of data, i.e. for instructor Rav Ahuja</p><pre>cursor_obj.execute(&#39;&#39;&#39;insert into INSTRUCTOR values (1, &#39;Rav&#39;, &#39;Ahuja&#39;, &#39;TORONTO&#39;, &#39;CA&#39;)&#39;&#39;&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*B2pTitOiTaZi8YfNyzBVVA.png" /></figure><p>The output you will get something as: <strong>sqlite3.Cursor at 0x27a1a491260</strong> which means mySql database has sqlite3.Cursor object at 0x27a1a49126 as output in table. But you may get the different number.</p><p>Now use a single query to insert the remaining two rows of data</p><pre>cursor_obj.execute(&#39;&#39;&#39;insert into INSTRUCTOR values (2, &#39;Raul&#39;, &#39;Chong&#39;, &#39;Markham&#39;, &#39;CA&#39;), (3, &#39;Hima&#39;, &#39;Vasudevan&#39;, &#39;Chicago&#39;, &#39;US&#39;)&#39;&#39;&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*gLPbd-1kMefh3_-_vJ66-g.png" /></figure><h3>Task 4: Query data in the table<a href="https://jupyterlab-3-labs-prod-jupyterlab-us-east-0.labs.cognitiveclass.ai/user/uvictoramanz/lab/tree/labs/authoride/IBMSkillsNetwork%2BDB0201EN/labs/FinalModule_Coursera_V5/Week4_Insert_Update_SQLite.ipynb#Task-4:-Query-data-in-the-table">¶</a></h3><p>In this step we will retrieve data we inserted into the INSTRUCTOR table.</p><pre>statement = &#39;&#39;&#39;SELECT * FROM INSTRUCTOR&#39;&#39;&#39;<br>cursor_obj.execute(statement)<br><br>print(&quot;All the data&quot;)<br>output_all = cursor_obj.fetchall()<br>for row_all in output_all:<br>  print(row_all)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*yeuzQHLTj0oD05pj2DKoIg.png" /></figure><h3>Fetch few rows from the table</h3><pre><br>statement = &#39;&#39;&#39;SELECT * FROM INSTRUCTOR&#39;&#39;&#39;<br>cursor_obj.execute(statement)<br>  <br>print(&quot;All the data&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*tEZJAeuIi3JW443YwUJK0w.png" /></figure><h3>If you want to fetch few rows from the table we use fetchmany(numberofrows) and mention the number how many rows you want to fetch.</h3><pre>output_many = cursor_obj.fetchmany(2) <br>for row_many in output_many:<br>  print(row_many)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*OwkfSOfjvQadSlT4Xz6gjA.png" /></figure><h3>Fetch only FNAME from the table</h3><pre><br>statement = &#39;&#39;&#39;SELECT FNAME FROM INSTRUCTOR&#39;&#39;&#39;<br>cursor_obj.execute(statement)<br>  <br>print(&quot;All the data&quot;)<br>output_column = cursor_obj.fetchall()<br>for fetch in output_column:<br>  print(fetch)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*X-nEwsY1HEmrDH4sZ5qHHw.png" /></figure><p><strong>Bonus: now write and execute an update statement that changes the Rav’s CITY to MOOSETOWN</strong></p><pre>query_update=&#39;&#39;&#39;update INSTRUCTOR set CITY=&#39;MOOSETOWN&#39; where FNAME=&quot;Rav&quot;&#39;&#39;&#39;<br>cursor_obj.execute(query_update)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*MntiupBUN7mefXPgnbazIg.png" /></figure><pre>statement = &#39;&#39;&#39;SELECT * FROM INSTRUCTOR&#39;&#39;&#39;<br>cursor_obj.execute(statement)<br>  <br>print(&quot;All the data&quot;)<br>output1 = cursor_obj.fetchmany(2)<br>for row in output1:<br>  print(row)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*JuijlfQzfxagrwVvZkJ8PA.png" /></figure><h3>Task 5: Retrieve data into Pandas<a href="https://jupyterlab-3-labs-prod-jupyterlab-us-east-0.labs.cognitiveclass.ai/user/uvictoramanz/lab/tree/labs/authoride/IBMSkillsNetwork%2BDB0201EN/labs/FinalModule_Coursera_V5/Week4_Insert_Update_SQLite.ipynb#Task-5:-Retrieve-data-into-Pandas">¶</a></h3><p>In this step we will retrieve the contents of the INSTRUCTOR table into a Pandas dataframe</p><pre>import pandas as pd<br>#retrieve the query results into a pandas dataframe<br>df = pd.read_sql_query(&quot;select * from instructor;&quot;, conn)<br><br>#print the dataframe<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*KGcxCeB3aEdVZzXthLpi3A.png" /></figure><pre>#print just the LNAME for first row in the pandas data frame<br>df.LNAME[0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/1*MROBgo_SlAcYX2m0odQ_0A.png" /></figure><p>Once the data is in a Pandas dataframe, you can do the typical pandas operations on it.</p><p>For example you can use the shape method to see how many rows and columns are in the dataframe</p><pre>df.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/1*4BfpBRmRbaeiTI0AVPdZmQ.png" /></figure><h3>Task 6: Close the Connection<a href="https://jupyterlab-3-labs-prod-jupyterlab-us-east-0.labs.cognitiveclass.ai/user/uvictoramanz/lab/tree/labs/authoride/IBMSkillsNetwork%2BDB0201EN/labs/FinalModule_Coursera_V5/Week4_Insert_Update_SQLite.ipynb#Task-6:-Close-the-Connection">¶</a></h3><p>We free all resources by closing the connection. Remember that it is always important to close connections so that we can avoid unused connections taking up resources.</p><pre># Close the connection<br>conn.close()</pre><h3>Summary<a href="https://jupyterlab-3-labs-prod-jupyterlab-us-east-0.labs.cognitiveclass.ai/user/uvictoramanz/lab/tree/labs/authoride/IBMSkillsNetwork%2BDB0201EN/labs/FinalModule_Coursera_V5/Week4_Insert_Update_SQLite.ipynb#Summary">¶</a></h3><p>In this tutorial you created a database &amp; table in Python notebook using SQLite3. Then created a table and insert a few rows of data into it. Then queried the data. You also retrieved the data into a pandas dataframe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9822d30beaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run simple linear regression]]></title>
            <link>https://medium.com/@u.victoramanze345/run-simple-linear-regression-3bb909e29597?source=rss-f19630666fb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bb909e29597</guid>
            <category><![CDATA[data-analysis-project]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis-with-python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-science-projects]]></category>
            <dc:creator><![CDATA[Victor Emeka Amanze]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 18:43:45 GMT</pubDate>
            <atom:updated>2023-07-04T21:00:38.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yHVh4zQU8V44y60n.png" /></figure><h3>Introduction</h3><p>As you’re learning, simple linear regression is a way to model the relationship between two variables. By assessing the direction and magnitude of a relationship, data professionals are able to uncover patterns and transform large amounts of data into valuable knowledge. This enables them to make better predictions and decisions.</p><p>In this lab, you are part of an analytics team that provides insights about your company’s sales and marketing practices. You have been assigned to a project that focuses on the use of influencer marketing. For this task, you will explore the relationship between your radio promotion budget and your sales.</p><p>The dataset provided includes information about marketing campaigns across TV, radio, and social media, as well as how much revenue in sales was generated from these campaigns. Based on this information, company leaders will make decisions about where to focus future marketing resources. Therefore, it is critical to provide them with a clear understanding of the relationship between types of marketing campaigns and the revenue generated as a result of this investment.</p><p>Imports In this section, first import relevant Python libraries and modules.</p><h3>Import relevant Python libraries and modules</h3><pre><br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from statsmodels.formula.api import ols<br>import statsmodels.api as sm</pre><p>Now load the dataset into a DataFrame. The dataset provided is a csv file (named marketing_sales_data.csv) containing information about promotional marketing conducted in collaboration with influencers, along with the corresponding sales. This is a fictional dataset that was created for educational purposes and modified for this lab. Assume that the numerical variables in the data are expressed in millions of dollars.</p><h3>Load the dataset into a DataFrame and save in a variable</h3><pre><br>pd.read_csv(&quot;marketing sales data.csv&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*LywXjHwuDzVBhy62iKOHIA.png" /></figure><pre>data = pd.read_csv(&quot;marketing sales data.csv&quot;)</pre><h3>Data Exploration</h3><p>To get a sense of what the data includes, display the first 10 rows of the data.</p><h3>Display the first 10 rows of the data</h3><pre><br>data.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*TSlR8C08dWQxA9AjUfEZFg.png" /></figure><p>The data includes the following information: TV promotion budget (expressed as “Low”, “Medium”, or “High”) Radio promotion budget Social media promotion budget Type of influencer that the promotion is in collaboration with (expressed as “Mega”, “Macro”, or “Micro”, or “Nano”) Note: Mega-influencers have over 1 million followers, macro-influencers have 100,000 to 1 million followers, micro-influencers have 10,000 to 100,000 followers, and nano-influencers have fewer than 10,000 followers. Sales accrued from the promotion</p><p>To get a sense of how large the data is, identify the number of rows and the number of columns in the data.</p><h3>Display number of rows, number of columns</h3><pre><br>data.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/1*2smQybK0L6ONGaPn332QdA.png" /></figure><p>There are 572 rows and 5 columns in the data. One way to interpret this is that 572 companies are represented in the data, along with 5 aspects about each company that reveals how they promote their products/services and the sales accrued from their promotion.</p><p>Now, check for missing values in the rows of the data. This is important because missing values are not that meaningful when modeling the relationship between two variables. To do so, begin by getting Booleans that indicate whether each value in the data is missing. Then, check both columns and rows for missing values</p><h3>Step 1.</h3><h3>Start with .isna() to get booleans indicating whether each value in the data is missing</h3><pre><br>data.isna()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*5uBYEU88FBeTnTUKPtJYgg.png" /></figure><h3>Step 2.</h3><h3>Use .any(axis=1) to get booleans indicating whether there are any missing values along the columns in each row</h3><pre><br>data.isna().any(axis=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*BGCuCuUPXP4bmKstephzIA.png" /></figure><h3>Step 3.</h3><h3>Use .sum() to get the number of rows that contain missing values</h3><pre>data.isna().any(axis=1).sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/110/1*Fvn-AdE7U6XZR5giFuGubQ.png" /></figure><p>There are 3 rows containing missing values, which is not that many, considering the total number of rows. It would be appropriate to drop these rows that contain missing values to proceed with preparing the data for modeling.</p><p>Drop the rows that contain missing values. This is an important step in data cleaning, as it makes the data more usable for the analysis and regression that you will conduct next.</p><h3>Step 1. Use .dropna(axis=0) to indicate that you want rows which contain missing values to be dropped</h3><pre>data = data.dropna(axis=0)</pre><h3>Check to make sure that the data does not contain any rows with missing values now</h3><h3>Start 1</h3><p>with .isna() to get booleans indicating whether each value in the data is missing</p><h3>Step 2.</h3><p>Use .any(axis=1) to get booleans indicating whether there are any missing values along the columns in each row</p><h3>Step 3.</h3><p>Use .sum() to get the number of rows that contain missing values Use .dropna(axis=0) to indicate that you want rows which contain missing values to be dropped</p><pre><br>data.isna().any(axis=1).sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/110/1*BTbfTOCNbWluJuQ1HTCC5g.png" /></figure><h3>Check model assumptions.</h3><p>You would like to explore the relationship between radio promotion budget and sales. You could model the relationship using linear regression. To do this, you want to check if the model assumptions for linear regression can be made in this context. Some of the assumptions can be addressed before the model is built — — you will address those in this section. After the model is built, you can finish checking the assumptions.</p><p>Start by creating a plot of pairwise relationships in the data. This will help you visualize the relationships between variables in the data and help you check model assumptions.</p><pre>sns.pairplot(data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*shaA5jj4lOCdMu219gJeUw.png" /></figure><h3>Is the assumption of linearity met?</h3><p>In the scatter plot of Sales over Radio, the points appear to cluster around a line that indicates a positive association between the two variables. Since the points cluster around a line, it seems the assumption of linearity is met.</p><p>Model Building Start by selecting only the columns that are needed for the model that you will build from the data.</p><h3>Select relevant columns</h3><h3>Save resulting DataFrame in a separate variable to prepare for regression</h3><pre><br>ols_data = data[[&quot;Radio&quot;, &quot;Sales&quot;]]</pre><p>Display the first 10 rows of the new DataFrame to ensure it is accurate.</p><h3>Display first 10 rows of the new DataFrame</h3><pre>ols_data.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*kdb1B1bEaLexfDssMeaRoQ.png" /></figure><p>Write the linear regression formula for modeling the relationship between the two variables of interest.</p><h3>Write the linear regression formula</h3><h3>Save it in a variable</h3><pre><br>ols_formula = &quot;Sales ~ Radio&quot;</pre><p>Implement the Ordinary Least Squares (OLS) approach for linear regression.</p><h3>Implement OLS</h3><pre><br>OLS = ols(formula = ols_formula, data = ols_data)</pre><p>Create a linear regression model for the data and fit the model to the data.</p><h3>Fit the model to the data</h3><h3>Save the fitted model in a variable</h3><pre><br>model = OLS.fit()</pre><p>Results and Evaluation Get a summary of the results from the model.</p><h3>Get summary of results</h3><pre><br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*t2ExX3Gy7Rg8AuHB2pXFzQ.png" /></figure><p>Analyze the bottom table from the results summary. Based on that table, identify the coefficients that the model determined would generate the line of best fit, the coefficients here being the y-intercept and the slope.</p><h3>Question</h3><p>What is the y-intercept? The y-intercept is 41.5326.</p><h3>Question</h3><p>What is the slope?</p><p>The slope is 8.1733.</p><h3>Question</h3><p>What is the linear equation you would write to express the relationship between sales and radio promotion budget in the form of y = slope * x + y-intercept? sales = 8.1733 * radio promotion budget + 41.5326</p><h3>Question</h3><p>What do you think the slope in this context means?</p><p>One interpretation: If a company has a budget of 1 million dollars more for promoting their products/services on the radio, the company’s sales would increase by 8.1733 million dollars on average. Another interpretation: Companies with 1 million dollars more in their radio promotion budget accrue 8.1733 million dollars more in sales on average.</p><p>Finish checking model assumptions. Now that you’ve built the linear regression model and fit it to the data, you can finish checking the model assumptions. This will help confirm your findings.</p><p>Plot the OLS data with the best fit regression line.</p><h3>Plot the OLS data with the best fit regression line</h3><pre><br>sns.regplot(x = &quot;Radio&quot;, y = &quot;Sales&quot;, data = ols_data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*i4haMEQA3CnDfzoi61l3Jw.png" /></figure><p>What do you observe from the regression plot above? The regression plot above shows an approximately linear relationship between the two variables along with the best fit line. This confirms the assumption of linearity.</p><p>Check the normality assumption. To get started, get the residuals from the model.</p><h3>Get the residuals from the model</h3><pre><br>residuals = model.resid</pre><p>Visualize the distribution of the residuals.</p><h3>Visualize the distribution of the residuals</h3><pre><br>fig = sns.histplot(residuals)<br>fig.set_xlabel(&quot;Residual Value&quot;)<br>fig.set_title(&quot;Histogram of Residuals&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qHQ4aAYYQM-iHg0TEVtUYg.png" /></figure><p>Based on the visualization above, what do you observe about the distribution of the residuals? Based on the visualization above, the distribution of the residuals is approximately normal. This indicates that the assumption of normality is likely met.</p><p>Create a Q-Q plot to confirm the assumption of normality.</p><h3>Create a Q-Q plot</h3><pre><br>sm.qqplot(residuals, line=&#39;s&#39;)<br>plt.title(&quot;Q-Q plot of Residuals&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*qI5-k0SP_pM69vX3Nu37QA.png" /></figure><h3>Is the assumption of normality met?</h3><p>In the Q-Q plot above, the points closely follow a straight diagonal line trending upward. This confirms that the normality assumption is met.</p><p>Check the assumptions of independent observation and homoscedasticity. Start by getting the fitted values from the model.</p><h3>Get fitted values</h3><pre><br>fitted_values = model.predict(ols_data[&quot;Radio&quot;])</pre><p>Create a scatterplot of the residuals against the fitted values.</p><h3>Create a scatterplot of residuals against fitted values</h3><pre><br>fig = sns.scatterplot(x=fitted_values, y=residuals)<br>fig.axhline(0)<br>fig.set_xlabel(&quot;Fitted Values&quot;)<br>fig.set_ylabel(&quot;Residuals&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*pF-f2qpeKxiHRb_OMlw_gA.png" /></figure><p>Are the assumptions of independent observation and homoscedasticity met? In the scatterplot above, the data points have a cloud-like resemblance and do not follow an explicit pattern. So it appears that the independent observation assumption has not been violated. Given that the residuals appear to be randomly spaced, the homoscedasticity assumption seems to be met.</p><h3>Conclusion</h3><p>What are the key takeaways from this lab?</p><p>Data visualizations and exploratory data analysis can be used to check if linear regression is a well suited approach for modeling the relationship between two variables. The results of a linear regression model can be used to express the relationship between two variables. What results can be presented from this lab?</p><p>In the simple linear regression model, the y-intercept is 41.5326 and the slope is 8.1733. One interpretation: If a company has a budget of 1 million dollars more for promoting their products/services on the radio, the company’s sales would increase by 8.1733 million dollars on average. Another interpretation: Companies with 1 million dollars more in their radio promotion budget accrue 8.1733 million dollars more in sales on average.</p><p>The results are statistically significant with a p-value of 0.000, which is a very small value (and smaller than the common significance level of 0.05). This indicates that there is a very low probability of observing data as extreme or more extreme than this dataset when the null hypothesis is true. In this context, the null hypothesis is that there is no relationship between radio promotion budget and sales i.e. the slope is zero, and the alternative hypothesis is that there is a relationship between radio promotion budget and sales i.e. the slope is not zero. So, you could reject the null hypothesis and state that there is a relationship between radio promotion budget and sales for companies in this data.</p><p>The slope of the line of best fit that resulted from the regression model is approximate and subject to uncertainty (not the exact value). The 95% confidence interval for the slope is from 7.791 to 8.555. This indicates that there is a 95% probability that the interval [7.791, 8.555] contains the true value for the slope.</p><h3>How would you frame your findings to external stakeholders?</h3><p>Based on the dataset at hand and the regression analysis conducted here, there is a notable relationship between radio promotion budget and sales for companies in this data, with a p-value of 0.000 and standard error of 0.194. For companies represented by this data, a 1 million dollar increase in radio promotion budget could be associated with a 8.1733 million dollar increase in sales. It would be worth continuing to promote products/services on the radio. Also, it is recommended to consider further examining the relationship between the two variables (radio promotion budget and sales) in different contexts. For example, it would help to gather more data to understand whether this relationship is different in certain industries or when promoting certain types of products/services.</p><p>Follow my GitHub for more data science beginners friendly. project</p><p>github.com/victoramanze</p><p>DATA SCIENCE : REGRESSION ANALYSIS : MODEL ASSUMPTIONS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bb909e29597" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Hypothesis Testing to Test The Air Quality]]></title>
            <link>https://medium.com/@u.victoramanze345/using-hypothesis-testing-to-test-the-air-quality-c70361e9dc87?source=rss-f19630666fb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c70361e9dc87</guid>
            <category><![CDATA[data-science-projects]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Victor Emeka Amanze]]></dc:creator>
            <pubDate>Wed, 28 Jun 2023 15:49:38 GMT</pubDate>
            <atom:updated>2023-07-04T21:09:55.068Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*aGyQ14kITwkLvCAB.png" /></figure><h3>Introduction</h3><p>You work for an environmental think tank called Repair Our Air (ROA). ROA is formulating policy recommendations to improve the air quality in America, using the Environmental Protection Agency’s Air Quality Index (AQI) to guide their decision making. An AQI value close to 0 signals “little to no” public health concern, while higher values are associated with increased risk to public health.</p><p>They’ve tasked you with leveraging AQI data to help them prioritize their strategy for improving air quality in America.</p><p>ROA is considering the following decisions. For each, construct a hypothesis test and an accompanying visualization, using your results of that test to make a recommendation:</p><pre>import pandas as pd<br>import numpy as np<br>from scipy import stats</pre><pre>pd.read_csv(&quot;c4 epa air dataset.csv&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YkhITweIJVUR-Ag3h0XazA.png" /></figure><pre>ads = pd.read_csv(&quot;c4 epa air dataset.csv&quot;)</pre><p>show a sample of data “Use describe() to summarize AQI”For a more thorough examination of observations by state use values_counts()”)</p><pre>print(ads.head())<br>print(ads.describe(include=&#39;all&#39;))<br>print(ads[&#39;state_name&#39;].value_counts())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*7xIXakihvAcsN5Ir3Z-Efw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*mHOQ49kcrqIVsyqw1byZZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*8cZgPE9MQXzson3TfQ01AA.png" /></figure><p>From data exploration above, what do you recognize?¶ You have county-level data for the first hypothesis. Ohio and New York both have a higher number of observations to work with in this dataset.</p><p>Before you proceed, recall the following steps for conducting hypothesis testing:</p><p>Formulate the null hypothesis and the alternative hypothesis. Set the significance level. Determine the appropriate test procedure. Compute the p-value. Draw your conclusion.</p><h3>HYPOTHESIS 1</h3><p>ROA is considering a metropolitan-focused approach. Within California, they want to know if the mean AQI in Los Angeles County is statistically different from the rest of California</p><pre>ca_la = ads[ads[&#39;county_name&#39;]==&#39;Los Angeles&#39;]<br>ca_other = ads[(ads[&#39;state_name&#39;]==&#39;California&#39;) &amp; (ads[&#39;county_name&#39;]!=&#39;Los Angeles&#39;)]</pre><p>Formulate your null and alternative hypotheses:</p><p>𝐻0 : There is no difference in the mean AQI between Los Angeles County and the rest of California. 𝐻𝐴 : There is a difference in the mean AQI between Los Angeles County and the rest of California.</p><p>we will use 95% as the significant level</p><pre>significance_level = 0.95<br>significance_level</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*nQVWkmH5eCBOnRTzf0-5kg.png" /></figure><p>Determine the appropriate test procedure: Here, you are comparing the sample means between two independent samples. Therefore, you will utilize a two-sample 𝑡-test.</p><p>Compute the P-value</p><pre>stats.ttest_ind(a=ca_la[&#39;aqi&#39;], b=ca_other[&#39;aqi&#39;], equal_var=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*8MD5N808BZ9zU4DZr91ayA.png" /></figure><p>Question 2. What is your P-value for hypothesis 1, and what does this indicate for your null hypothesis? With a p-value (0.049) being less than 0.05 (as your confidence level is 95%), reject the null hypothesis in favor of the alternative hypothesis.</p><p>Therefore, a metropolitan strategy may make sense in this case.</p><h3><strong>Hypothesis 2:</strong></h3><p>With limited resources, ROA has to choose between New York and Ohio for their next regional office. Does New York have a lower AQI than Ohio?¶</p><pre>ny = ads[ads[&#39;state_name&#39;]==&#39;New York&#39;]<br>ohio = ads[ads[&#39;state_name&#39;]==&#39;Ohio&#39;]</pre><p>Formulate your hypothesis: Formulate your null and alternative hypotheses:</p><p>𝐻0 : The mean AQI of New York is greater than or equal to that of Ohio. 𝐻𝐴 : The mean AQI of New York is below that of Ohio.</p><p>significance level = 95%</p><p>Determine the appropriate test procedure: Here, you are comparing the sample means between two independent samples in one direction. Therefore, you will utilize a two-sample 𝑡-test.</p><p>Compute the P-value¶</p><pre>tstat, pvalue = stats.ttest_ind(a=ny[&#39;aqi&#39;], b=ohio[&#39;aqi&#39;], alternative=&#39;less&#39;)<br>print(tstat)<br>print(pvalue)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*2wG_VRDQqhI-9f26GKtr8A.png" /></figure><h3>Question 3.</h3><p>What is your P-value for hypothesis 2, and what does this indicate for your null hypothesis? With a p-value (0.030) being less than 0.05 (as your confidence level is 95%) and a t-statistic &lt; 0 (-2.02), reject the null hypothesis in favor of the alternative hypothesis.</p><p>Therefore, you can conclude with 95% confidence that New York has a lower mean AQI than Ohio.</p><h3>Hypothesis 3:</h3><p>A new policy will affect those states with a mean AQI of 10 or greater. Can you rule out Michigan from being affected by this new policy?</p><pre>michigan = ads[ads[&#39;state_name&#39;]==&#39;Michigan&#39;]</pre><p>Formulate your hypothesis: Formulate your null and alternative hypotheses here:</p><p>𝐻0 : The mean AQI of Michigan is less than or equal to 10. 𝐻𝐴 : The mean AQI of Michigan is greater than 10.</p><p>significance level remains at 95%</p><p>Determine the appropriate test procedure: Here, you are comparing one sample mean relative to a particular value in one direction. Therefore, you will utilize a one-sample 𝑡-test.</p><pre>tstat, pvalue = stats.ttest_1samp(michigan[&#39;aqi&#39;], 10, alternative=&#39;greater&#39;)<br>print(tstat)<br>print(pvalue)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*xTuuMlDJwSIm9QU8gYUvcw.png" /></figure><h3>Question 4.</h3><p>What is your P-value for hypothesis 3, and what does this indicate for your null hypothesis? With a p-value (0.060) being greater than 0.05 (as your confidence level is 95%) and a t-statistic &lt; 0 (-1.73), fail to reject the null hypothesis.</p><p>Therefore, you cannot conclude with 95% confidence that Michigan’s mean AQI is below 10.</p><p>Step 4. Results and Evaluation Now that you’ve completed your statistical tests, you can consider your hypotheses and the results you gathered.</p><h3>Question 5.</h3><p>Did your results show that the AQI in Los Angeles County was statistically different from the rest of California? Yes, the results indicated that the AQI in Los Angeles County was in fact different from the rest of California.</p><h3>Question 6.</h3><p>Did New York or Ohio have a lower AQI? Using a 95% significance level, you can conclude that New York has a lower AQI than Ohio based on the results.</p><h3>Question 7:</h3><p>Will Michigan be affected by the new policy impacting states with a mean AQI of 10 or greater? Based on the tests, you would fail to reject the null hypothesis, meaning you can’t conclude that the mean AQI is below 10. Thus, it is likely that Michigan would be affected by the new policy.</p><h3>Conclusion</h3><p>What are key takeaways from this lab?</p><p>Even with small sample sizes, the variation within the data is enough to allow you to make statistically significant conclusions. You identified with 95% confidence that the Los Angeles mean AQI was stastitically different from the rest of California, and that New York does have a lower mean AQI than Ohio. However, you were unable to conclude with 95% confidence that Michigan’s mean AQI was below 10.</p><h3>What would you consider presenting to your manager as part of your findings?</h3><p>For each test, you would present the null and alternative hypothesis, then describe your conclusion and the resulting p-value that drove that conclusion. As the setup of t-test’s have a few key configurations that dictate how you interpret the result, you would specify the type of test you chose, whether that tail was one-tail or two-tailed, and how you performed the t-test from stats.</p><h3>What would you convey to external stakeholders?</h3><p>In answer to the research questions posed, you would convey the degree of confidence (95%) and your conclusion. Additionally, providing the sample statistics being compared in each case will likely provide important context for stakeholders to quickly understand the difference between your results.</p><p>follow my Github page for more data science beginners projects@<br>github.com/victoramanze</p><p>DATA SCIENCE . HYPOTHESIS TESTING. STATISTICS</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c70361e9dc87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Linear Regression with python and checking model assumptions]]></title>
            <link>https://medium.com/@u.victoramanze345/copy-of-simple-linear-regresssion-with-python-and-checking-model-assumptions-c79ea449146e?source=rss-f19630666fb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c79ea449146e</guid>
            <category><![CDATA[data-science-projects]]></category>
            <dc:creator><![CDATA[Victor Emeka Amanze]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 17:59:24 GMT</pubDate>
            <atom:updated>2023-07-04T21:10:25.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*Lj3b6ZqrF6pbG6Vi7OKo3A.png" /></figure><p>Now we will begin diving into regression analysis and this is the first simple linear regression project which identifies standards model assumption will be met to fit a model.<br>Throughout the following exercises, you will learn to use Python to build a simple linear regression model. Before starting on this programming exercise</p><p>As we move forward, you can find instructions on how to install required libraries as they arise in this notebook. Before we begin with the exercises and analyzing the data, we need to import all libraries and extensions required for this programming exercise. Throughout the course, we will be using pandas and statsmodels for operations, and seaborn for plotting.</p><p>first we begin by importing the relevant libraries</p><pre>import pandas as pd<br>import seaborn as sns</pre><p>now we import the dataset with the read_csv</p><pre>sns.load_dataset(&quot;penguins&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*axDRI1d2bvqHDMDwbiPr-g.png" /></figure><pre>penguins = sns.load_dataset(&quot;penguins&quot;)</pre><pre>penguins.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*zj-BQdI8dK_AOlGPjPZ4lA.png" /></figure><p>From the first 5 rows of the dataset, we can see that there are several columns available: species, island, bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g, and sex. There also appears to be some missing data.</p><h3>data cleaning</h3><p>For the purposes of this project, we are focusing our analysis on Adelie and Gentoo penguins, and will be dropping any missing values from the dataset. In a work setting, you would typically examine the data more thoroughly before deciding how to handle missing data (i.e., fill in, drop, etc.).</p><pre>penguins_sub = penguins[penguins[&quot;species&quot;] != &quot;Chinstrap&quot;]<br>penguins_final = penguins_sub.dropna()<br>penguins_final.reset_index(inplace=True, drop=True)</pre><p>You can review the documentation for dropna() and reset_index(). In short, the dropna() function by default removes any rows with any missing values in any of the columns. The reset_index() function resets the index values for the rows in the dataframe. Typically, you use reset_index() after you’ve finished manipulating the dataset. By setting inplace=True, you will not create a new DataFrame object. By setting drop=True, you will not insert a new index column into the DataFrame object.</p><h3>Exploratory data analysis</h3><p>Before you construct any model, it is important to get more familiar with your data. You can do so by performing exploratory data analysis or EDA. Please review previous program materials as needed if you would like to re-familiarize yourself with EDA concepts.</p><p>Since this part of the course focuses on simple linear regression, you want to check for any linear relationships among variables in the dataframe. You can do this by creating scatterplots using any data visualization package, for example matplotlib.plt, seaborn, or plotly.</p><p>To visualize more than one relationship at the same time, we use the pairplot() function from the seaborn package to create a scatterplot matrix.</p><pre>sns.pairplot(penguins_final)</pre><p>&lt;seaborn.axisgrid.PairGrid at 0x7f68cbc69630&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*YlZtnzaWW-SsuGldMNv4bQ.png" /></figure><p>Next, you can construct the linear regression formula, and save it as a string. Remember that the y or dependent variable comes before the ~, and the x or independent variables comes after the ~.</p><pre>ols_formula = &quot;body_mass_g ~ bill_length_mm&quot;</pre><p>Lastly, you can build the simple linear regression model in statsmodels using the ols() function. You can import the ols() function directly using the line of code below.</p><p>now we import the olx functions</p><pre>from statsmodels.formula.api import ols</pre><p>Then, you can plug in the ols_formula and ols_data as arguments in the ols() function. After you save the results as a variable, you can call on the fit() function to actually fit the model to the data.</p><p>now we build ols and fit model to data</p><pre>OLS = ols(formula = ols_formula, data = ols_data)<br>model = OLS.fit()</pre><p>Lastly, you can call the summary() function on the model object to get the coefficients and more statistics about the model. The output from model.summary() can be used to evaluate the model and interpret the results. Later in this section, we will go over how to read the results of the model output.</p><pre>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*Lj3b6ZqrF6pbG6Vi7OKo3A.png" /></figure><p>You use the regplot() function from seaborn to visualize the regression line.</p><p>According to the simple linear regression model we built, � 1 ^ β 1​</p><p>^​is 141.1904. So for every one-millimeter increase in the bill length of a penguin, we would expect a penguin to have about 141.1904 more grams in body mass. The estimate has a p-value of 0.000, which is less than 0.05, meaning that the coefficient is “statistically significant.” Additionally our estimate has a 95% confidence interval of 131.788 and 150.592. Let’s review these short sentences a bit more.</p><p>Confidence Intervals Each beta coefficient also has a confidence interval associated with its estimate. A 95% interval means the interval itself has a 95% chance of containing the true parameter value of the coefficient. So there is 5% chance that our confidence interval [131.788, 150.592] does not contain the true value of � 1 β 1​.</p><p>But, since there is uncertainty in both of the estimated beta coefficients, then the estimated y values also have uncertainty. This is where confidence bands become useful.</p><pre>sns.regplot(x = &quot;bill_length_mm&quot;, y = &quot;body_mass_g&quot;, data = ols_data)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*qg5kOrEN3HoNcL0rJ4Fl6w.png" /></figure><h3>Finish checking model assumptions</h3><p>there are four main model assumptions for simple linear regression, in no particular order:</p><p>Linearity</p><p>Normality</p><p>Independent observations</p><p>Homoscedasticity</p><p>You already checked the linearity assumption by creating the scatterplot matrix. The independent observations assumption is more about data collection. There is no reason to believe that one penguin’s body mass or bill length would be related to any other penguin’s anatomical measurements. So we can check off assumptions 1 and 3.</p><p>The normality and homoscedasticity assumptions focus on the distribution of errors. Thus, you can only check these assumptions after you have constructed the model. To check these assumptions, you will check the residuals, as an approximation of the errors.</p><p>To more easily check the model assumptions and create relevant visualizations, you can first subset the X variable by isolating just the bill_length_mm column. Additionally, you can save the predicted values from the model using the model.predict(X) function.</p><p>subset * variable</p><pre>X = ols_data[&quot;bill_length_mm&quot;]</pre><pre>fitted_values = model.predict(X)</pre><p>Then, you can save the model residuals as a variable by using the model.resid attribute.</p><p>we calculate the residual</p><pre>residuals = model.resid</pre><h3>Check the normality</h3><p>To check the normality assumption, you can create a histogram of the residuals using the histplot() function from the seaborn package.</p><p>From the below histogram, you may notice that the residuals are almost normally distributed. In this case, it is likely close enough that the assumption is met.</p><pre>import matplotlib.pyplot as plt<br>fig = sns.histplot(residuals)<br>fig.set_xlabel(&quot;Residual Value&quot;)<br>fig.set_title(&quot;Histogram of Residuals&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*zhudVnASU4FV23RIUp_bZg.png" /></figure><p>Another way to check the normality function is to create a quantile-quantile or Q-Q plot. Recall that if the residuals are normally distributed, you would expect a straight diagonal line going from the bottom left to the upper right of the Q-Q plot. You can create a Q-Q plot by using the qqplot function from the statsmodels.api package.</p><p>The Q-Q plot shows a similar pattern to the histogram, where the residuals are mostly normally distributed, except at the ends of the distribution.</p><pre>import matplotlib.pyplot as plt<br>import statsmodels.api as sm<br>fig = sm.qqplot(model.resid, line = &#39;s&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*zMyAErHxmS8nvwqfTnYpQA.png" /></figure><h3>Check the homoscedasticity assumption</h3><p>Lastly, we have to check the homoscedasticity assumption. To check the homoscedasticity assumption, you can create a scatterplot of the fitted values and residuals. If the plot resembles a random cloud (i.e., the residuals are scattered randomly), then the assumption is likely met.</p><p>You can create one scatterplot by using the scatterplot() function from the seaborn package. The first argument is the variable that goes on the x-axis. The second argument is the variable that goes on the y-axis.</p><pre>import matplotlib.pyplot as plt<br>fig = sns.scatterplot(x=fitted_values, y=residuals)<br>fig.axhline(0)<br>fig.set_xlabel(&quot;Fitted Values&quot;)<br>fig.set_ylabel(&quot;Residuals&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*67gKyZVEnwDhyXhWuIkgdA.png" /></figure><p>DATA SCIENCE. SIMPLE LINEAR REGRESSION. AND MODEL ASSUMPTION.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c79ea449146e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[using confidence interval with python to understand the air distribution.]]></title>
            <link>https://medium.com/@u.victoramanze345/using-confidence-interval-with-python-to-understand-the-air-distribution-302903ae4247?source=rss-f19630666fb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/302903ae4247</guid>
            <category><![CDATA[data-science-projects]]></category>
            <dc:creator><![CDATA[Victor Emeka Amanze]]></dc:creator>
            <pubDate>Sat, 03 Jun 2023 07:45:10 GMT</pubDate>
            <atom:updated>2023-07-04T21:10:55.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c2MLqKXPgHcn8RB1.jpg" /></figure><p>The Air Quality Index (AQI) is the Environmental Protection Agency’s index for reporting air quality. A value close to 0 signals little to no public health concern, while higher values are associated with increased risk to public health. The United States is considering a new federal policy that would create a subsidy for renewable energy in states observing an average AQI of 10 or above.</p><p>You’ve just started your new role as a data analyst in the Strategy division of Ripple Renewable Energy (RRE). RRE operates in the following U.S. states: California, Florida, Michigan, Ohio, Pennsylvania, Texas. You’ve been tasked with constructing an analysis which identifies which of these states are most likely to be affected, should the new federal policy be enacted.</p><p>Your manager has requested that you do the following for your analysis:</p><pre>import pandas as pd<br>import numpy as np</pre><pre>pd.read_csv(&quot;c4 epa air dataset.csv&quot;)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OEPsuxtQVTEhHkdNpLWf6A.png" /></figure><p>we rename the dataset to ads .</p><pre>ads = pd.read_csv(&quot;c4 epa air dataset.csv&quot;)</pre><pre>print(ads.describe(include=&#39;all&#39;))<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*Mv7TUbS-tlOLWvrkweWY0Q.png" /></figure><p>now let us observe the states .let us use the values_counts()”)</p><pre>print(ads[&#39;state_name&#39;].value_counts())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*RVi-HAszQ1IhA4unjScoGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*FYbpaitroc94vhOHon7B7A.png" /></figure><h3>Question: What time range does this data cover?</h3><p>All of the sites collected data on January 1st, 2018.</p><h3>Question: What are the minimum and maximum AQI values observed in the dataset?</h3><p>The minimum AQI value is 0 and the maximum AQI value is 50.</p><h3>Question: Are all states equally represented in the dataset?</h3><p>No, all states are not equally represented. California has 66 sites that reported AQI for this dataset, while states such as Delaware and Alabama have only one site that reported AQI.</p><pre>rre_states = [&#39;California&#39;,&#39;Florida&#39;,&#39;Michigan&#39;,&#39;Ohio&#39;,&#39;Pennsylvania&#39;,&#39;Texas&#39;]</pre><pre>ads_rre = ads[ads[&#39;state_name&#39;].isin(rre_states)]</pre><p>Seaborn is a simple visualization library, commonly imported as sns. Import seaborn below, then utilize a boxplot visualization from this library to compare the distributions of AQI scores by state.</p><pre>import seaborn as sns</pre><pre>sns.boxplot(x=ads_rre[&quot;state_name&quot;],y=ads_rre[&quot;aqi&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*BsHcRSQnfayEC3adhXbcnQ.png" /></figure><p>Based on the data and your visualizations, which state(s) do you suspect will be most affected by this policy<br><strong>California:</strong><br> The mean and a signficant portion of the boxplot range over 10. Michigan: While the mean is below 10, the boxplot ranges above 10.</p><p>Construct a confidence interval for the RRE state with the highest mean AQI Recall the four-step process for constructing a confidence interval:</p><p>Identify a sample statistic.</p><p>Choose a confidence level.</p><p>Find the margin of error.</p><p>Calculate the interval.</p><p>now let us construct our sample statistics</p><pre>aqi_ca = ads[ads[&#39;state_name&#39;]==&#39;California&#39;]</pre><pre>sample_mean = aqi_ca[&#39;aqi&#39;].mean()<br>sample_mean</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*1AUX1rWnU5GugzDeJ4mjVA.png" /></figure><h3>Choose your confidence level</h3><p>Choose your confidence level for your analysis. The most typical confidence level chosen is 95%; however, you can choose 90% or 99% if you want decrease or increase (respectively) your level of confidence about your result.</p><pre>confidence_level = 0.95<br>confidence_level</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/103/1*Mzw8Q3-pgD_Bj4_ZMTUMWQ.png" /></figure><h3>Find your margin of error (ME)</h3><p>Recall margin of error = z * standard error, where z is the appropriate z-value for the given confidence level. To calculate your margin of error:</p><p>Find your z-value.</p><p>Find the approximate z for common confidence levels.</p><p>Calculate your standard error estimate.</p><p>Confidence Level Z</p><p>90% 1.65 95% 1.96 99% 2.58</p><h3>Begin by identifying the z associated with your chosen confidence level.</h3><pre><br>z_value = 1.96</pre><pre>standard_error = aqi_ca[&#39;aqi&#39;].std() / np.sqrt(aqi_ca.shape[0])</pre><pre>print(&quot;standard error:&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*G9-i--6IztZjc3Q5ekPVpw.png" /></figure><pre>print(standard_error)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*yXJIZaVjzH1T4fo_cvcAag.png" /></figure><p>now let us use the above calculation to find the margin of error</p><pre>margin_of_error = standard_error * z_value</pre><pre>print(&quot;margin of error:&quot;)<br>print(margin_of_error)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*gudMHX_PP56syPyG6tMxpg.png" /></figure><h3>Calculate your interval</h3><p>Calculate both a lower and upper limit surrounding your sample mean to create your interval.</p><pre>upper_ci_limit = sample_mean + margin_of_error<br>lower_ci_limit = sample_mean - margin_of_error<br>(lower_ci_limit, upper_ci_limit)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*mGeMepMleYKuTfYFDOUeiA.png" /></figure><h3>Alternative: Construct the interval using scipy.stats.norm.interval()</h3><p>scipy presents a simpler solution to developing a confidence interval. To use this, first import the stats module from scipy.</p><pre>from scipy import stats</pre><pre>stats.norm.interval(alpha=confidence_level, loc=sample_mean, scale=standard_error)</pre><pre>&lt;ipython-input-51-e12bc462ed8f&gt;:1: DeprecationWarning: Use of keyword argument &#39;alpha&#39; for method &#39;interval&#39; is deprecated and wil be removed in SciPy 1.11.0. Use first positional argument or keyword argument &#39;confidence&#39; instead.<br>  stats.norm.interval(alpha=confidence_level, loc=sample_mean, scale=standard_err</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*pbNw7wAadnHxf7LXhCxt_w.png" /></figure><h3>Considerations</h3><p>What are key takeaways from this lab?</p><p>Based on the mean AQI for RRE states, California and Michigan were most likely to have experienced a mean AQI above 10. With California experiencing the highest sample mean AQI in the data, it appears to be the state most likely to be affected by the policy change. Constructing a confidence interval allowed you to estimate the sample mean AQI with a certain degree of confidence.</p><h3>What findings would you share with others?</h3><p>Present this notebook to convey the analytical process and describe the methodology behind constructing the confidence interval. Convey that a confidence interval at the 95% level of confidence from this sample data yielded [10.36 , 13.88], which provides the interpretation “given the observed sample AQI measurements, there is a 95% confidence that the population mean AQI for California was between 10.36 and 13.88. This range is notably greater than 10.” Share how varying the confidence level changes the interval. For example, if you varied the confidence level to 99%, the confidence interval would become [9.80 , 14.43].</p><h3>What would you convey to external stakeholders?</h3><p>Explain statistical significance at a high level. Describe California’s observed mean AQI and suggest focusing on that state. Share the result of the 95% confidence interval, describing what this means relative to the threshold of 10. Convey any potential shortcomings of this analysis, such as the short time period being referenced.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=302903ae4247" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ANALYZING THE NYC TAXI TRIP USING PYTHON]]></title>
            <link>https://medium.com/@u.victoramanze345/analyzing-the-nyc-taxi-trip-using-python-87521b7aa6e2?source=rss-f19630666fb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/87521b7aa6e2</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis-project]]></category>
            <category><![CDATA[data-analysis-with-python]]></category>
            <dc:creator><![CDATA[Victor Emeka Amanze]]></dc:creator>
            <pubDate>Wed, 17 May 2023 21:46:35 GMT</pubDate>
            <atom:updated>2023-07-04T21:03:29.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WFjY0NbPH7lv2sBp.jpg" /></figure><p>As an analyst you have been tasked with analyzing the datasets of the new york taxi trip to get insight to help improve services .<br>The dataset consist of</p><p>vendor id</p><p>tpep_pickup_datetime</p><p>tpep_dropoff_datetime</p><p>passenger_count</p><p>trip_distance</p><p>RatecodeID</p><p>store_and_fwd_flag</p><p>PULocationID</p><p>DOLocationID</p><p>payment_type</p><p>fare_amount</p><p>extra</p><p>mta_tax</p><p>tip_amount</p><p>tolls_amount</p><p>improvement_surcharge</p><p>total_amount</p><h3>First</h3><p>we import the relevant packages and libaraies for the analysis</p><p>importing numpy for numerical analysis</p><p>pandas for analysing our dataset</p><p>matplotlib and seaborn for data visualization.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><p>now we load the dataset into the dataframe</p><pre>pd.read_csv(&#39;yellow taxi trip nyc.csv&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9yIoawJ65IEljJX9LSO7RQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*2lrQnVl6YR4fz6PaNy8k2A.png" /></figure><p>now we rename the dataset</p><pre>ytt = pd.read_csv(&#39;yellow taxi trip nyc.csv&#39;)</pre><p>then we find details included in the column</p><pre>ytt.columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*VdbCsOK42bIOkaRhMkA-UA.png" /></figure><p>now we do some cleaning on our dataset .</p><pre>ytt.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*iq2bxlrWqu3A-Cp6iQvmHA.png" /></figure><p>now we find the shape of our dataframe using the shape function.</p><pre>ytt.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*gy99LT05LCj8kmUKZBbidw.png" /></figure><p>now we can see that our dataset has 22699rows and 18 columns.</p><p>so we go ahead to find the the first 10 datasets using the head function.</p><pre>ytt.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxOibK-7B9jbBfa43V89_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*sT8xXujCkP4FXO8oL22GPg.png" /></figure><p>WE use the nfo function now to know the details of our dataset.</p><pre>ytt.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*AeZcVqPkjFzU8pq8MJf4wQ.png" /></figure><p>Using the sort function to remove datasets not relevant to our analysis.</p><pre>ytt_sort = ytt.sort_values(by=[&#39;trip_distance&#39;],ascending=False) <br>ytt_sort.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgEPScNVNRefeVazFGgcBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*-zbIYH4YVRAXedZQO-6SlA.png" /></figure><p>we get the statistical insight of our dataset using the describe function.</p><pre>ytt.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Yk3UGCSfQFtrdlefkdl_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*DR1v0lo9TGanm0ral04fSA.png" /></figure><h3>Question 1:</h3><p><strong>what is the min, mean and max of your first variable ?</strong></p><h3>Answer:</h3><p>Min Mean Max</p><p><strong>total_amount -120.30 , 16.31 , 1200.29</strong></p><h3>Question 2:</h3><p>what is the min, mean, and max of your second variable?</p><h3>Answer:</h3><p>Min Mean Max trip_distance 0 , 2.91 , 33.96</p><p>we plot a histogram to observe the distribution level of our dataset.</p><pre>plt.figure(figsize=(8,6))<br>plt.xticks(fontsize=14); plt.yticks(fontsize=14)<br>ytt = ytt.sort_values(by=&#39;total_amount&#39;)<br>plt.hist(ytt[&#39;total_amount&#39;],bins=[0,20,40,60,80,100])<br>plt.title(&#39;Histogram of Total Amount&#39;,fontsize=20)<br>plt.xticks(fontsize=15); plt.yticks(fontsize=15)<br>plt.xlabel(&#39;$ amount bin&#39;,fontsize=20)<br>plt.ylabel(&#39;Count&#39;, fontsize=20)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*rVTW8cRLdj0P66x33IUkDw.png" /></figure><p>Now we can see that for the amount we have an even distribution .</p><p>now we check for trip distance to see how even it is</p><pre>plt.figure(figsize=(8,6))<br>#plt.xticks(fontsize=14); plt.yticks(fontsize=14)<br>ytt = ytt.sort_values(by=&#39;trip_distance&#39;)<br>plt.hist(ytt[&#39;trip_distance&#39;],bins=[0,5,10,20,25])<br>plt.title(&#39;Histogram of Trip Distance&#39;,fontsize=20)<br>plt.xticks(fontsize=15); plt.yticks(fontsize=15)<br>plt.xlabel(&#39;Trip distance bin&#39;,fontsize=20)<br>plt.ylabel(&#39;Count&#39;, fontsize=20)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*6h2vhdz1DiRJ3lQ5ihpL4g.png" /></figure><p>We can observe by the histogram that our amount category and trip distance is evenly distributed……</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87521b7aa6e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[using sampling statistics in python to determine the air quality index]]></title>
            <link>https://medium.com/@u.victoramanze345/using-sampling-statistics-in-python-to-determine-the-air-quality-index-39f49c5dfacd?source=rss-f19630666fb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/39f49c5dfacd</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science-projects]]></category>
            <dc:creator><![CDATA[Victor Emeka Amanze]]></dc:creator>
            <pubDate>Fri, 12 May 2023 11:27:05 GMT</pubDate>
            <atom:updated>2023-07-04T21:11:54.853Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wtb_CwFYDf2qvbQbdw_1RA.png" /></figure><p>Now as as analyst for the Environmental protection agency you been tasked to use effective sampling to analyze the data on air quality .</p><p>As said in the last project that this will be a series of projects using statistics with python to analyze this dataset and this is the 3rd project on this series .\</p><p>Go to my previous post to view the last 2 post where analysis was done with statistics and this is just one where we use sampling to derive insight</p><p>first we import all relevant libraries needed</p><p>Import pandas,</p><p>numpy,</p><p>matplotlib,</p><p>statsmodels,</p><p>and scipy.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import statsmodels.api as sm<br>from scipy import stats</pre><p>now we import the dataset needed for analysis</p><pre>pd.read_csv(&quot;c4 epa air dataset.csv&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wgTm6pHj3Bc0SAisT13tcg.png" /></figure><p>we rename the dataset</p><pre>ads = pd.read_csv(&quot;c4 epa air dataset.csv&quot;)</pre><p>we use the head function to view the first 10 set of data in our dataset</p><pre>ads.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yyUev7zBPS0QkbBnrw_Epg.png" /></figure><p>based on the first few rows of data seen above that As the units_of_measure column contains parts per million, you can infer that the aqi values are measured in parts per million.</p><p>we use the describe(include=’all’) to get the description of the data in the DataFrames</p><pre>ads.describe(include=&#39;all&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aO1x7w1zpGkqFSmSAnBMLQ.png" /></figure><p>Based on the table of descriptive statistics generated above, what do you notice about the count value for the aqi column?**</p><p>The count value for the aqi column is 260. This means there are 260 AQI measurements represented in this dataset.</p><p>Now, use the mean() function on the aqi column and assign the value to a variable population_mean. The value should be the same mean value the describe() function produced for the ‘aqi’ column.</p><pre>population_mean = ads[&#39;aqi&#39;].mean()</pre><p><strong>Sample with replacement</strong></p><p>First, name a new variable sampled_data. Then, set the arguments for the sample function N, sample size, equal to 50. Set replace equal to “True” to specify sampling with replacement. For random_state, choose an arbitrary number for random seed. Make that arbitrary number 42.</p><pre>sampled_data = ads.sample(n=50, replace=True, random_state=42)</pre><pre>sampled_data.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FCp5KTxW2a4UAyWSlhOZVA.png" /></figure><pre>sample_mean = sampled_data[&#39;aqi&#39;].mean()</pre><p>Apply the central limit theorem Imagine repeating the the earlier sample with replacement 10,000 times and obtaining 10,000 point estimates of the mean. In other words, imagine taking 10,000 random samples of 50 AQI values and computing the mean for each sample. According to the central limit theorem, the mean of a sampling distribution should be roughly equal to the population mean. Follow the steps below to compute the mean of the sampling distribution with 10,000 samples.</p><p>Create an empty list and assign it to a variable called estimate_list. Iterate through a for loop 10,000 times. To do this, make sure to utilize the range() function to generate a sequence of numbers from 0 to 99,999. In each iteration of the loop, use the sample() function to take a random sample (with replacement) of 50 AQI values from the population. Do not set random_state to a value. Use the list append() function to add the value of the sample mean to each item in the list.</p><pre>estimate_list = []<br>for i in range(10000):<br>    estimate_list.append(ads[&#39;aqi&#39;].sample(n=50,replace=True).mean())</pre><p>Next, create a new DataFrame from the list of 10,000 estimates. Name the new variable estimate_df.</p><pre>estimate_df = pd.DataFrame(data={&#39;estimate&#39;: estimate_list})<br>estimate_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*DSfRmVueLkKg1t2gmlAXvQ.png" /></figure><p>Next, compute the mean() of the sampling distribution of 10,000 random samples and store the result in a new variable mean_sample_means</p><pre>mean_sample_means = estimate_df[&#39;estimate&#39;].mean()<br><br>mean_sample_means</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*OSlGyrZle454hk1lvTHevQ.png" /></figure><p>How are the central limit theorem and random sampling (with replacement) related?</p><p>Random sampling with replacement is related to the central limit theorem because it means you are drawing observations independently from a population. The central limit theorem states that if a sample size is large enough and the observations are drawn independently — or with replacement — the sampling distribution of the sample mean is approximately the normal distribution. Furthermore, the mean parameter is the population mean and the variance parameter is the standard error.</p><p>Output the distribution of these estimates using a histogram. This provides an idea of the sampling distribution.</p><pre>estimate_df[&#39;estimate&#39;].hist()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*MUrNRzdLXO83cJb0KFo3Jg.png" /></figure><h3><strong>Calculate the standard error</strong></h3><p>Calculate the standard error of the statistic. The standard error of a statistic is the standard deviation of the sampling distribution associated with the statistic. It provides a numerical measure of sampling variability and answers the question: How far is a statistic based on one particular sample from the typical value of the statistic?</p><pre>standard_error = estimate_df[&#39;estimate&#39;].std()<br>standard_error</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*enAOUwhPEXeBGJYC1to0bQ.png" /></figure><h3><strong>Visualize the relationship between the sampling and normal distributions</strong></h3><p>Visualize the relationship between your sampling distribution of 10,000 estimates and the normal distribution. The code below overlays the density curve of the normal distribution described in the theorem on top of the histogram of the sampling distribution obtained by repeated sampling. The solid green line in the graph is the population mean and the red dashed line is the estimate.</p><pre>plt.hist(estimate_df[&#39;estimate&#39;], bins=25, density=True, alpha=0.4, label = &quot;histogram of sample means of 10000 random samples&quot;)<br>xmin, xmax = plt.xlim()<br>x = np.linspace(xmin, xmax, 100) # generate a grid of 100 values from xmin to xmax.<br>p = stats.norm.pdf(x, population_mean, standard_error)<br>plt.plot(x, p, &#39;k&#39;, linewidth=2, label = &#39;normal curve from central limit theorem&#39;)<br>plt.axvline(x=population_mean, color=&#39;g&#39;, linestyle = &#39;solid&#39;, label = &#39;population mean&#39;)<br>plt.axvline(x=sample_mean, color=&#39;r&#39;, linestyle = &#39;--&#39;, label = &#39;sample mean of the first random sample&#39;)<br>plt.axvline(x=mean_sample_means, color=&#39;b&#39;, linestyle = &#39;:&#39;, label = &#39;mean of sample means of 10000 random samples&#39;)<br>plt.title(&quot;Sampling distribution of sample mean&quot;)<br>plt.xlabel(&#39;sample mean&#39;)<br>plt.ylabel(&#39;density&#39;)<br>plt.legend(bbox_to_anchor=(1.04,1))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8696Jo3PHmaNnIJn4lUhA.png" /></figure><h3><strong>What insights did you gain from the sampling distribution above?</strong></h3><p>The histogram of the sampling distribution is well-approximated by the normal distribution described by the central limit theorem. The estimate based on one particular sample (red dashed line) is off-center. This is expected due to sampling variability. The red dashed line would be in a different location if epa_data.sample(n=50, replace=True, random_state=42) had a different value for random_state. The population mean (green solid line) and the mean of the sample means (blue dotted line) overlap, meaning that they are essentially equal to each other.</p><h3>Considerations</h3><h3><strong>What are some key takeaways that you learned from this lab?</strong></h3><p>Sampling with replacement on a dataset leads to duplicate rows. Sample means are different from population means due to sampling variability. The central limit theorem helps describe the sampling distribution of the sample mean for many different types of datasets.</p><h3><strong>What findings would you share with others?</strong></h3><p>The mean AQI in a sample of 50 observations was below 100 in a statistically significant sense (at least 2–3 standard errors away). For reference, AQI values at or below 100 are generally thought of as satisfactory. This notebook didn’t examine values outside the “satisfactory” range so analysis should be done to investigate unhealthy AQI values.</p><h3><strong>What would you convey to external stakeholders?</strong></h3><p>Carbon monoxide levels are satisfactory in general. Funding should be allocated to further investigate regions with unhealthy levels of carbon monoxide and improve the conditions in those regions………</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39f49c5dfacd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>