<?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 Varun Srivatsa on Medium]]></title>
        <description><![CDATA[Stories by Varun Srivatsa on Medium]]></description>
        <link>https://medium.com/@varunsrivatsa27?source=rss-35df1a22f691------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*j3YpXHyqaCl1GHZBVv5BNg.jpeg</url>
            <title>Stories by Varun Srivatsa on Medium</title>
            <link>https://medium.com/@varunsrivatsa27?source=rss-35df1a22f691------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:16:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@varunsrivatsa27/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[10-Year Forecast: Factors that could Influence Home Prices in the US.]]></title>
            <link>https://medium.com/@varunsrivatsa27/10-year-forecast-factors-that-could-influence-home-prices-in-the-us-bba4947feb1?source=rss-35df1a22f691------2</link>
            <guid isPermaLink="false">https://medium.com/p/bba4947feb1</guid>
            <category><![CDATA[usa]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[case-study]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Varun Srivatsa]]></dc:creator>
            <pubDate>Tue, 04 Oct 2022 04:36:05 GMT</pubDate>
            <atom:updated>2022-10-04T04:46:41.707Z</atom:updated>
            <content:encoded><![CDATA[<p>Since real estate consists of both the property and the land on which it is built, it is considered to be a tangible asset. This is why it is such a large part of most people’s wealth. Americans are especially affected by this.</p><p>The property and the land are just as immune as the stocks and bonds we avoid investing in; the price of each is highly changeable. The connection lies in the fact that their price is so variable. When demand increases, the price goes up; when supply increases, the price goes down. See the diagram below and reconsider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7yP6zAfFwC3GLRfaW4Nczg.png" /></figure><p>The MECE framework is used to create an issue tree, as shown in the diagram. If you’re not a consultant, don’t worry; you don’t need to know what MECE means (for non-consultants only). I’ll elucidate, and you’ll see how this idea can assist you in life.</p><h4>So what is the MECE framework?</h4><p>Management consulting firms like McKinsey utilize this framework to divide up big issues for their customers. MECE is a method of grouping information into elements that are mutually exclusive (ME) and collectively exhaustive (CE). In other words, it is a process by which information — ideas, topics, issues, solutions — is arranged or, put in “MECE buckets,” with no overlapping between buckets and with each item having a place in one bucket only (ME), and with the buckets including all possible items relevant to the context.</p><p>We now understood the MECE framework, but we still must figure out how to represent it properly. In other words, we know how to divide up the issue, but we must devise a method for presenting it in an organized and meaningful way for our customers (in my case, interviewers). Here are three suggestions for how to tackle the problem comprehensively:</p><ol><li><strong>Issue tree:</strong> Deals with the issue of the clients, where we break down the problem into smaller buckets and lead to the solution for each bucket.</li><li><strong>Decision tree:</strong> Decides on the correct decision to be made, where we break down the choice into probable more fundamental choices and reach a potential answer.</li><li><strong>Hypothesis tree:</strong> It is an answer-first approach, where we define the problem around the hypothesis. This is mainly down when we have prior knowledge about the field.</li></ol><p>You can find out more about these structures by referring to the provided <a href="https://www.mbacrystalball.com/blog/strategy/mece-framework/"><strong>link</strong></a>. The structures listed above are not necessarily what would be seen in most scenarios, including this one. You must combine them to create a representation that fits your situation or build a new structure from scratch. Because we are looking for factors that influence the housing market in the United States, this is neither a problem nor a decision. Therefore, I created a tree that divides the elephant in the room into smaller issues, leading to the hypothesis that those issues affect housing prices.</p><h4>Now, let’s get started.</h4><p>The tree diagram shown above is too big and hard to read. Let’s go through it step by step to understand it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*Xu_Si8GZ-2PISdcf6R0GLQ.png" /></figure><p>Housing prices are determined by the classic economic factors of <strong>supply</strong> and <strong>demand</strong>, at least on the first level. During recessions, houses may be abundant for sale, but no one wants them (2008 recession, are you there?). Alternatively, if demand is higher than supply, buyers compete for fewer houses, boosting the chance that they will pay more than the asking price.</p><h4>Supply</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-HYo90zNVGNkpjh6AqFIg.png" /></figure><p>The supply of the houses is determined by two variables, “permission to build” and “time and cost to build,” which are made up of numerous other variables. Finally, the leaf nodes are the hypothesis that either supports the supply or opposes it.</p><p>From the figure, we can see that most of the explanations support an increase in supply. However, this does not necessarily mean the price will decrease. There are a couple of reasons for this:</p><ol><li>Not all the hypotheses are equally weighted, which means some would matter more than others based on what’s happening and when. But that’s not all</li><li>Remember, supply and demand are relative — so you should find out what the current demand for housing is to make a more educated guess as to which hypothesis you should give more importance to make your final call.</li></ol><h4>Demand</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MPbygXwS6qRqD5QcK0rpg.png" /></figure><p>The demand for houses depends on wages, trends, and other smaller factors.</p><p>A lot of factors go into controlling demand. These can include wages, trends, and credit availability as well as recessions and interest rates. But why do these factors vary? It’s due to inflation and, in turn, a result of excessive federal spending and a weak economy. And those are already mentioned in the deeper levels of this sub-tree. This means any more additions to it would make it non-MECE.</p><h4>Supply vs Demand</h4><p>Now that we have both perspectives, we can give higher weights to our hypotheses and then predict the outcome of these two theories. It’s hard to know who will come out on top, but the dynamics of supply and demand in the markets seem to be headed in a positive direction.</p><p><strong>One of the many factors to consider is urgency; how fast will this hypothesis be realized? Is it too soon to tell?</strong></p><p>In the case of demand, all the hypotheses have an immediate impact. For example, trends change fast, and due to covid, the whole world was pushed into the new normal of working remotely. Same for the wage growth, the demographic is affecting it right now, and inflation and recession are building up at this instant.</p><p>But in the case of supply, there is only one factor with hypotheses that have an immediate impact, that too against the growth of supply, which is labor. All other factors supporting supply growth are slow growing and will have an impact shortly.</p><p><strong>In other words, it will take time to build houses, even with the latest technology, and even if the process is easier. But when in contrast, fluctuations in demand are immediate so prices for houses will increase greatly!</strong></p><p>What will happen in the future? Well, to answer this question, there’s a concept called Price Equilibrium which we need to briefly understand.</p><h4>Let’s talk about it!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7wZma0Ol0VqA1VVvJt3hw.jpeg" /><figcaption><em>In a competitive market, equilibrium price and quantity are determined by the intersection of the supply and demand curves.</em></figcaption></figure><p>The trends in supply and demand can be summarized from the curves shown above, and if you’re unsure, no worries. Head on over to this <a href="https://saylordotorg.github.io/text_macroeconomics-theory-through-applications/s08-01-housing-supply-and-demand.html"><strong>link</strong></a> and take a look for yourself — you’ll be right on track in no time!</p><p>As you can see, the market demand curve shows a downward trend with an increase in the number of houses, and the supply curve does the exact opposite. The point where the two curves meet is called the equilibrium quantity, where the price will settle.</p><p>At an equilibrium price, suppliers of goods can sell as much as they want, and demanders of the good can buy as much output that suits their needs. The amount supplied and demanded will not disappoint any party.</p><p>And the housing market will likely reach equilibrium in a few years when prices are so high that bidders can’t afford them and sellers have to lower their asking price. This situation is somewhat similar to the great recession in the housing market. It all started when people couldn’t enter into a lot of risky deals and prices went down and eventually crashed.</p><p>Great! I hope this story was helpful😁. Thank you Rohit Arora for bringing me up to speed on this and being really helpful. His <a href="https://medium.com/@rohit18115/the-housing-market-in-the-united-states-for-the-next-decade-c234100939a7"><strong>article</strong></a> was a great resource.</p><p>Thanks for reading! Check out my other <a href="https://medium.com/@varunsrivatsa27"><strong>articles</strong></a> too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bba4947feb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Analysis with Python — Model Evaluation — Part 4]]></title>
            <link>https://medium.com/@varunsrivatsa27/data-analysis-with-python-model-evaluation-part-4-1f2a46d4781a?source=rss-35df1a22f691------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f2a46d4781a</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Varun Srivatsa]]></dc:creator>
            <pubDate>Mon, 26 Sep 2022 12:33:09 GMT</pubDate>
            <atom:updated>2022-09-26T12:33:09.096Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Analysis with Python — Model Evaluation — Part 4</h3><p>Model evaluation tells us how our model performs in the real world. In the previous <a href="https://medium.com/@varunsrivatsa27/data-analysis-with-python-model-development-part-3-d75df5480ab3"><strong>part</strong></a>, we learned about in-sample evaluation. In-sample evaluation tells us how our model fits the data already given to training it. It does not give us an estimate of how well the trained model can predict new data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3mhNrSq_FrA_lFzv" /><figcaption>Photo by <a href="https://unsplash.com/@alinnnaaaa?utm_source=medium&amp;utm_medium=referral">Alina Grubnyak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The solution is to split our data and use the in-sample or training data to train the model. The rest of the data, called Test data, is used as out-of-sample data. This data is then used to approximate, how the model performs in the real world. Separating data into training and testing sets is an important part of model evaluation. When we split a dataset, usually the larger portion of data is used for training and a smaller part is used for testing. For example, we can use 70 percent of the data for training. We can then use 30 percent for testing. We use a training set to build a model and discover predictive relationships. We then use a testing set to evaluate model performance. When we have completed testing our model, we should use all the data to train the model.</p><p>A popular function, in the scikit-learn package for splitting datasets, is the train test split function. This function randomly splits a dataset into training and testing subsets.</p><h3><strong>Let’s get started.</strong></h3><p><strong><em>Note</em></strong><em>: For a better understanding of the data and the steps I have taken to clean it and for model development, I highly recommend reading </em><a href="https://medium.com/@varunsrivatsa27/data-analysis-with-python-data-wrangling-part-1-dc571ab55259"><strong><em>Data Analysis with Python — Data Wrangling — Part 1</em></strong></a>, <a href="https://medium.com/@varunsrivatsa27/data-analysis-with-python-exploratory-data-analysis-eda-part-2-c2460874d49f"><strong><em>Data Analysis with Python — Exploratory Data Analysis (EDA) — Part 2</em></strong></a>,<strong><em> and </em></strong><a href="https://medium.com/@varunsrivatsa27/data-analysis-with-python-model-development-part-3-d75df5480ab3"><strong><em>Data Analysis with Python — Model Development — Part 3</em></strong></a><strong><em>.</em></strong></p><p>For your reference, the Notebook is also available <a href="https://github.com/NXture/automobile-price-prediction/blob/master/Model-Evaluation-and-Refinement.ipynb"><strong>here</strong></a>.</p><h4>Setup —Let’s first Import Data</h4><pre>import pandas as pd<br>import numpy as np</pre><pre># Import clean data<br>path = &#39;https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DA0101EN-SkillsNetwork/labs/Data%20files/module_5_auto.csv&#39;</pre><pre>df = pd.read_csv(path)</pre><p>Save it as a .csv file for your reference.</p><pre>df.to_csv(&quot;part4.csv&quot;)</pre><p>Next, let’s only use numeric data:</p><pre>df = df._get_numeric_data()<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OnVTGxwPA9WnIu7x8G2ICQ.png" /></figure><p>Following are the libraries for plotting:</p><pre>from ipywidgets import interact, interactive, fixed, interact_manual</pre><h3>Functions for Plotting</h3><pre>import matplotlib as plt<br>import seaborn as sns</pre><p><strong>Function 1:</strong></p><pre>def DistributionPlot(RedFunction, BlueFunction, RedName, BlueName, Title):<br>  width = 12<br>  height = 10<br>  plt.figure(figsize=(width, height))</pre><pre>  ax1 = sns.distplot(RedFunction, hist=False, color=&quot;r&quot;, label=RedName)<br>  ax2 = sns.distplot(BlueFunction, hist=False, color=&quot;b&quot;, label=BlueName, ax=ax1)<br>  <br>  plt.title(Title)<br>  plt.xlabel(&quot;Price (in dollars)&quot;)<br>  plt.ylabel(&quot;Proportion of Cars&quot;)<br>  <br>  plt.show()<br>  plt.close()</pre><p><strong>Function 2:</strong></p><pre>def PollyPlot(xtrain, xtest, y_train, y_test, lr, poly_transform):<br>  width = 12<br>  height = 10<br>  plt.figure(figsize=(width, height))<br>  <br>  #training data<br>  #testing data<br>  #lr: linear regression object<br>  #poly_transform: polynomial transformation object<br>  <br>  xmax=max([xtrain.values.max(), xtest.values.max()])<br>  xmin=min([xtrain.values.min(), xtest.values.min()])</pre><pre>  x=np.arrange(xmin, xmax, 0.1)<br>  plt.plot(xtrain, y_train, &quot;ro&quot;, label=&quot;Training Data&quot;)<br>  plt.plot(xtest, y_test, &quot;go&quot;, label=&quot;Test Data&quot;)<br>  plt.plot(x, lr.predict(poly_tranform.fit_transform(x.reshape(-1, 1))), label=&quot;Predicted Function&quot;)<br>  plt.ylim([-10000, 60000])<br>  plt.ylabel(&quot;Price&quot;)<br>  plt.legend()</pre><h3>Part 1: Training and Testing</h3><p>An important step in testing your model is to split your data into training and testing data. We will place the target data price in a separate data frame y_data:</p><pre>y_data = df[&quot;price&quot;]</pre><p>Drop price data in data frame x_data:</p><pre>x_data=df.drop(&quot;price&quot;, axis=1)</pre><p>Now, we randomly split our data into training and testing data using the function train_test_split.</p><pre>from sklearn.model_selection import train_test_split</pre><pre>x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.10, random_state=1)</pre><pre>print(&quot;number of test samples:&quot;, x_test.shape[0])<br>print(&quot;number of training samples:&quot;, x_train.shape[0])</pre><p><strong>Output:</strong></p><p>number of test samples : 21</p><p>number of training samples : 180</p><p>The test_size parameter sets the proportion of data that is split into the testing set. In the above, the testing set is 10% of the total dataset.</p><p>Let’s use the function “train_test_split” to split up the dataset such that 40% of the data samples will be utilized for testing. Set the parameter “random_state” equal to zero. The output of the function should be the following: “x_train1”, “x_test1”, “y_train1”, and “y_test1”.</p><pre>x_train1, x_test1, y_train1, y_test1 = train_test_split(x_data, y_data, test_size=0.4, random_state=0)</pre><pre>print(&quot;number of test samples :&quot;, x_test1.shape[0])<br>print(&quot;number of training samples :&quot;, x_train1.shape[0])</pre><p><strong>Output:</strong></p><p>number of test samples : 81</p><p>number of training samples : 120</p><p>Let’s import LinearRegression from the module linear_model.</p><pre>from sklearn.linear_model import LinearRegression</pre><p>We create a Linear Regression object:</p><pre>lre=LinearRegression()</pre><p>We fit the model using the feature “horsepower”:</p><pre>lre.fit(x_train[[&quot;horsepower&quot;]], y_train)</pre><p>Let’s calculate the R² on the test data:</p><pre>lre.score(x_test[[&quot;horsepower&quot;]], y_test)</pre><p><strong>Output:</strong> 0.36358755750788263</p><p>We can see the R² is much smaller using the test data compared to the training data.</p><pre>lre.score(x_train[[&quot;horsepower&quot;]], y_train)</pre><p><strong>Output:</strong> 0.6619724197515104</p><p>Let’s find the R² on the test data using 40% of the dataset for testing.</p><pre>x_train1, x_test1, y_train1, y_test1 = train_test_split(x_data, y_data, test_size=0.4, random_state=0)<br>lre.fit(x_train1[[&quot;horsepower&quot;]],y_train1)<br>lre.score(x_test1[[&quot;horsepower&quot;]],y_test1)</pre><p><strong>Output:</strong> 0.7139364665406973</p><p>Sometimes you do not have sufficient testing data; as a result, you may want to perform cross-validation. Let’s go over several methods that you can use for cross-validation.</p><h4>Cross-Validation Score</h4><p>Let’s import model_selection from the module cross_val_score.</p><pre>from sklearn.model_selection import cross_val_score</pre><p>We input the object, the feature (“horsepower”), and the target data (y_data). The parameter “cv” determines the number of folds. In this case, it is 4.</p><pre>Rcross = cross_val_score(lre, x_data[[&quot;horsepower&quot;]], y_data, cv=4)</pre><p>The default scoring is R². Each element in the array has the average R² value for the fold:</p><pre>Rcross</pre><p><strong>Output:</strong> array([0.7746232, 0.51716687, 0.74785353, 0.04839605])</p><p>We can calculate the average and standard deviation of our estimate:</p><pre>print(&quot;The mean of the folds are&quot;, Rcross.mean(), &quot;and the standard deviation is&quot;, Rcross.std())</pre><p><strong>Output:</strong> The mean of the folds are 0.522009915042119 and the standard deviation is 0.291183944475029</p><p>We can use a negative squared error as a score by setting the parameter “scoring” metric to “neg_mean_squared_error”.</p><pre>-1 * cross_val_score(lre, x_data[[&quot;horsepower&quot;]], y_data, cv=4, scoring=&quot;neg_mean_squared_error&quot;)</pre><p><strong>Output:</strong> array([20254142.84026702, 43745493.2650517, 12539630.34014931, 17561927.7224759])</p><p>Let’s calculate the average R² using two folds, then find the average R² for the second fold utilizing the “horsepower” feature:</p><pre>Rc=cross_val_score(lre, x_data[[&quot;horsepower&quot;]], y_data, cv=2)<br>Rc.mean()</pre><p><strong>Output:</strong> 0.5166761697127429</p><p>You can also use the function “cross_val_predict” to predict the output. The function splits up the data into the specified number of folds, with one fold for testing and the other folds used for training. First, import the function:</p><pre>from sklearn.model_selection import cross_val_predict</pre><p>We input the object, the feature <strong>“horsepower”,</strong> and the target data <strong>y_data</strong>. The parameter “cv” determines the number of folds. In this case, it is 4. We can produce an output:</p><pre>yhat = cross_val_predict(lre, x_data[[&quot;horsepower&quot;]], y_data, cv=4)<br>yhat[0:5]</pre><p><strong>Output:</strong> array([14141.63807508, 14141.63807508, 20814.29423473, 12745.03562306, 14762.35027598])</p><h3>Part 2: Overfitting, Underfitting, and Model Selection</h3><p>It turns out that the test data sometimes referred to as the “out-of-sample data”, is a much better measure of how well your model performs in the real world. One reason for this is overfitting.</p><p>Let’s go over some examples. It turns out these differences are more apparent in Multiple Linear Regression and Polynomial Regression so we will explore overfitting in that context.</p><p>Let’s create Multiple Linear Regression objects and train the model using “horsepower”, “curb-weight”, “engine-size”, and “highway-mpg” as features.</p><pre>lr = LinearRegression()<br>lr.fit(x_train[[&quot;horsepower&quot;, &quot;curb-weight&quot;, &quot;engine-size&quot;, &quot;highway-mpg&quot;]], y_train)</pre><p>Prediction using training data:</p><pre>yhat_train = lr.predict(x_train[[&quot;horsepower&quot;, &quot;curb-weight&quot;, &quot;engine-size&quot;, &quot;highway-mpg&quot;]])<br>yhat_train[0:5]</pre><p><strong>Output:</strong> array([7426.6731551, 28323.75090803, 14213.38819709, 4052.34146983, 34500.19124244])</p><p>Prediction using test data:</p><pre>yhat_test = lr.predict(x_test[[&quot;horsepower&quot;, &quot;curb-weight&quot;, &quot;engine-size&quot;, &quot;highway-mpg&quot;]])<br>yhat_test[0:5]</pre><p><strong>Output:</strong> array([11349.35089149, 5884.11059106, 11208.6928275, 6641.07786278, 15565.79920282])</p><p>Let’s perform some model evaluation using our training and testing data separately. First, we import the seaborn and matplotlib library for plotting.</p><pre>import matplotlib.pyplot as plt<br>%matplotlib inline<br>import seaborn as sns</pre><p>Let’s examine the distribution of the predicted values of the training data.</p><pre>Title = &#39;Distribution  Plot of  Predicted Value Using Training Data vs Training Data Distribution&#39;</pre><pre>DistributionPlot(y_train, yhat_train, &quot;Actual Values (Train)&quot;, &quot;Predicted Values (Train)&quot;, Title)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*onf1M675TmC8zVZ3ndKtBg.png" /><figcaption>The plot of predicted values using the training data compared to the actual values of the training data.</figcaption></figure><p>So far, the model seems to be doing well in learning from the training dataset. But what happens when the model encounters new data from the testing dataset? When the model generates new values from the test data, we see the distribution of the predicted values is much different from the actual target values.</p><pre>Title=&#39;Distribution  Plot of  Predicted Value Using Test Data vs Data Distribution of Test Data&#39;</pre><pre>DistributionPlot(y_test,yhat_test,&quot;Actual Values (Test)&quot;,&quot;Predicted Values (Test)&quot;,Title)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*yTcnHtsxujw9K_0QT9BBGg.png" /><figcaption>The plot of predicted value using the test data compared to the actual values of the test data.</figcaption></figure><p>Comparing Figure 1 and Figure 2, it is evident that the distribution of the test data in Figure 1 is much better at fitting the data. This difference in Figure 2 is apparent in the range of 5000 to 15,000. This is where the shape of the distribution is extremely different. Let’s see if polynomial regression also exhibits a drop in prediction accuracy when analyzing the test dataset.</p><pre>from sklearn.preprocessing import PolynomialFeatures</pre><h4>Overfitting</h4><p>Overfitting occurs when the model fits the noise, but not the underlying process. Therefore, when testing your model using the test set, your model does not perform as well since it is modeling noise, not the underlying process that generated the relationship. Let’s create a degree 5 polynomial model.</p><p>Let’s use 55% of the data for training and the rest for testing:</p><pre>x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.45, random_state=0)</pre><p>We will perform a degree 5 polynomial transformation on the feature “horsepower”.</p><pre>pr = PolynomialFeatures(degree=5)<br>x_train_pr = pr.fit_transform(x_train[[&quot;horsepower&quot;]])<br>x_test_pr = pr.fit_transform(x_test[[&quot;horsepower&quot;]])<br>pr</pre><p>Now, let’s create a Linear Regression model “poly” and train it.</p><pre>poly = LinearRegression()<br>poly.fit(x_train_pr, y_train)</pre><p>We can see the output of our model using the method “predict”. We assign the values to “yhat”.</p><pre>yhat = poly.predict(x_test_pr)<br>yhat[0:5]</pre><p><strong>Output:</strong> array([6728.65566037, 7307.9878638, 12213.7877412, 18893.24796457, 19995.95185894])</p><p>Let’s take the first five predicted values and compare them to the actual targets.</p><pre>print(&quot;Predicted values:&quot;, yhat[0:4])<br>print(&quot;True Values:&quot;, y_test[0:4].values)</pre><p><strong>Output:</strong> Predicted values: [6728.65566037 7307.9878638 12213.7877412 18893.24796457]</p><p>True values: [6295. 10698. 13860. 13499.]</p><p>We will use the function “PollyPlot” that we defined at the beginning of the post to display the training data, testing data, and the predicted function.</p><pre>PollyPlot(x_train[[&quot;horsepower&quot;]], x_test[[&quot;horsepower&quot;]], y_train, y_test, poly, pr)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*Qk-sU-TPnuNmGk1NBbCvsA.png" /><figcaption>A polynomial regression model where red dots represent training data, green dots represent test data, and the blue line represents the model prediction.</figcaption></figure><p>We see that the estimated function appears to track the data but at around 200 horsepower, the function begins to diverge from the data points.</p><p>R² of the training data:</p><pre>poly.score(x_train_pr, y_train)</pre><p><strong>Output:</strong> 0.5567716902121724</p><p>R² of the test data:</p><pre>poly.score(x_test_pr, y_test)</pre><p><strong>Output:</strong> -29.87134054062532</p><p>We see the R² for the training data is 0.5567 while the R² on the test data was -29.87. The lower the R², the worse the model. A negative R² is a sign of overfitting.</p><p>Let’s see how the R² changes on the test data for different order polynomials and then plot the results:</p><pre>Rsqu_test = []</pre><pre>order = [1, 2, 3, 4]<br>for n in order:<br>  pr = PolynomialFeatures(degree = n)<br>  x_train_pr = pr.fit_transform(x_train[[&quot;horsepower&quot;]])<br>  x_test_pr = pr.fit_transform(x_test[[&quot;horsepower&quot;]])<br>  lr.fit(x_train_pr, y_train)<br>  Rsqu_test.append(lr.score(x_test_pr, y_test))</pre><pre>plt.plot(order, Rsqu_test)<br>plt.xlabel(&quot;order&quot;)<br>plt.ylabel(&quot;R^2&quot;)<br>plt.title(&quot;R^2 Using Test Data&quot;)<br>plt.text(3, 0.75, &quot;Maximun R^2&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*8tDMd3Z_Svcit143jymCeA.png" /><figcaption>Text(3, 0.75, &quot;Maximun R^2&quot;)</figcaption></figure><p>We see the R² gradually increase until an order three polynomial is used. Then, the R² dramatically decreases at an order four polynomial.</p><p>The following function will be used in the next section. Please run the cell below.</p><pre>def f(order, test_data):<br>  x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=test_data, random_state=0)<br>  pr = PolynomialFeatures(degree = order)<br>  x_train_pr = pr.fit_transform(x_train[[&quot;horsepower&quot;]])<br>  x_test_pr = pr.fit_transform(x_test[[&quot;horsepower&quot;]])<br>  poly = LinearRegression()<br>  poly.fit(x_train_pr, y_train)<br>  PollyPlot(x_train[[&quot;horsepower&quot;]], x_test[[&quot;horsepower&quot;]], y_train, y_test, poly, pr)</pre><p>The following interface allows you to experiment with different polynomial orders and different amounts of data.</p><pre>interact(f, order=(0, 6, 1), test_data=(0.05, 0.95, 0.05))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*Qwqi2Vw5AU_gZDHvBznKLw.png" /><figcaption>interface to experiment with different polynomial orders and data.</figcaption></figure><p>Now, let’s perform polynomial transformations with more than one feature. For that, create a “PolynomialFeatures” object “pr1” of degree two.</p><pre>pr1=PolynomialFeatures(degree=2)</pre><p>Followed by transforming the training and testing samples for the features “horsepower”, “curb-weight”, “engine-size”, and “highway-mpg” by using the “fit_transform” method.</p><pre>x_train_pr1= pr1.fit_transform(x_train[[&quot;horsepower&quot;, &quot;curb-weight&quot;, &quot;engine-size&quot;, &quot;highway-mpg&quot;]])</pre><pre>x_test_pr1= pr1.fit_transform(x_test[[&quot;horsepower&quot;, &quot;curb-weight&quot;, &quot;engine-size&quot;, &quot;highway-mpg&quot;]])</pre><p>Let’s check the dimensions of the new feature.</p><pre>x_train_pr1.shape</pre><p><strong>Output:</strong> (110, 15)</p><p>Next, create a linear regression model “poly1”. Then train the object using the method “fit” using the polynomial features.</p><pre>poly1=LinearRegression().fit(x_train_pr1, y_train)</pre><p>Use the method “predict” to predict an output on the polynomial features, then use the function “DistributionPlot” to display the distribution of the predicted test output vs. the actual test data.</p><pre>yhat_test1=poly1.predict(x_test_pr1)</pre><pre>Title=&quot;Distribution Plot of Predicted Value Using Test Data vs Data Distribution of Test Data&quot;</pre><pre>DistributionPlot(y_test, yhat_test1, &quot;Actual Values (Test)&quot;, &quot;Predicted Values (Test)&quot;, Title)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*pfu8CsabjZy8xPWlfOg8Yg.png" /></figure><p>Using the distribution plot above, we can see that the predicted value is higher than the actual value for cars where the price $10,000 range, conversely the predicted price is lower than the price cost in the #30,000 to $40,000 range. As such the model is not as accurate in these ranges.</p><h3>Part 3: Ridge Regression</h3><p>In this section, we will review Ridge Regression and see how the parameter alpha changes the model. Just a note, here our test data will be used as validation data.</p><p>Let’s perform a degree two polynomial transformation on our data.</p><pre>pr=PolynomialFeatures(degree=2)</pre><pre>x_train_pr=pr.fit_transform(x_train[[&#39;horsepower&#39;, &#39;curb-weight&#39;, &#39;engine-size&#39;, &#39;highway-mpg&#39;,&#39;normalized-losses&#39;,&#39;symboling&#39;]])</pre><pre>x_test_pr=pr.fit_transform(x_test[[&#39;horsepower&#39;, &#39;curb-weight&#39;, &#39;engine-size&#39;, &#39;highway-mpg&#39;,&#39;normalized-losses&#39;,&#39;symboling&#39;]])</pre><p>Let’s import Ridge from the module linear models.</p><pre>from sklearn.linear_model import Ridge</pre><p>Let’s create a Ridge regression object, setting the regularization parameter (alpha) to 0.1.</p><pre>RidgeModel = Ridge(alpha=1)</pre><p>Like regular regression, you can fit the model using the method fit.</p><pre>RidgeModel.fit(x_train_pr, y_train)</pre><p>Similarly, you can obtain a prediction:</p><pre>yhat = RidgeModel.predict(x_test_pr)</pre><p>Let’s compare the first five predicted samples to our test set:</p><pre>print(&quot;predicted:&quot;, yhat[0:4])<br>print(&quot;test set:&quot;, y_test[0:4].values)</pre><p><strong>Output:</strong> predicted: [6570.82441941 9636.24891471 20949.92322737 19403.60313256]</p><p>test set: [6295. 10698. 13860. 13499.]</p><p>We select the value of alpha that minimizes the test error. To do so, we can use a for loop. We have also created a progress bar to see how many iterations we have completed so far.</p><pre>from tqdm import tqdm</pre><pre>Rsqu_test = []<br>Rsqu_train = []<br>dummy1 = []<br>Alpha = 10 * np.array(range(0,1000))<br>pbar = tqdm(Alpha)</pre><pre>for alpha in pbar:<br>  RigeModel = Ridge(alpha=alpha)<br>  RigeModel.fit(x_train_pr, y_train)<br>  test_score, train_score = RigeModel.score(x_test_pr, y_test), RigeModel.score(x_train_pr, y_train)<br>  pbar.set_postfix({&quot;Test Score&quot;: test_score, &quot;Train Score&quot;: train_score})<br>  Rsqu_test.append(test_score)<br>  Rsqu_train.append(train_score)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*c2EYqInsSZSbynwOb-kTng.png" /></figure><p>We can plot out the value of R² for different alphas:</p><pre>width = 12<br>height = 10<br>plt.figure(figsize=(width, height))</pre><pre>plt.plot(Alpha, Rsqu_test, label=&quot;validation data&quot;)<br>plt.plot(Alpha, Rsqu_train, &quot;r&quot;, label=&quot;training Data&quot;)<br>plt.xlabel(&quot;alpha&quot;)<br>plt.ylabel(&quot;R^2&quot;)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*LNaJ0WaiV5btw-QIZrauMA.png" /><figcaption>The blue line represents the R² of the validation data, and the red line represents the R² of the training data. The x-axis represents the different values of Alpha.</figcaption></figure><p>Here the model is built and tested on the same data, so the training and test data are the same.</p><p>The red line in the above figure represents the R² of the training data as alpha increases the R² decreases. Therefore, as alpha increases, the model performs worse on the training data.</p><p>The blue line represents the R² on the validation data. As the value for alpha increases, the R² increases and converges at a point.</p><h3>Part 4: Grid Search</h3><p>The term alpha is a hyperparameter. Sklearn has the class GridSearchCV to make the process of finding the best hyperparameter simpler.</p><p>Let’s import GridSearchCV from the module model_selection.</p><pre>from sklearn.model_selection import GridSearchCV</pre><p>We create a dictionary of parameter values:</p><pre>parameters1 = [{&quot;alpha&quot;: [0.001, 0.1, 1, 10, 100, 1000, 10000, 100000, 1000000]}]</pre><p>Create a Ridge regression object:</p><pre>RR=Ridge()<br>RR</pre><p>Create a ridge grid search object:</p><pre>Grid1 = GridSearchCV(RR, parameters1, cv=4)</pre><p>In order to avoid a deprecation warning due to the iid parameter, we set the value of iid to “None”.</p><p>Fit the model:</p><pre>Grid1.fit(x_data[[&#39;horsepower&#39;, &#39;curb-weight&#39;, &#39;engine-size&#39;, &#39;highway-mpg&#39;]], y_data)</pre><p>The object finds the best parameter values on the validation data. We can obtain the estimator with the best parameters and assign it to the variable BestRR as follows:</p><pre>BestRR = Grid1.best_estimator_</pre><p>We now test our model on the test data:</p><pre>BestRR.score(x_test[[&#39;horsepower&#39;, &#39;curb-weight&#39;, &#39;engine-size&#39;, &#39;highway-mpg&#39;]], y_test)</pre><p><strong>Output:</strong> 0.8411649831036152</p><h3>Let’s summarize what we learned in this part.</h3><ul><li><strong>Identify over-fitting and under-fitting in a predictive model:</strong> Overfitting occurs when a function is too closely fit the training data points and captures the noise of the data. Underfitting refers to a model that can’t model the training data or capture the trend of the data.</li><li><strong>Apply Ridge Regression to linear regression models:</strong> Ridge regression is a regression that is employed in a Multiple regression model when Multicollinearity occurs.</li><li><strong>Tune hyper-parameters of an estimator using Grid search:</strong> Grid search is a time-efficient tuning technique that exhaustively computes the optimum values of hyperparameters performed on specific parameter values of estimators.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f2a46d4781a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Analysis with Python — Model Development — Part 3]]></title>
            <link>https://medium.com/@varunsrivatsa27/data-analysis-with-python-model-development-part-3-d75df5480ab3?source=rss-35df1a22f691------2</link>
            <guid isPermaLink="false">https://medium.com/p/d75df5480ab3</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Varun Srivatsa]]></dc:creator>
            <pubDate>Sun, 04 Sep 2022 09:41:24 GMT</pubDate>
            <atom:updated>2022-09-04T09:41:24.110Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Analysis with Python — Model Development — Part 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xS8I1gsP6fiZmcw3" /><figcaption>Photo by <a href="https://unsplash.com/@marius?utm_source=medium&amp;utm_medium=referral">Marius Masalar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this part, we will examine <strong>model development</strong> by trying to predict the price of a car using our dataset. We’ll learn about simple and multiple linear regression, model evaluation using visualization, polynomial regression and pipelines, R-squared and MSE for in-sample evaluation, prediction and decision making, and how we can determine a fair value for a used car.</p><p><strong>What is a model?</strong></p><p>A model can be thought of as a mathematical equation used to predict a value, given one or more other values. For example, we input a car model’s highway miles per gallon as the independent variable or feature, and the output of the model is the price, which is the dependent variable.</p><p>Usually, the more relevant data we have, the more accurate our model is. For example, if we input multiple independent variables or features into our model, our model may predict a more accurate price for the car. To understand why more data is important, consider the following situation.</p><p>You have two almost identical cars. Pink cars sell for significantly less. You want to use your model to determine the price of two cars, one pink, and one red. if your model&#39;s independent variables or features do not include color, your model will predict the same price for cars that may sell for much less.</p><p>I hope now you have a better understanding of what a model is and how it works. Let’s get into developing one.</p><p><strong>We’ll look into the following objectives in this Part:</strong></p><ul><li>Describe how to process linear regression in Python.</li><li>Apply model evaluation using visualization in Python.</li><li>Apply polynomial regression techniques to Python.</li><li>Evaluate a data model by using visualization.</li><li>Describe the use of R-squared and MSE for in-sample evaluation.</li><li>Apply prediction and decision-making to Python model creation.</li></ul><h3>Setup — Import Data</h3><p>Import libraries.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt</pre><p>Load the data and store it in data frame <strong>df</strong>:</p><p>This dataset was hosted on an IBM Cloud object.</p><pre># path of data<br>path = &#39;https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DA0101EN-SkillsNetwork/labs/Data%20files/automobileEDA.csv&#39;</pre><pre>df = pd.read_csv(path)</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wGtygBRtz9IoEVmOkpoa9Q.png" /><figcaption>Dataset</figcaption></figure><p><strong><em>Note</em></strong><em>: For a better understanding of the data and the steps I have taken to clean it, I highly recommend reading </em><a href="https://medium.com/@varunsrivatsa27/data-analysis-with-python-data-wrangling-part-1-dc571ab55259"><strong><em>Data Analysis with Python — Data Wrangling — Part 1</em></strong></a><em> and </em><a href="https://medium.com/@varunsrivatsa27/data-analysis-with-python-exploratory-data-analysis-eda-part-2-c2460874d49f"><strong><em>Data Analysis with Python — Exploratory Data Analysis (EDA) — Part 2</em></strong></a><em>.</em></p><p>For your reference, the Notebook is also available <a href="https://github.com/NXture/automobile-price-prediction/blob/master/Model-Development.ipynb">here</a>.</p><h3>Linear Regression and Multiple Linear Regression</h3><p><strong>Linear Regression</strong></p><p>One example of a Data Model that we will be using is:</p><p><strong>Simple Linear Regression</strong></p><p>Simple Linear Regression is a method to help us understand the relationship between two variables:</p><ul><li>The predictor/independent variable — X</li><li>The response/dependent variable (that we want to predict) — Y</li></ul><p>The result of Linear Regression is a <strong>linear function</strong> that predicts the response (dependent) variable as a function of the predictor (independent) variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*ZsixoCWOq2fk52QOneVcBA.png" /></figure><p><strong>Linear Function</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*_RkvTE9ePh7xcjh2kQFu5A.png" /></figure><ul><li>a refers to the <strong>intercept</strong> of the regression line, in other words: the value of Y when X is 0.</li><li>b refers to the <strong>slope</strong> of the regression line, in other words: the value with which Y changes when X increases by 1 unit.</li></ul><p>Let’s load the modules for linear regression:</p><pre>from sklearn.linear_model import LinearRegression</pre><p>Create the linear regression object:</p><pre>lm = LinearRegression()<br>lm</pre><p><em>How could “highway-mpg” helps us predict car price?</em></p><p>For this example, we want to look at how highway-mpg can help us predict car prices. Using simple linear regression, we will create a linear function with “highway-mpg” as the predictor variable and the “price” as the response variable.</p><pre>X = df[[&quot;highway-mpg&quot;]]<br>Y = df[[&quot;price&quot;]]</pre><p>Fit the linear model using highway-mpg:</p><pre>lm.fit(X,Y)</pre><p>We can output a prediction:</p><pre>Yhat = lm.predict(X)<br>Yhat[0:5]</pre><p>Output: array([16236.50464347, 16236.50464347, 17058.23802179, 13771.3045085, 20345.17153508])</p><p><em>What is the value of the intercept (a)?</em></p><pre>lm.intercept_</pre><p><strong>Output:</strong> 38423.3058581574</p><p><em>What is the value of slope (b)?</em></p><pre>lm.coef_</pre><p><strong>Output: </strong>array([-821.73337832])</p><p><em>What is the final estimated linear model we get?</em></p><p>As we saw above, we should get a final linear model with the structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*_RkvTE9ePh7xcjh2kQFu5A.png" /></figure><p>Plugging in the actual values we get:</p><p><em>Price = 38423.31 -821.73 * </em><strong><em>highway-mpg</em></strong></p><h3>Multiple Linear Regression</h3><p>What if we want to predict car prices using more than one variable?</p><p>If we want to use more variables in our model to predict car price, we can use Multiple Linear Regression. Multiple Linear Regression is very similar to Simple Linear Regression, but this method is used to explain the relationship between one continuous response (dependent) variable and two or more predictor (independent) variables. Most real-world regression models involve multiple predictors. We will illustrate the structure by using four predictor variables, but these results can generalize to any integer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*UJ_QvM3fCP5YFGXWoAk1tQ.png" /></figure><p>The equation is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*ddgDi3nIxBMxEaf0dxZ6sw.png" /></figure><p>From the previous section we know that other good predictors of price could be:</p><ul><li>Horsepower</li><li>Curb-weight</li><li>Engine-size</li><li>Highway-mpg</li></ul><p>Let’s develop a model using these variables as the predictor variables.</p><pre>Z = df[[&quot;horsepower&quot;, &quot;curb-weight&quot;, &quot;engine-size&quot;, &quot;highway-mpg&quot;]]</pre><p>Fit the linear model using the four variables mentioned above.</p><pre>lm.fit(Z, df[&quot;price&quot;])</pre><p>What is the value of the intercept(a)?</p><pre>lm.intercept_</pre><p><strong>Output:</strong> -15806.62462632923</p><p>What are the values of the coefficients (b1, b2, b3, b4)?</p><pre>lm.coef_</pre><p><strong>Output:</strong> array([53.49574423, 4.7077099, 81.53026382, 36.05748882])</p><p>What is the final estimated linear model that we get?</p><p>As we saw above, we should get a final linear function with the structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*ddgDi3nIxBMxEaf0dxZ6sw.png" /></figure><p>What is the linear function we get in this example?</p><p>Price = -15678.742628061467 + 52.65851272 * horsepower + 4.69878948 * curb-weight + 81.95906216 * engine-size + 33.58258185 * highway-mpg</p><p>Let’s create and train a Multiple Linear Regression model “lm2” where the response variable is “price”, and the predictor variable is “normalized-losses” and “highway-mpg”.</p><pre>lm2 = LinearRegression()<br>lm2.fit(df[[&quot;normalized-losses&quot;, &quot;highway-mpg&quot;]], df[&quot;price&quot;])</pre><p>Find the coefficient of the model.</p><pre>lm2.coef_</pre><p><strong>Output:</strong> array([1.49789786, -820.45434016])</p><h3>Model Evaluation Using Visualization</h3><p>Now that we’ve developed some models, how do we evaluate our models and choose the best one? One way to do this is by using visualization.</p><p>Import the visualization package, seaborn:</p><pre># import the visualization package: seaborn<br>import seaborn as sns<br>%matplotlib inline</pre><h4>Regression Plot</h4><p>When it comes to simple linear regression, an excellent way to visualize the fit of our model is by using <strong>regression plots</strong>.</p><p>This plot will show a combination of scattered data points (a scatterplot), as well as the fitted <strong>linear regression</strong> line going through the data. This will give us a reasonable estimate of the relationship between the two variables, the strength of the correlation, as well as the direction (positive or negative correlation).</p><p>Let’s visualize <strong>highway-mpg </strong>as a potential predictor variable of price:</p><pre>width = 12<br>height = 10<br>plt.figure(figsize=(width, height))<br>sns.regplot(x=&quot;highway-mpg&quot;, y=&quot;price&quot;, data=df)<br>plt.ylim(0,)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*hflk3AsjBmQdALM9SwxsKw.png" /><figcaption>Regression plot for “highway-mpg” or “price”</figcaption></figure><p>We can see from this plot that price is negatively correlated to highway-mpg since the regression slope is negative.</p><p>One thing to keep in mind when looking at a regression plot is to pay attention to how scattered the data points are around the regression line. This will give you a good indication of the variance of the data and whether a linear model would be the best fit or not. If the data is too far off from the line, this linear model might not be the best model for this data.</p><p>Let’s compare this plot to the regression plot of “peak-rpm”.</p><pre>plt.figure(figsize=(width, height))<br>sns.regplot(x=&quot;peak-rpm&quot;, y=&quot;price&quot;, data=df)<br>plt.ylim(0,)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*bBdwfTFotDspeR3o4hKqaA.png" /><figcaption>Regression plot of “peak-rpm” and “price”</figcaption></figure><p>Comparing the regression plot of “peak-rpm” and “highway-mpg”, we see that the points for “highway-mpg” are much closer to the generated line and, on average, decrease. The points of “peak-rpm” have more spread around the predicted line and it is much harder to determine if the points are decreasing or increasing as the “peak-rpm” increases.</p><p>In the regression plots above, is “peak-rpm” or “highway-mpg” more strongly correlated with “price”? Use the method “.corr()” to verify your answer.</p><pre>df[[&quot;peak-rpm&quot;,&quot;highway-mpg&quot;,&quot;price&quot;]].corr()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*KEpQtPwzTdFkFpOAwuDV5g.png" /></figure><h4>Residual Plot</h4><p>A good way to visualize the variance of the data is to use a residual plot.</p><p><em>What is a </em><strong><em>residual</em></strong><em>?</em></p><p>The difference between the observed value (y) and the predicted value (Yhat) is called the residual (e). When we look at a regression plot, the residual is the distance from the data point to the fitted regression line.</p><p><em>So what is a </em><strong><em>residual plot</em></strong><em>?</em></p><p>A residual plot is a graph that shows the residuals on the vertical y-axis and the independent variable on the horizontal x-axis.</p><p>What do we pay attention to when looking at a residual plot?</p><p>We look at the spread of the residuals:</p><ul><li>If the points in a residual plot are <strong>randomly spread out around the x-axis</strong>, then a <strong>linear model is appropriate</strong> for the data.</li></ul><p>What is that? Randomly spread out residuals means that the variance is constant, and thus the linear model is a good fit for this data.</p><pre>width = 12<br>height = 10<br>plt.figure(figsize=(width, height))<br>sns.residplot(df[&quot;highway-mpg&quot;], df[&quot;price&quot;])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*AqYaRePV7dIJ76WyHEBf4g.png" /><figcaption>Residual plot for price and highway-mpg</figcaption></figure><p><em>What is this plot telling us?</em></p><p>We can see from this residual plot that the residuals are not randomly spread around the x-axis, leading us to believe that maybe a non-linear model is more appropriate for this data.</p><h4>Multiple Linear Regression</h4><p>How do we visualize a model for multiple Linear Regression? This gets a bit more complicated because you can’t visualize it with regression or residual plots.</p><p>One way to look at the fit of the model is by looking at the distribution plot. We can look at the distribution of the fitted values that result from the model and compare it to the distribution of the actual values.</p><p>First, let’s make a prediction:</p><pre>Y_hat = lm.predict(Z)</pre><pre>plt.figure(figsize=(width, height))</pre><pre>ax1 = sns.distplot(df[&quot;price&quot;], hist=False, color=&quot;r&quot;, label=&quot;Actual Value&quot;)<br>sns.distplot(Y_hat, hist=False, color=&quot;b&quot;, label=&quot;Fitted Values&quot;,ax=ax1)</pre><pre>plt.title(&quot;Actual vs Fitted Values for Price&quot;)<br>plt.xlabel(&quot;Price (in dollars)&quot;)<br>plt.ylabel(&quot;Proportion of Cars&quot;)</pre><pre>plt.show()<br>plt.close()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*_kSDUVwVPoV9euXCEY0yBw.png" /><figcaption>Distribution plot to evaluate model</figcaption></figure><p>We can see that the fitted values are reasonably close to the actual values since the two distributions overlap a bit. However, there is definitely some room for improvement.</p><h3>Polynomial Regression and Pipelines.</h3><p>Polynomial regression is a particular case of the general linear regression model or multiple linear regression models.</p><p>We get non-linear relationships by squaring or setting higher-order terms of the predictor variables.</p><p>There are different orders of polynomial regressions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*Gn8aAzwn6NZxDKXoBC4igg.png" /></figure><p>We saw earlier that a linear model did not provide the best fit while using “highway-mpg” as the predictor variable. Let’s see if we can try fitting a polynomial model to the data instead.</p><p>We will use the following function to plot the data:</p><pre># Define a function PlotPolly </pre><pre>def PlotPolly(model, independent_variable, dependent_variable, Name):<br>   x_new = np.linespace(15, 55, 100)<br>   y_new = model(x_new)<br>   plt.plot(independent_variable, dependent_variable, &quot;.&quot;, x_new, y_new, &quot;-&quot;)<br>   plt.title(&quot;Polynomial Fit with Matplotlib for Price ~ Length&quot;)<br>   ax = plt.gca()<br>   ax.set_facecolor((0.898, 0.898, 0.898))<br>   fig = plt.gcf()<br>   plt.xlabel(Name)<br>   plt.ylabel(&quot;Price of Cars&quot;)</pre><pre>   plt.show()<br>   plt.close()</pre><p>Let’s get the variables:</p><pre>x = df[&quot;highway-mpg&quot;]<br>y= df[&quot;price&quot;]</pre><p>Let’s fit the polynomial using the function <strong>polyfit</strong>, then use the function poly1d to display the polynomial function.</p><pre># Here we use a polynomial of the 3rd order (cubic)<br>f = np.polyfit(x, y, 3)<br>p = np.poly1d(f)<br>print(p)</pre><p><strong>Output:</strong> -1.557 x + 204.8 x — 8965 x + 1.379e+05</p><p>Let’s plot the function:</p><pre>PlotPolly(p, x, y, &quot;highway-mpg&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*c8JVU2yLzgmv2_hW_4y3vQ.png" /><figcaption>Polynomial fit for price and length</figcaption></figure><pre>np.polyfit(x, y, 3)</pre><p><strong>Output:</strong> array([-1.55663829e+00, 2.04754306e+02, -8.96543312e+03, 1.37923594e+05])</p><p>We can already see from the plotting that this polynomial model performs better than the liner model. This is because the generated polynomial function “hits” more of the data points.</p><p>Let’s create 11 order polynomial model with the variables x and y from above.</p><pre># Here we use a polynomial of the 11rd order (cubic)<br>f1 = np.polyfit(x, y, 11)<br>p1 = np.poly1d(f1)<br>print(p1)<br>PlotPolly(p1, x, y, &quot;Highway MPG&quot;)</pre><p>11 10 9 8 7 -1.243e-08 x + 4.722e-06 x — 0.0008028 x + 0.08056 x — 5.297 x 6 5 4 3 2 + 239.5 x — 7588 x + 1.684e+05 x — 2.565e+06 x + 2.551e+07 x — 1.491e+08 x + 3.879e+08</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*FzjNlD-TebzDBSa6d_qoxg.png" /><figcaption>Polynomial Fit for Price ~ Length</figcaption></figure><p>The analytical expression for the Multivariate Polynomial function gets complicated. For example, the expression for a second-order (degree=2) polynomial with two variables is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*YvELXCxMmTy7Y_c0whEF0w.png" /></figure><p>We can perform a polynomial transformation on multiple features. First, we import the module:</p><pre>from sklearn.preprocessing import PolynomialFeatures</pre><p>We create a PolynomialFeatures object of degree 2:</p><pre>pr=PolynomialFeatures(degree=2)<br>pr</pre><pre>Z_pr=pr.fit_transform()</pre><p>In the original data, there are 201 samples and 4 features.</p><pre>Z.shape</pre><p><strong>Output:</strong> (201, 4)</p><p>After the transformation, there are 201 samples and 15 features.</p><pre>Z_pr.shape</pre><p><strong>Output:</strong> (201, 15)</p><h4>Pipeline</h4><p>Data Pipelines simplify the steps of processing the data. We use the module Pipeline to create a pipeline. We also use StandardScalar as a step in our pipeline.</p><pre>from sklearn.pipline import Pipeline<br>from sklearn.preprocessing import StandardScaler</pre><p>We create the pipeline by creating a list of tuples including the name of the model or estimator and its corresponding constructor.</p><pre>Input=[(&quot;scale&quot;, StandardScaler()),(&quot;polynomial&quot;, PolynomialFeatures(include_bias=False)), (&quot;model&quot;, LinearRegression())]</pre><p>We input the list as an argument to the pipeline constructor:</p><pre>pipe=Pipeline(Input)<br>pipe</pre><p>First, we convert the data type Z to type float to avoid conversion warnings that may appear as a result of StandardScaler taking float inputs.</p><p>Then, we can normalize the data, perform a transform and fit the model simultaneously.</p><pre>z = Z.astype(float)<br>pipe.fit(Z, y)</pre><p>Similarly, we can normalize the data, perform a transform and produce a prediction simultaneously.</p><pre>ypipe = pipe.predict(Z)<br>ypipe[0:4]</pre><p><strong>Output: </strong>array([13102.74784201, 13102.74784201, 18225.54572197, 10390.29636555])</p><h3>Measures for In-Sample Evaluation</h3><p>When evaluating our models, not only do we want to visualize the results, but we sold want a quantitative measure to determine how accurate the model is.</p><p>Two very important measures that are often used in Statistics to determine the accuracy of a model are:</p><ul><li><strong>R²/R-squared</strong></li><li><strong>Mean Squared Error (MSE)</strong></li></ul><p><strong>R-squared</strong></p><p>R-squared, also known as the coefficient of determination is a measure to indicate how close the data is to the fitted regression line.</p><p>The value of the R-squared is the percentage of variation of the response variable (y) that is explained by a linear model.</p><p><strong>Mean Squared Error (MSE)</strong></p><p>The Mean Squared Error measures the average of the squares of errors. That is the difference between the actual value (y) and the estimated value (ŷ).</p><h4>Model 1: Simple Linear Regression</h4><p><strong>Let’s calculate the R²:</strong></p><pre>#highwa_mpg_fit<br>lm.fit(X, Y)<br># Find the R^2<br>print(&quot;The R-square is: &quot;, lm.score(X, Y))</pre><p><strong>Output: </strong>The R-square is: 0.4965911884339176</p><p>We can say that ~49.659% of the variation of the price is explained by this simple linear model “horsepower_fit”.</p><p><strong>Let’s calculate the MSE:</strong></p><p>We can predict the output i.e., “yhat” using the predict method, where X is the input variable:</p><pre>Yhat = lm.predict(X)<br>print(&quot;The out of the first four predicted value is: &quot;, Yhat[0:4])</pre><p><strong>Output:</strong> The output of the first four predicted value is: [16236.50464347 16236.50464347 17058.23802179 13771.3045085]</p><p>Let’s import the function mean_squared_error from the module <strong>metrics</strong>:</p><pre>from sklearn.metrics import mean_squared_error</pre><p>We can compare the predicted results with the actual results:</p><pre>mse = mean_squared_error(df[&quot;price&quot;], Yhat)<br>print(&quot;The mean square of price and predicted value is: &quot;, mse)</pre><p><strong>Output:</strong> The mean square error of price and predicted value is: 31635042.944639888</p><h4>Model 2: Multiple Linear Regression</h4><p><strong>Let’s calculate the R²:</strong></p><pre># Fit the model<br>lm.fit(Z,df[&quot;price&quot;])<br># Find the R^2<br>print(&quot;The R-square is: &quot;, lm.score(Z, df[&quot;price&quot;]))</pre><p><strong>Output:</strong> The R-square is: 0.8093562806577457</p><p>We can say that ~80.896% of the price variation is explained by this multiple linear regression “<strong>multi_fit</strong>”.</p><p>Let’s calculate a prediction:</p><pre>Y_predict_multifit = lm.predict(Z)</pre><p>We compare the predicted results with the actual results:</p><pre>print(&quot;The mean square error of price and predicted value using multifit is: &quot;, mean_squared_error(df[&quot;price&quot;], Y_predict_multifit))</pre><p><strong>Output:</strong> The mean square error of price and predicted value using multifit is: 11980366.87072649</p><h4>Model 3: Polynomial Fit</h4><p><strong>Let’s calculate the R².</strong></p><p>Let’s import the function <strong>r2_score</strong> from the module metrics as we are using a different function.</p><pre>from sklearn.metrics impot r2_score</pre><p>We apply the function to get the value of R²:</p><pre>r_squared = r2_score(y, p(x))<br>print(&quot;The R-square value is: &quot;, r_squared)</pre><p><strong>Output:</strong> The R-square value is: 0.6741946666390652</p><p>We can say that ~67.419 % of the price variation is explained by this polynomial fit.</p><p><strong>MSE</strong></p><p>We can also calculate the MSE:</p><pre>mean_square_error(df[&quot;price&quot;], p(x))</pre><p><strong>Output:</strong> 20474146.426361218</p><h3>Prediction and Decision Making</h3><h4>Prediction</h4><p>In the previous section, we trained the model using the method <strong>fit</strong>. Now we will use the method <strong>predict</strong> to produce a prediction. Let&#39;s import <strong>pyplot</strong> for plotting; we will also be using some functions from NumPy.</p><pre>import matplotlib.pyplot as plt<br>import numpy as np</pre><pre>%matplotlib inline</pre><p>Create a new input:</p><pre>new_input = np.arrange(1, 100, 1).reshape(-1, 1)</pre><p>Fit the model:</p><pre>lm.fit(X, Y)<br>lm</pre><p>Produce a prediction:</p><pre>yhat= lm.predict(new_input)<br>yhat[0:5]</pre><p><strong>Output: </strong>array([37601.57247984, 36779.83910151, 35958.10572319, 35136.37234487, 34314.63896655])</p><p>We can plot the data:</p><pre>plt.plot(new_input, yhat)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*Vy80d2fxAACNgxkm90ztpw.png" /><figcaption>Plotting the prediction.</figcaption></figure><h4>Decision Making: Determining a Good Model Fit</h4><p>Now that we have visualized the different models, and generated the R-squared and MSE values for the fits, how do we determine a good model fit?</p><ul><li><em>What is a good R-squared value?</em></li></ul><p>When comparing models, <strong>the model with the higher R-squared value is a better fit</strong> for the data.</p><ul><li><em>What is a good MSE?</em></li></ul><p>When comparing models, <strong>the model with the smallest MSE value is a better fit</strong> for the data.</p><p><strong>Let’s take a look at the values for the different models.</strong></p><p><strong>Simple Linear Regression:</strong> Using Highway-mpg as a Predictor Variable of Price.</p><ul><li>R-squared: 0.49659118843391759</li><li>MSE: 3.16*10⁷</li></ul><p><strong>Multiple Linear Regression:</strong> Using Horsepower, Curb-weight, Engine-size, and Highway-mpg as Predictor Variables of Price.</p><ul><li>R-squared: 0.80896354913783497</li><li>MSE: 1.2*10⁷</li></ul><p><strong>Polynomial Fit:</strong> Using Highway-mpg as a Predictor Variable of Price.</p><ul><li>R-squared: 0.67419466663906514</li><li>MSE: 2.05*10⁷</li></ul><h4>Simple Linear Regression Model (SLR) vs Multiple Linear Regression Model (MLR)</h4><p>Usually, the more variables you have, the better your model is at predicting, but this is not always true. Sometimes you may not have enough data, you may run into numerical problems, or many of the variables may not be useful and even act as noise. As a result, you should always check the MSE and R².</p><p>In order to compare the results of the MLR vs SLR models, we look at a combination of both the R-squared and MSE to make the best conclusion about the fit of the model.</p><ul><li><strong>MSE:</strong> the MSE of SLR is 3.16*10⁷ while MLR has an MSE of 1.2*10⁷. The MSE of MLR is much smaller.</li><li><strong>R-squared:</strong> In this case, we can also see that there is a big difference between the R-squared of the SLR and the R-squared of the MLR. The R-squared for the SLR(~0.497) is very small compared to the R-squared for the MLR(~0.809).</li></ul><p>This R-squared in combination with the MSE shows that MLR seems like the better model fit in this care compared to SLR.</p><h4>Simple Linear Model (SLR) vs. Polynomial Fit</h4><ul><li><strong>MSE:</strong> We can see that the Polynomial fit brought down the MSE since this MSE is smaller than the one from the SLR.</li><li><strong>R-squared:</strong> The R-squared for the Polynomial Fit is larger than the R-squared for the SLR, so the Polynomial Fit also brought up the R-squared quite a bit.</li></ul><p>Since the Polynomial Fit resulted in a lower MSE and a higher R-squared, we can conclude that this was a better fit model than some linear regression for predicting “price” with “highway-mpg” as a predictor variable.</p><h4>Multiple Linear Regression (MLR) vs. Polynomial Fit</h4><ul><li><strong>MSE:</strong> The MSE for the MLR is smaller than the MSE for the Polynomial Fit.</li><li><strong>R-squared:</strong> The R-squared for the MLR is also much large than for the Polynomial Fit.</li></ul><h3>Conclusion</h3><p>Comparing these three models, we can conclude that the MLR model is the best model to be able to predict price from our dataset. This result makes sense since we have 27 variables in total and we know that more than one of those variables are potential predictors of the final car price.</p><p>Thanks for making it this far 👏. In the next part, we’ll learn about the importance of model evaluation and discuss different data model refinement techniques. Then about model selection and how to identify overfitting and underfitting in a predictive model. Next about using Ridge Regression to regularize and reduce standard errors to prevent overfitting a regression model and how to use the Grid Search method to tune the hyperparameters of an estimator.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d75df5480ab3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Analysis with Python — Exploratory Data Analysis (EDA) — Part 2]]></title>
            <link>https://medium.com/@varunsrivatsa27/data-analysis-with-python-exploratory-data-analysis-eda-part-2-c2460874d49f?source=rss-35df1a22f691------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2460874d49f</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Varun Srivatsa]]></dc:creator>
            <pubDate>Fri, 26 Aug 2022 08:53:01 GMT</pubDate>
            <atom:updated>2022-09-06T04:10:11.720Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Analysis with Python — Exploratory Data Analysis (EDA) — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T9t2rqnSY5zjlOLw" /><figcaption>Photo by <a href="https://unsplash.com/@hharritt?utm_source=medium&amp;utm_medium=referral">Hunter Harritt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Exploratory data analysis or in short EDA is an approach to analyzing data in order to summarize the main characteristics of the data, gain a better understanding of the data set, uncover relationships between different variables, and extract important variables for the problem we’re trying to solve. The main question we are trying to answer in this module is what are the characteristics that have the most impact on the car price? We will be going through a couple of different useful exploratory data analysis techniques to answer this question.</p><p>In this part, we will learn about descriptive statistics, which describe the basic features of a data set and obtains a short summary of the sample and measures of the data. Basics of grouping data using group by and how this can help to transform our data set, the correlation between different variables, and lastly advanced correlation.</p><h3>Import Data — Setup</h3><p><strong>Import libraries:</strong></p><pre>import pandas as pd<br>import numpy as np</pre><p>Load the data and store it in a data frame df :</p><p><strong>This dataset is hosted on the IBM Cloud object.</strong></p><pre>path=&#39;https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DA0101EN-SkillsNetwork/labs/Data%20files/automobileEDA.csv&#39;</pre><pre>df = pd.read_csv(path)</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlAQ6w0ILk0qw7xCCum3oA.png" /><figcaption>Data frame after cleaning</figcaption></figure><p><strong><em>Note:</em></strong><em> It is highly recommended that you first read </em><a href="https://medium.com/@varunsrivatsa27/data-analysis-with-python-data-wrangling-part-1-dc571ab55259"><strong><em>Data Analysis with Python — Data Wrangling — Part 1</em></strong></a><em> to gain a better understanding of the data and the steps I have taken to clean it.</em></p><p>The Notebook is also available for your reference <a href="https://github.com/NXture/automobile-price-prediction/blob/master/Exploratory-Data-Analysis.ipynb">here</a>.</p><h3>Analyzing Individual Feature Patterns Using Visualization.</h3><p>To install Seaborn we use pip , the Python package manager.</p><p>Import visualization packages “Matplotlib” and “Seaborn”. Don’t forget about %matplotlib inline to plot in a Jupyter notebook.</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br>%matplotlib inline</pre><h4>How to choose the right visualization method?</h4><p>When visualizing individual variables, it is important to first understand what type of variable you are dealing with. This will help us find the right visualization method for that variable.</p><pre># list the data types for each column<br>print(df.dtypes)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*JSPNaSxT6MaIsPMVmmjidg.png" /><figcaption>dtypes of all labels</figcaption></figure><pre># The data type of the column “peak-rpm”.<br>print(df[&quot;peak-rpm&quot;].dtype)</pre><p><strong>Output:</strong> float64</p><p>We can calculate the correlation between variables of type “int64” or “float64” using the method “corr”:</p><pre>df.corr()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJb_ezBzouZGgwjJdVc15w.png" /><figcaption>Correlation between variables.</figcaption></figure><p>The diagonal elements are always one; we will study correlation more precisely Pearson Correlation in-depth at the end of the notebook.</p><p>Let’s find the correlation between the following columns: bore, stroke, compression-ratio, and horsepower.</p><p><strong>Hint:</strong> if you would like to select those columns, use the following syntax: df[[&quot;bore&quot;, &quot;stroke&quot;, &quot;compression-ratio&quot;,&quot;horsepower&quot;]]</p><pre>df[[&quot;bore&quot;, &quot;stroke&quot;, &quot;compression-ratio&quot;, &quot;horsepower&quot;]].corr()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*zomHcZVVQfsApgcvmE5-zw.png" /><figcaption>Correlation of a few variables.</figcaption></figure><h4>Continuous Numerical Variables:</h4><p>Continuous numerical variables are variables that may contain any value within some range. They can be of type “int64” or “float64”. A greater way to visualize these variables is by using scatterplots with fitted lines.</p><p>To start understanding the (linear) relationship between an individual variable and the price, we can use “regplot” which plots the scatterplot plus the fitted regression line for the data. This will be useful later on for visualizing the fit of the simple linear regression model as well.</p><p>Let’s see several examples of different linear relationships:</p><h4>Positive Linear Relationship</h4><p>Let’s find the scatterplot of “engine-size” and “price”.</p><pre># Engine size as potential predictor variable of price<br>sns.regplot(x=&quot;engine-size&quot;, y=&quot;price&quot;, data=df)<br>plt.ylim(0,)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*WSRn_l_Dgi2v42ksrRueMw.png" /><figcaption>Scatterplot of “engine-size” and “price”.</figcaption></figure><p>As the “engine-size” goes up, the price goes up: this indicates a positive direct correlation between these two variables. Engine size seems like a pretty good predictor of price since the regression line is almost a perfect diagonal line.</p><p>We can examine the correlation between “engine-size” and “price”. i.e., that’s approximately 0.87.</p><pre>df[[&quot;engine-size&quot;, &quot;price&quot;]].corr()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*GDKnYwhgcF4YQPTU6JF11A.png" /><figcaption>Correlation between “engine-size” and “price”.</figcaption></figure><p>Highway mpg is a potential predictor variable of price. Let’s find the scatterplot of “highway-mpg” and “price”.</p><pre>sns.regplot(x=&quot;highway-mpg&quot;, y=&quot;price&quot;, data=df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*tshMtjrpBGIpuXgn8mTLGg.png" /><figcaption>Scatterplot of “highway-mpg” and “price”.</figcaption></figure><p>As “highway-mpg” goes up, the price goes down: this indicates an inverse/negative relationship between these two variables. “highway-mpg” could potentially be a predictor of price.</p><p>We can examine the correlation between “highway-mpg” and “price” and see it’s approximately -0.704.</p><pre>df[[&quot;highway-mpg&quot;, &quot;price&quot;]].corr()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*xKEfQwiyamZspA_Kljxd0Q.png" /><figcaption>Correlation between “highway-mpg” and “price”.</figcaption></figure><h4>Weak Linear Relationship</h4><p>Let’s see if “peak-rpm” is a predictor variable of “price”</p><pre>sns.regplot(x=&quot;peak-rpm&quot;, y=&quot;price&quot;, data=df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*irRve26KGESPdOSgLisPNQ.png" /><figcaption>Correlation between “peak-rpm” and “price”.</figcaption></figure><p>Peak rpm does not seem like a good predictor of the price at all since the regression line is close to horizontal. Also, the data points are very scattered and far from the fitted line, showing lots of variabilities. Therefore, it’s not a reliable variable.</p><p>We can examine the correlation between “peak-rpm” and “price” and see it’s approximately -0.101616.</p><pre>df[[&quot;peak-rpm&quot;, &quot;price&quot;]].corr()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*0vkXQbiA9g8fNiMUQEKvIg.png" /><figcaption>Correlation between “peak-rpm” and “price”.</figcaption></figure><p>The correlation results between “price” and “stroke”, do you expect a linear relationship?</p><p>Let’s verify our results using the function “regplot()”.</p><pre>sns.regplot(x=&quot;stroke&quot;, y=&quot;price&quot;, data=df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*NeuZJk4c23-LtD6bMixLzQ.png" /><figcaption>Correlation between “price” and “stroke”.</figcaption></figure><h4>Categorical Variables</h4><p>These are variables that describe a “characteristic” of a data unit and are selected from a small group of categories. The categorical variables can have the type “object” or “int64”. A good way to visualize categorical variables is by using boxplots.</p><p>Let’s look at the relationship between “body-style” and “price”.</p><pre>sns.boxplot(x=&quot;body-style&quot;, y=&quot;price&quot;, data=df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*ujSpr-_Se9T77yO6hyLefg.png" /><figcaption>Relationship between “body-style” and “price”.</figcaption></figure><p>We see that the distributions of price between the different body-style categories have significant overlap, so “body-style” would not be a good predictor of price. Let’s examine engine “engine-location” and “price”:</p><pre>sns.boxplot(x=&quot;engine-location&quot;, y=&quot;price&quot;, data=df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*CqEDmNz9skbuh7M4UOpRow.png" /><figcaption>Relationship between “engine-location” and “price”.</figcaption></figure><p>Here we see that the distribution of price between these two engine-location categories, front, and rear, are distinct enough to take engine-location as a potential good predictor of price.</p><p>Let’s examine “drive-wheels” and “price”.</p><pre># drive-wheels<br>sns.boxplot(x=&quot;drive-wheels&quot;, y=&quot;price&quot;, data=df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*cWUNozFk84EB-yuWGhYaqg.png" /><figcaption>Relationship between “drive-wheels” and “price”.</figcaption></figure><p>Here we see that the distribution of price between the different “drive-wheels” categories differs. As such, “drive-wheels” could potentially be a predictor of price.</p><h3>Descriptive Statistical Analysis</h3><p>Let’s first take a look at the variables by utilizing a description method.</p><p>The <strong>describe</strong> function automatically computes basic statistics for all continuous variables. Any NaN values are automatically skipped in these statistics.</p><p>This will show:</p><ul><li>the count of that variable</li><li>the mean</li><li>the standard deviation (std)</li><li>the minimum value</li><li>the IQR (Interquartile Range: 25%, 50%, and 75%)</li><li>the maximum value</li></ul><p>The default setting of “describe” skips variables of the type object. We can apply the method “describe” on the variables of type “object” as follows:</p><pre>df.describe(include=[&#39;object&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_PWvhcgDsJX5zdO0eCmRQ.png" /><figcaption>describe function for object variables.</figcaption></figure><h4>Value Counts</h4><p>Value_counts is a good way of understanding how many units of each characteristic/variable we have. We can apply the “value_counts” method to the column “drive-wheels”. Don’t forget the method “value_counts” only works on pandas series, not pandas data frames. As a result, we only include one bracket df[&quot;drive-wheels&quot;] , not two brackets df[[&quot;drive-wheels&quot;]] .</p><pre>df[&quot;drive-wheels&quot;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*hEgIYM5p0MUWTeemhQLZZQ.png" /><figcaption>value counts of drive wheels.</figcaption></figure><p>We can convert the series to a data frame as follows:</p><pre>df[&quot;drive-wheels&quot;].value_counts().to_frame()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*DDSJT8-9Z2IGvT8PntyctA.png" /><figcaption>Converting value counts to a data frame.</figcaption></figure><p>Let’s repeat the above steps but save the results to the data frame “drive_wheels_counts” and rename the column “drive-wheels” to “value-counts”.</p><pre>drive_wheels_counts = df[&quot;dirve-wheels&quot;].value_counts().to_frame()<br>drive_wheels_counts.rename(columns={&quot;drive-wheels&quot;: &quot;value_counts&quot;}, inplace=True)<br>drive_wheels_counts</pre><p>Now let’s rename the index to “dive-wheels”:</p><pre>drive_wheels_counts.index.name = &quot;drive-wheels&quot;<br>drive_wheels_counts</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*6dP5zC53m_THl7ZLKLyk4A.png" /><figcaption>value_counts for drive-wheels.</figcaption></figure><p>We can repeat the above process for the variable “engine-location”.</p><pre># engine-location as variable<br>engine_loc_counts = df[&quot;engine-location&quot;].value_counts().to_frame()<br>engine_loc_counts.rename(columns={&quot;engine-location&quot;:&quot;value_counts&quot;}, inplace= True)<br>engine_loc_counts.index.name = &quot;engine-location&quot;<br>engine_loc_counts.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*ozp5lP0NYFky0lipx5ub6A.png" /><figcaption>value counts of engine location.</figcaption></figure><p>After examining the value counts of the engine location, we see that engine location would not be a good predictor variable for the price. This is because we only have three cars with a rear engine and 198 with an engine in the front, so this result is skewed. Thus, we are not able to draw any conclusions about the engine location.</p><h4>Basics of Grouping</h4><p>The “groupby” method groups data into different categories. The data is grouped based on one or several variables, and analysis is performed on the individual groups.</p><p>For example, let’s group by the variable “drive-wheels”. We see that there are 3 different categories of drive wheels.</p><pre>df[&quot;drive-wheels&quot;].unique()</pre><p><strong>Output:</strong> array([&quot;rwd&quot;, &quot;fwd&quot;, &quot;4wd&quot;], dtype=object)</p><p>If we want to know, on average, which type of drive wheel is most valuable, we can group “drive-wheels” and then average them.</p><p>We can select the columns “drive-wheels”, “body-style”, and “price”, then assign them to the variable “df_group_one”.</p><pre>df_group_one = df[[&quot;drive-wheels&quot;, &quot;body-style&quot;, &quot;price&quot;]]</pre><p>We can then calculate the average price for each of the different categories of data.</p><pre># grouping results<br>df_group_one = df_group_one.groupby([&quot;drive-wheels&quot;], as_index= False).mean()<br>df_group_one</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*MLI6HBh85Nkdy-zpG3xMRg.png" /><figcaption>The average price of each category.</figcaption></figure><p>From our data, it seems rear-wheel drive vehicles are, on average, the most expensive, while 4-wheel and front-wheel are approximately the same in price.</p><p>You can also group by multiple variables. For example, let’s group by both “drive-wheels” and “body-style”. This groups the data frame by the unique combination of “drive-wheels” and “body-style”. We can store the results in the variable “grouped_test1”.</p><pre># grouping results<br>df_gptest = df[[&quot;drive-wheels&quot;, &quot;body-style&quot;, &quot;price&quot;]]<br>grouped_test1 = df_gptest.groupby([&quot;drive-wheels&quot;, &quot;body-style&quot;], as_index=False).mean()<br>grouped_test1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*YR5HtDaMRC8dOfvRGvUSxA.png" /><figcaption>Grouping data according to “drive-wheels” and “body-style”.</figcaption></figure><p>This grouped data is much easier to visualize when it is made into a pivot table. A pivot table is like an Excel spreadsheet, with one variable along the column and another along the row. We can convert the data frame to a pivot table using the method “pivot” to create a pivot table from the groups.</p><p>In this case, we will leave the “drive-wheels” variable as the rows of the table, and pivot “body-style” to become the columns of the table:</p><pre>grouped_pivot = grouped_test1.pivot(index=&quot;drive-wheels&quot;, columns=&quot;body-style&quot;)<br>grouped_pivot</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*5u7C8VmnBqcjguftyY26Yg.png" /><figcaption>Pivot table for “body-style” and “drive-wheels”.</figcaption></figure><p>Often, we won’t have data for some of the pivot cells. We can fill these missing cells with the value 0, but any other value could potentially be used as well. It should be mentioned that missing data is quite a complex subject and is an entire course on its own.</p><pre>grouped_pivot = grouped_pivot.fillna(0) #Fill missing values with 0<br>grouped_pivot</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*Wr2YIwbjES4cMzjJb62Pyg.png" /><figcaption>Pivot table without NaN values.</figcaption></figure><p>Next, let’s use the “groupby” function to find the average “price” of each car based on “body-style”.</p><pre>df_gptest2 = df[[&quot;body-style&quot;, &quot;price&quot;]]<br>grouped_test_bodystyle = df_gptest2.groupby([&quot;body-style&quot;], as_index = False).mean()<br>grouped_test_bodystyle</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*C8at4suToxyu0OCMci9-Dw.png" /><figcaption>Pivot table for “price” and “body-style”.</figcaption></figure><h4>Variables: Drive wheels and Body Style vs. Price</h4><p>Let’s use a heat map to visualize the relationship between Body Style vs Price.</p><pre># Use the grouped Results<br>plt.pcolor(grouped_pivot, cmap=&quot;RdBu&quot;)<br>plt.colorbar()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*QFbCaCS29gntTTjo-bsJsg.png" /><figcaption>Relationship between “Body-Style” vs “Price”.</figcaption></figure><p>The heatmap plots the target variable (price) proportional to color with respect to the variables “drive-wheel” and “body-style” on the vertical and horizontal axis, respectively. This allows us to visualize how the price is related to “drive-wheel” and “body-style”.</p><p>The default labels convey no useful information to us. Let’s change that.</p><pre>fig, ax = plt.subplots()<br>im = ax.pcolor(grouped_pivot, cmap=&quot;RdBu&quot;)</pre><pre>#label names<br>row_labels = grouped_pivot.columns.levels[1]<br>col_labels = grouped_pivot.index</pre><pre>#move ticks and labels to the center<br>ax.set_xticks(np.arange(grouped_pivot.shape[1]) + 0.5, minor=False)<br>ax.set_yticks(np.arange(grouped_pivot.shape[0]) + 0.5, minor=False)</pre><pre>#insert labels<br>ax.set_xticklabels(row_labels, minor=False)<br>ax.set_yticklabels(col_labels, minor=False)</pre><pre>#rotate label if too long<br>plt.xticks(rotation=90)</pre><pre>fig.colorbar(im)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*yETh__kJ_nsQw0Y8Cne3Sw.png" /><figcaption>Heatmap with labels for better understanding.</figcaption></figure><p>Visualization is very important in data science, and Python visualization packages provide great freedom.</p><p>The main question we want to answer in this module is, “What are the main characteristics which have the most impact on the car price?”.</p><p>To get a better measure of the important characteristics, we look at the correlation of these variables with car prices. In other words: How is the car price dependent on this variable?</p><h3>Correlation and Causation</h3><ul><li><strong>Correlation:</strong> A measure of the extent of interdependence between variables.</li><li><strong>Causation:</strong> the relationship between cause and effect between two variables.</li></ul><p>It is important to know the difference between these two. Correlation does not imply causation. Determining correlation is much simpler than determining causation as causation may require independent experimentation.</p><h4><strong>Pearson Correlation</strong></h4><p>The Pearson Correlation measures the linear dependence between two variables X and Y.</p><p>The resulting coefficient is a value between -1 and 1 inclusive, where:</p><ul><li><strong>1</strong>: Perfect positive linear correlation.</li><li><strong>0</strong>: No linear correlation, the two variables most likely do not affect each other.</li><li><strong>-1</strong>: Perfect negative linear correlation.</li></ul><p>Pearson Correlation is the default method of the function “corr”. Like before, we can calculate the Pearson Correlation of the “int64” or “float64” variables.</p><pre>df.corr()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiMRYSeZB68X5PLv-3KJoQ.png" /><figcaption>Correlation between all variables.</figcaption></figure><p>Sometimes we would like to know the significance of the correlation estimate.</p><h4><strong>P-value</strong></h4><p>What is this P-value? The P-value is the probability value that the correlation between these two variables is statistically significant. Normally, we choose a significance level of 0.05, which means that we are 95% confident that the correlation between the variables is significant.</p><p>By convention, when the</p><ul><li>p-value is $&lt;$ 0.001: we say there is strong evidence that the correlation is significant.</li><li>the p-value is $&lt;$ 0.05: there is moderate evidence that the correlation is significant.</li><li>the p-value is $&lt;$ 0.1: there is weak evidence that the correlation is significant.</li><li>the p-value is $&gt;$ 0.1: there is no evidence that the correlation is significant.</li></ul><p>We can obtain this information using “stats” module in the “scipy” library.</p><pre>from scipy import stats</pre><h4><strong>Wheel-Base vs. Price</strong></h4><p>Let’s calculate the Pearson Correlation Coefficient and P-value of “wheel-base” and “price”.</p><pre>pearson_coef, p_value = stats.pearsonr(df[&quot;whell-base&quot;], df[&quot;price&quot;])<br>print(&quot;The Pearson Correlation Coefficient is&quot;, pearson_coef, &quot; with a P-value of P =&quot;, p_value)</pre><p><strong>Output:</strong> The Pearson Correlation Coefficient is 0.584641822265508 with a P-value of P = 8.076488270733218e-20</p><p><strong>Conclusion:</strong></p><p>Since the p-value is $&lt;$ 0.001, the correlation between “wheel-base” and “price” is statistically significant, although the linear relationship isn’t extremely strong (~0.585).</p><h4><strong>Horsepower vs. Price</strong></h4><p>Let’s calculate the Pearson Correlation Coefficient and P-value of “horsepower” and “price”.</p><pre>pearson_coef, p_value = stats.pearsonr(df[&quot;horsepower&quot;], df[&quot;price&quot;])<br>print(&quot;The Pearson Correlation Coefficient is&quot;, pearson_coef, &quot; with a P-value of P = &quot;, p_value)</pre><p><strong>Output:</strong> The Pearson Correlation Coefficient is 0.8095745670036559 with a P-value of P = 6.369057428260101e-48</p><p><strong>Conclusion:</strong></p><p>Since the p-value is $&lt;$ 0.001, the correlation between “horsepower” and “price” is statistically significant, and the linear relationship is quite strong (~0.809, close to 1).</p><h4><strong>Length vs. Price</strong></h4><p>Let’s calculate the Pearson Correlation and P-value of “width” and “price”:</p><pre>pearson_coef, p_value = stats.pearsonr(df[&quot;width&quot;], df[&quot;price&quot;])<br>print(&quot;The Pearson Correlation Coefficient is&quot;, pearson_coef, &quot; with a P-value of P =&quot;, p_value)</pre><p><strong>Output:</strong> The Pearson Correlation Coefficient is 0.75126533440522672 with a P-value of P = 9.20033551048217e-38</p><p><strong>Conclusion:</strong></p><p>Since the p-value is &lt; 0.001, the correlation between width and price is statistically significant, and the linear relationship is quite strong (~0.751).</p><h4><strong>Curb-Weight vs. Price</strong></h4><p>Let’s calculate the Pearson Correlation Coefficient and P-value of “curb-weight” and “price”:</p><pre>pearson_coef, p_value = stats.pearsonr(df[&quot;curb-weight&quot;], df[&quot;price&quot;])<br>print(&quot;The Pearson Correlation Coeffient is&quot;, pearson_coef, &quot; with a P-value of P = &quot;, p_value)</pre><p><strong>Output:</strong> The Pearson Correlation Coefficient is 0.8344145257702843 with a P-value of P = 2.189577238894065e-53</p><p><strong>Conclusion:</strong></p><p>Since the p-value is $&lt;$ 0.001, the correlation between curb-weight and price is statistically significant, and the linear relationship is quite strong (~0.834).</p><h4><strong>Engine-Size vs. Price</strong></h4><p>Let’s calculate the Pearson Correlation Coefficient and P-value of “engine-size” and “price”:</p><pre>pearson_coef, p_value = stats.pearsonr(df[&quot;engine_size&quot;], df[&quot;price&quot;])<br>print(&quot;The Pearson Correlation Coefficient is&quot;, pearson_coef, &quot; with a P-value of P =&quot;, p_value)</pre><p><strong>Output:</strong> The Pearson Correlation Coefficient is 0.8723351674455182 with a P-value of P = 9.265491622200232e-64</p><p><strong>Conclusion:</strong></p><p>Since the p-value is $&lt;$ 0.001, the correlation between “engine-size” and “price” is statistically significant, and the linear relationship is very strong (~0.872).</p><h4><strong>Bore vs. Price</strong></h4><p>Let’s calculate the Pearson Correlation Coefficient and P-value of “bore” and “price”:</p><pre>pearson_coef, p_value = stats.pearsonr(df[&quot;bore&quot;], df[&quot;price&quot;])<br>print(&quot;The Pearson Correlation Coefficient is&quot;, pearson_coef, &quot; with a P-value of P = &quot;, p_value)</pre><p><strong>Output:</strong> The Pearson Correlation Coefficient is 0.5431553832626603 with a P-value of P = 8.049189483935261e-17</p><p><strong>Conclusion:</strong></p><p>Since the p-value is $&lt;$ 0.001, the correlation between “bore” and “price” is statistically significant, but the linear relationship is only moderate (~0.521).</p><p>We can relate the process for each “city-mpg” and “highway-mpg”:</p><h4><strong>City-mpg vs. Price</strong></h4><pre>pearson_coef, p_value = stats.pearsonr(df[&quot;city-mpg&quot;], df[&quot;price&quot;])<br>print(&quot;The Pearson Correlation Coefficient is&quot;, pearson_coef, &quot; with a P-value of P = &quot;, p_value)</pre><p><strong>Output:</strong> The Pearson Correlation Coefficient is -0.6865710067844678 with a P-value of P = 2.321132065567641e-29</p><p><strong>Conclusion:</strong></p><p>Since the p-value is $&lt;$ 0.001, the correlation between “city-mpg” and “price” is statistically significant, and the coefficient of about -0.687 shows that the relationship is negative and moderately strong.</p><h4><strong>Highway-mpg vs. Price</strong></h4><pre>pearson_coef, p_value = stats.pearsonr(df[&quot;highway-mpg&quot;], df[&quot;price&quot;])<br>print(&quot;The Pearson Correlation Coefficient is&quot;, pearson_coef, &quot; with a P-value of P = &quot;, p_value)</pre><p><strong>Output:</strong> The Pearson Correlation Coefficient is -0.704692265058953 with a P-value of P = 1.7495471144476358e-31</p><p><strong>Conclusion:</strong></p><p>Since the p-value is &lt; 0.001, the correlation between “highway-mpg” and “price” is statistically significant, and the coefficient of about -0.705 shows that the relationship is negative and moderately strong.</p><h3>ANOVA</h3><h4>ANOVA: Analysis of Variance</h4><p>The analysis of Variance (ANOVA) is a statistical method used to test whether there are significant differences between the means of two or more groups. ANOVA returns two parameters:</p><p><strong>F-test score:</strong> ANOVA assumes the means of all groups are the same, calculates how much the actual means deviate from the assumption and reports it as the F-test score. A larger score means there is a larger difference between the means.</p><p><strong>P-value:</strong> P-value tells how statistically significant our calculated score value is.</p><p>If our price variable is strongly correlated with the variable we are analyzing, we expect ANOVA to return a sizeable F-test score and a small p-value.</p><h4>Drive Wheels</h4><p>Since ANOVA analyzes the difference between different groups of the same variable, the “groupby” function will come in handy. Because the ANOVA algorithm averages the data automatically, we do not need to take the average beforehand.</p><p>To see if different types of “drive-wheels” impact “price”, we group the data.</p><pre>grouped_test2 = df_gptest[[&quot;drive-wheels&quot;, &quot;price&quot;]].groupby([&quot;drive-wheels&quot;])<br>grouped_test2.head(2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*D92nalkb6HP8zW5Q414T_w.png" /><figcaption>“drive-wheels” impact “price”.</figcaption></figure><p>We can obtain the values of the method group using the method get_group .</p><pre>grouped_test2.get_group(&quot;4wd&quot;)[&quot;price&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*yZHBLuZ5BuxQwXxlcpop_w.png" /><figcaption>get_group method.</figcaption></figure><p>We can use the function “f_oneway” in the module “stats” to obtain the F-test score and P-value.</p><pre># ANOVA<br>f_val, p_val = status.f_oneway(grouped_test2.get_group(&quot;fwd&quot;)[&quot;price&quot;], grouped_test2.get_group(&quot;rwd&quot;)[&quot;price&quot;], grouped_test2.get_group(&quot;4wd&quot;)[&quot;price&quot;])</pre><pre>print(&quot;ANOVA results: F=&quot;, f_val, &quot;, P=&quot;, p_val)</pre><p><strong>Output:</strong> ANOVA results: F= 67.95406500780399, P= 3.3945443577151245e-23</p><p>This is a great result with a large F-test score showing a strong correlation and a P-value of almost 0 implying almost certain statistical significance. But does this mean all three tested groups are all this highly correlated?</p><p>Let’s examine them separately.</p><p><strong>fwd and rwd</strong></p><pre>f_val, p_val = stats.f_oneway(grouped_test2.get_group(&quot;fwd&quot;)[&quot;price&quot;], grouped_test2.get_group(&quot;rwd&quot;)[&quot;&quot;price])</pre><pre>print(&quot;ANOVA results: F=&quot;, f_val, &quot;, P=&quot;, p_val)</pre><p><strong>Output:</strong> ANOVA results: F= 130.5533160959111, P= 2.2355306355677845e-23</p><p>Let’s examine the other groups.</p><p><strong>4wd and rwd</strong></p><pre>f_val, p_val = stats.f_oneway(grouped_test2.get_group(&#39;4wd&#39;)[&#39;price&#39;], grouped_test2.get_group(&#39;rwd&#39;)[&#39;price&#39;])</pre><pre>print( &quot;ANOVA results: F=&quot;, f_val, &quot;, P=&quot;, p_val)</pre><p><strong>Output:</strong> ANOVA results: F= 8.580681368924756, P= 0.004411492211225333</p><p><strong>4wd and fwd</strong></p><pre>f_val, p_val = stats.f_oneway(grouped_test2.get_group(&#39;4wd&#39;)[&#39;price&#39;], grouped_test2.get_group(&#39;fwd&#39;)[&#39;price&#39;])</pre><pre>print(&quot;ANOVA results: F=&quot;, f_val, &quot;, P=&quot;, p_val)</pre><p><strong>Output:</strong> ANOVA results: F= 0.665465750252303, P= 0.41620116697845666</p><p>We notice that ANOVA for the categories 4wd and fwd yields a high p-value &gt; 0.1, so the calculated F-test score is not very statistically significant. This suggests we can’t reject the assumption that the means of these two groups are the same, or, in other words, we can’t conclude the difference in correlation to be significant.</p><h3>Conclusion: Important Variables</h3><p>We now have a better idea of what our data looks like and which variables are important to take into account when predicting the car price. We have narrowed it down to the following variables:</p><p><strong>Continuous numerical variables:</strong></p><ul><li>Length</li><li>Width</li><li>Curb-weight</li><li>Engine-size</li><li>Horsepower</li><li>City-mpg</li><li>Highway-mpg</li><li>Wheel-base</li><li>Bore</li></ul><p><strong>Categorical variables:</strong></p><ul><li>Drive-wheels</li></ul><p>In the <a href="https://medium.com/@varunsrivatsa27/data-analysis-with-python-model-development-part-3-d75df5480ab3">next part</a>, as we move into building machine learning models to automate our analysis, feeding the model with variables that meaningfully affect our target variable will improve our model’s prediction performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2460874d49f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Analysis with Python — Data Wrangling — Part 1]]></title>
            <link>https://medium.com/@varunsrivatsa27/data-analysis-with-python-data-wrangling-part-1-dc571ab55259?source=rss-35df1a22f691------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc571ab55259</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Varun Srivatsa]]></dc:creator>
            <pubDate>Fri, 19 Aug 2022 04:32:44 GMT</pubDate>
            <atom:updated>2022-08-27T04:21:39.647Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Analysis with Python — Data Wrangling — Part 1</h3><p>Before we begin, let’s first understand the importance of data analysis. As we already know, data is collected everywhere around us. Whether it’s collected manually by scientists or collected digitally, like every time we click on a website or our mobile device. But just having data doesn’t mean information. Data Analysis (a.k.a, Data Science) helps us unlock information and insights from raw data to answer our questions. So data analysis plays a vital role by enabling us to discover useful information from the data, answer questions, and even predict the future or the unknown.</p><p>So let’s begin with our scenario. Let’s say we have a friend named Sam. And Sam wants to sell his car. But the problem is he doesn’t know how much he should sell his car for. Sam wants to sell his car for as much as he can. But he also wants to set the price reasonably, so someone would want to purchase it. So the price he sets should represent the value of the car.</p><p>How can we help Sam determine the best price for his car? Let’s think like a data analyst or data scientist and clearly define some of his problems. For example, is there data on the prices of other cars and their characteristics? What features of cars affect their prices? Color? Brand? Does horsepower also affect the selling price, or perhaps something else? As a data analyst or data scientist, these are some of the questions we can start thinking about.</p><p>To answer these we are going to need some data. <a href="https://archive.ics.uci.edu/ml/machine-learning-databases/autos/imports-85.data?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkDA0101ENSkillsNetwork20235326-2022-01-01">Data Source</a></p><p><strong><em>Note:</em></strong><em> I’m using Python Jupyter Notebook to execute my code. If you prefer using another tool or environment, feel free to do so.</em></p><h3>Let’s first understand the data.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JqZiXgMoqtwx8YyLU9EVIw.png" /><figcaption>Open dataset by Jeffrey C. Schlemmer — CSV format.</figcaption></figure><p>This dataset is in CSV format, which separates each of the values with commas, making it very easy to import into most tools and applications. Each line represents a row in the dataset. <a href="https://archive.ics.uci.edu/ml/datasets/Automobile?utm_medium=Exinfluencer&amp;utm_source=Exinfluencer&amp;utm_content=000026UJ&amp;utm_term=10006555&amp;utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkDA0101ENSkillsNetwork20235326-2022-01-01">Here’s</a> the documentation on what each of the 26 columns represents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*hhbgLSG-UIe8JPle16-JpQ.png" /><figcaption>Attribute information with range.</figcaption></figure><p>Okay, after we understand the meaning of each feature, we can notice that the 26th attribute is price. This is our target value or label in other words. This means the price is the value that we want to predict from the dataset and the predictors should be all the other variables listed like symboling, normalized losses, make, and so on. Thus, the goal of this project is to predict price in terms of other car features.</p><p><strong><em>Note:</em></strong><em> This dataset is actually from 1985, the car prices for the models may seem a little low. But just bear in mind that the goal here is to learn how to analyze the data.</em></p><h4>Data Acquisition</h4><p>There are various formats for a dataset: .csv, .json, .xlsx etc. The dataset can be stored in different places, on our local machine or sometimes online.</p><p>In our case, the Automobile dataset is an online source, and it is in a CSV (comma-separated value) format.</p><p>and the Pandas Library is a useful tool that enables us to read various datasets into a data frame, I recommend you to create a python virtual environment and install pandas using pip install pandas` and importing them into our notebook as follows.</p><pre># import pandas &amp; numpy library<br>import pandas as pd<br>import numpy as np</pre><h4>Read Data</h4><p>We can use pandas.read_csv() function to read the CSV file. In the brackets, we put the file path along with a quotation mark so that pandas will read the file into a data frame from that address. The fuel path can be either an URL or our local file address.</p><p>Because the data does not include headers, we can add an argument headers = None inside the read_csv() method so that pandas will not automatically set the first row as a header. And we can assign the dataset to any variable.</p><pre># Import pandas library<br>import pandas as pd</pre><pre># Read the online file by the URL privded above, and assign it to variable &quot;df&quot;<br>other_path = &quot;https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DA0101EN-SkillsNetwork/labs/Data%20files/auto.csv&quot;</pre><pre>df = pd.read_csv(other_path, header=None)</pre><p>After reading the dataset, we can use the dataframe.head(n) method to check the top n rows of the data frame, where n is an integer. Contrary to dataframe.head(n) , dataframe.tail(n) will show us the bottom n rows of the data frame.</p><pre># Show the first 5 rows using dataframe.head() method<br>print(&quot;The first 5 rows of the dataframe&quot;)<br>df.head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFb6mRDsxiGgnD9HU-Hizw.png" /><figcaption>The output of df.head(5)</figcaption></figure><p>As we can see, our dataset doesn’t have a header. To better describe and understand our data, we can introduce a header by adding it manually.</p><p>First, we create a list of “headers” that include all column names in order. Then, we use dataframe.columns = headers to replace the headers with the list we created.</p><pre># create headers list<br>headers = [&quot;symboling&quot;,&quot;normalized-losses&quot;,&quot;make&quot;,&quot;fuel type&quot;,&quot;aspiration&quot;, &quot;num-of-doors&quot;,&quot;body-style&quot;, &quot;drive wheels&quot;,&quot;engine-location&quot;,&quot;wheel-base&quot;, &quot;length&quot;,&quot;width&quot;,&quot;height&quot;,&quot;curb-weight&quot;,&quot;engine-type&quot;, &quot;num-of-cylinders&quot;, &quot;engine-size&quot;,&quot;fuel system&quot;,&quot;bore&quot;,&quot;stroke&quot;,&quot;compression-ratio&quot;,&quot;horsepower&quot;, &quot;peak-rpm&quot;,&quot;city-mpg&quot;,&quot;highway-mpg&quot;,&quot;price&quot;]</pre><p>Let’s replace headers and recheck our data frame.</p><pre>df.columns = headers<br>df.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*so2JFClErEo82fSaLDfS6Q.png" /><figcaption>Data frame after adding a header.</figcaption></figure><h3>Data Wrangling</h3><p>Data wrangling is the process of converting data from the initial format to a format that may be better for analysis.</p><p>As we can see above, several question marks appeared in the data frame; those are missing values that may hinder our further analysis.</p><p><strong>So, how to work with missing data?</strong></p><p>Steps for working with missing data:</p><ol><li><strong>Identify missing data</strong></li><li><strong>Deal with missing data</strong></li><li><strong>Correct data format</strong></li></ol><h4>Identify and handle missing values</h4><p>Convert “?” to NaN</p><p>In the car dataset, missing data comes with the question mark “?”. We replace “?” with NaN (Not a Number), Python’s default missing value marker for reasons of computational speed and convenience.</p><pre>df.replace(&#39;?&#39;, np.nan, inplace=True)<br>df.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hi5NrlcUWvWk-3zDk_tHMw.png" /><figcaption>Data frame without null values.</figcaption></figure><h4>Evaluating for Missing Data</h4><p>The missing values are converted by default. We use the following functions to identify these missing values. There are two methods to detect missing data:</p><ol><li><strong>.isnull()</strong></li><li><strong>.notnull()</strong></li></ol><p>The output is a boolean value indicating whether the value that is passed into the argument is in fact missing data.</p><pre>missing_data = df.isnull()<br>missing_data.head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-eBxULvtUW7FNbjWFhI7A.png" /><figcaption>missing_data data frame.</figcaption></figure><p>“True” means the value is a missing value while “False” means the value is not a missing value.</p><p>Count missing values in each column</p><p>Using a for loop in Python, we can quickly figure out the number of missing values in each column. As mentioned above, “True” represents a missing value and “False” means the value is present in the dataset. In the body of the for loop, the method .value_counts() counts the number of “True” values.</p><pre>for column in missing_data.columns.values.tolist():<br>    print(column)<br>    print(missing_data[column].value_counts())<br>    print(&quot;&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*LzXyJRADGumYx_Ys5t4HAw.png" /><figcaption>value counts of missing data in each column.</figcaption></figure><p>Based on the summary above, each column has 205 rows of data, and seven of the columns contain missing data:</p><ol><li><strong>“normalized-losses”:</strong> 41 missing data</li><li><strong>“num-of-doors”:</strong> 2 missing data</li><li><strong>“bore”:</strong> 4 missing data</li><li><strong>“stroke”:</strong> 4 missing data</li><li><strong>“horsepower”:</strong> 2 missing data</li><li><strong>“peak-rpm”:</strong> 2 missing data</li><li><strong>“price”:</strong> 4 missing data</li></ol><h4>Deal with missing data</h4><p>How to deal with missing data?</p><ol><li><strong>Drop data</strong> — Drop the whole row or Drop the whole column</li><li><strong>Replace data</strong> — Replace it by mean, Replace it by frequency, or Replace it based on other functions</li></ol><p>Whole columns should be dropped only if most entries in the column are empty. In our dataset, none of the columns are empty enough to drop entirely. We have some freedom in choosing which method to replace data; however, some methods may seem more reasonable than others. We will apply each method to many different columns:</p><p><strong>Replace by mean:</strong></p><ul><li><strong>“normalized-losses”:</strong> 41 missing data, replace them with mean.</li><li><strong>“stroke”:</strong> 4 missing data, replace them with mean</li><li><strong>“bore”:</strong> 4 missing data, replace them with mean</li><li><strong>“horsepower”:</strong> 2 missing data, replace them with mean</li></ul><p><strong>Replace by frequency:</strong></p><ul><li><strong>“num-of-doors”:</strong> 2 missing data, replace them with “four”. <strong>Reason:</strong> 84% of sedans are four doors. Since four doors are most frequent, it is most likely to occur.</li></ul><p><strong>Drop the whole row:</strong></p><ul><li><strong>“price”:</strong> 4 missing data, simply delete the whole row. <strong>Reason:</strong> the price is what we want to predict. Any data entry without price data cannot be used for prediction; there any row now without price data is not useful to us.</li></ul><p><strong>Calculate the mean value for the “normalized-losses” column</strong></p><pre>avg_norm_loss = df[&quot;normalized-losses&quot;].astype(&quot;flot&quot;).mean(axis=0)<br>print(&quot;Average of normalized-losses:&quot;, avg_norm_loss)</pre><p>Output: Average of normalized-losses: 122.0</p><p>Replace “NaN” with the mean value in the “normalized-losses” column</p><pre>df[&quot;normalized-losses&quot;].replace(np.nan, avg_norm_loss, inplace=True)</pre><p><strong>Calculate the mean value for the “bore” column</strong></p><pre>avg_bore = df[&quot;bore&quot;].astype(&quot;float&quot;).mean(axis=0)<br>print(&quot;Average of bore:&quot;, avg_bore)</pre><p>Output: Average of bore: 3.3297512437810943</p><p>Replace “NaN” with the mean value in the “bore” column</p><pre>df[&quot;bore&quot;].replace(np.nan, avg_bore, inplace=True)</pre><p>Replace the “stroke” column with the mean value.</p><pre>avg_stroke = df[&quot;stroke&quot;].astype(&#39;float&#39;).mean(axis=0)<br>print(&quot;Average of Stroke&quot;, avg_stroke)<br>df[&quot;stroke&quot;].replace(np.nan, avg_stroke, inplace=True)</pre><p>Output: Average of Stroke: 3.255422885572139</p><p><strong>Calculate the mean value for the “horsepower” column</strong></p><pre>avg_horsepower = df[&quot;horsepower&quot;].astype(&quot;float&quot;).mean(axis=0)<br>print(&quot;Average horsepower:&quot;, avg_horsepower)</pre><p>Output: Average horsepower: 104.25615763546799</p><p>Replace “NaN” with the mean value in the “horsepower” column</p><pre>df[&quot;horsepower&quot;].replace(np.nan, avg_horsepower, inplace=True)</pre><p><strong>Calculate the mean value for the “peak-rpm” column</strong></p><pre>avg_peakrpm = df[&quot;preak-rpm&quot;].astype(&quot;float&quot;).mean(axis=0)<br>print(&quot;Average peak rpm:&quot;, avg_peakrpm)</pre><p>Output: Average peak rpm: 5125.369458128079</p><p>Replace “NaN” with the mean value in the “peak-rpm” column</p><pre>df[&quot;peak-rpm&quot;].replace(np.nan, avg_peakrpm, inplace=True)</pre><p>To see which values are present in a particular column, we can use the .value_counts() method:</p><pre>df[&quot;num-of-doors&quot;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*Tt9kuEORQd8_o6arEyMIMg.png" /><figcaption>value counts of the number of doors.</figcaption></figure><p>We can see that four doors are the most common type. We can also use the .idxmax() method to calculate the most common type automatically:</p><pre>df[&quot;num-of-doors&quot;].value_counts().idmax()</pre><p>Output: &#39;four&#39;</p><p>The replacement procedure is very similar to what we have seen previously:</p><pre>#replace the missing &#39;num-of-doors&#39; values by the most frequent<br>df[&quot;num-of-doors&quot;].replace(np.nan, &quot;four&quot;, inplace=True)</pre><p>Finally, let’s drop all rows that do not have price data:</p><pre># simply drop whole row with NaN in &quot;price&quot; column<br>df.dropna(subset=[&quot;price&quot;], axis=0, inplace=True)</pre><pre># reset index, because we droped two rows<br>df.reset_index(drop=True, inplace=True)</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXzW2XXMEqf67a5NIIm4Hg.png" /><figcaption>Data frame with zero null values.</figcaption></figure><p>Now, we have a dataset with no missing values.</p><h4>Correct data format</h4><p><strong>We are almost there!</strong></p><p>The last step in data cleaning is checking and making sure that all data is in the correct format (int, float, text, or other).</p><p>In Pandas, we use:</p><ol><li><strong>.dtype()</strong> to check the data type</li><li><strong>.astype()</strong> to change the data type</li></ol><p>Let’s list the data types for each column</p><pre>df.dtypes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*kyFPQ8VjuhQrTVychus7Bw.png" /><figcaption>Data types of each variable</figcaption></figure><p>As we can see above, some columns are not of the correct data types. Numerical variables should have the type “float” or “int”, and variables with strings such as categories should have the type “object”. For example, “bore” and “stroke” variables are numerical values that describe the engines, so we should expect them to be of the type “float” or “int”; however, they are shown as type “object”. We have to convert data types into a proper format for each column using the “astype()” method.</p><p>Convert data types to the proper format</p><pre>df[[&quot;bore&quot;, &quot;stroke&quot;]] = df[[&quot;bore&quot;, &quot;stroke&quot;]].astype(&quot;float&quot;)<br>df[[&quot;normalized-losses&quot;]] = df[[&quot;normalized-losses&quot;]].astype(&quot;int&quot;)<br>df[[&quot;price&quot;]] = df[[&quot;price&quot;]].astype(&quot;float&quot;)<br>df[[&quot;peak-rpm&quot;]] = df[[&quot;peak-rpm&quot;]].astype(&quot;float&quot;)</pre><p>Let us list the columns after the conversion</p><pre>df.dtypes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*s8ouq5WQqd7CuOBdOjI70A.png" /><figcaption>Data types after conversion.</figcaption></figure><p>Now we have finally obtained the cleaned dataset with no missing values with all data in its proper format.</p><h4>Data Standardization</h4><p>Data is usually collected from different agencies in different formats. (Data standardization is also a term for a particular type of data normalization where we subtract the mean and divide by the standard deviation.)</p><p><strong>What is Standardization?</strong></p><p>Standardization is the process of transforming data into a common format, allowing the researcher to make a meaningful comparison.</p><p><strong>Example</strong></p><p>Transform mpg to L/100km:</p><p>In our dataset, the fuel consumption columns “city-mpg” and “highway-mpg” are represented by mpg (miles per gallon) unit. Assume we are developing an application in a country that accepts the fuel consumption with L/100km standard.</p><p>We will need to apply <strong>data transformation</strong> to transform mpg into L/100km.</p><p>The formula for unit conversion is:</p><p>L/100km = 235/mpg</p><p>We can do many mathematical operations directly in Pandas.</p><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sCL8sCLTBMApI_8q5GstCg.png" /><figcaption>Data frame after <strong>Standardization</strong></figcaption></figure><pre># Convert mpg to L/100km by mathematical operation (235 divided by mpg)<br>df[&#39;city-L/100km&#39;] = 235/df[&quot;city-mpg&quot;]</pre><pre># check your transformed data<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8IGDugZiw3QZYXw2jJOww.png" /><figcaption>Data Frame after Transformation</figcaption></figure><p>Transform mpg to L/100km in the column of “highway-mpg” and change the name of the column to “highway-L/100km”.</p><pre># transform mpg to L/100km by mathematical operation (235 divided by mpg)<br>df[&quot;highway-mpg&quot;] = 235/df[&quot;highway-mpg&quot;]</pre><pre># rename column name from &quot;highway-mpg&quot; to &quot;highway-L/100km&quot;<br>df.rename(columns={&#39;&quot;highway-mpg&quot;&#39;:&#39;highway-L/100km&#39;}, inplace=True)</pre><pre># check your transformed data<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ei2xMYkEdW9nkR7cWQYq2g.png" /><figcaption>Data frame after transformation.</figcaption></figure><h4>Data Normalization</h4><p><strong>Why Normalization?</strong></p><p>Normalization is the process of transforming values of several variables into a similar range. Typical normalizations include scaling the variable so the variable average is 0, scaling the variables so the variance is 1, or scaling the variable so the variable values range from 0 to 1.</p><p><strong>Example</strong></p><p>To demonstrate normalization, let’s say we want to scale the columns “length”, “width”, and “height”.</p><p><strong>Target: </strong>Would like to normalize those variables so their value ranges from 0 to 1.</p><p><strong>Approach:</strong> Replace original value by (original value)/(maximum value).</p><pre># replace (original value) by (original value)/(maximum value)<br>df[&#39;length&#39;] = df[&#39;length&#39;]/df[&#39;length&#39;].max()<br>df[&#39;width&#39;] = df[&#39;width&#39;]/df[&#39;width&#39;].max()</pre><p>Normalize the column “height”.</p><pre>df[&#39;height&#39;] = df[&#39;height&#39;]/df[&#39;height&#39;].max()</pre><pre># show the scaled columns<br>df[[&quot;length&quot;,&quot;width&quot;,&quot;height&quot;]].head()</pre><p>Here we can see we’ve normalized “length”, “width”, and “height” in the range of [0,1].</p><h4>Binning</h4><p><strong>Why binning?</strong></p><p>Binning is a process of transforming continuous numerical variables into discrete categorial “bins” for grouped analysis.</p><p><strong>Example:</strong></p><p>In our dataset, “horsepower” is a real-valued variable ranging from 48 to 288 and it has 59 unique values. What if we only care about the price difference between cars with high horsepower, medium horsepower, and little horsepower (3 types)? Can we rearrange them into three “bins” to simplify the analysis?</p><p>We will use the pandas method “cut” to segment the “horsepower” column into 3 bins.</p><p><strong>Example of Binning Data In Pandas</strong></p><p>Covert data to correct format:</p><pre>df[&quot;horsepower&quot;]=df[&quot;horsepower&quot;].astype(int, copy=True)</pre><p>Let’s plot the histogram of horsepower to see what the distribution of horsepower looks like.</p><pre>%matplotlib inline<br>import matplotlib as plt<br>from matplotlib import pyplot<br>plt.pyplot.hist(df[&quot;horsepower&quot;])</pre><pre># set x/y labels and plot title<br>plt.pyplot.xlabel(&quot;horsepower&quot;)<br>plt.pyplot.ylabel(&quot;count&quot;)<br>plt.pyplot.title(&quot;horsepower bins&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*WnZuHVGv96wQsR-lNV2iyg.png" /><figcaption>Text(0.5, 1.0, “horsepower bins”)</figcaption></figure><p>We would like 3 bins of equal size bandwidth so we use NumPy&#39;s linspace(start_value, end_value, numers_generated) function.</p><p>Since we want to include the minimum value of horsepower, we want to set start_value = min(df[“horsepower”]).</p><p>Since we want to include the maximum value of horsepower, we want to set end_value = max(df[“horsepower”]).</p><p>Since we are building 3 bins of equal length, there should be 4 dividers, so numbers_generated = 4.</p><p>We build a bin array with a minimum value to a maximum value by using the bandwidth calculated above. The values will determine when one bin ends and another begins.</p><pre>bins = np.linspace(min(df[&quot;horsepower&quot;]), max(df[&quot;horsepower&quot;]), 4)<br>bins</pre><p>Output: array([48. , 119.33333333, 190.66666667, 262. ])</p><p>We set group names:</p><pre>group_names = [“Low”, “Medium”, “High”]</pre><p>We apply the function “cut” to determine what each value of df[&quot;horsepower&quot;] belongs to.</p><pre>df[&#39;horsepower-binned&#39;] = pd.cut(df[&#39;horsepower&#39;], bins, labels=group_names, include_lowest=True )</pre><pre>df[[&#39;horsepower&#39;,&#39;horsepower-binned&#39;]].head(20)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*XU3fkJ31_UQCjZDzGRIRDg.png" /><figcaption>A binned data frame.</figcaption></figure><p>Let’s see the number of vehicles in each bin:</p><pre>df[&quot;horsepower-binned&quot;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*MGmU0-o0CTn_VfHzIkcDWQ.png" /><figcaption>value counts of vehicles in each bin.</figcaption></figure><p>Let’s plot the distribution of each bin:</p><pre>%matplotlib inline<br>import matplotlib as plt<br>from matplotlib import pyplot<br>pyplot.bar(group_names, df[&quot;horsepower-binned&quot;].value_counts())</pre><pre># set x/y labels and plot title<br>plt.pyplot.xlabel(&quot;horsepower&quot;)<br>plt.pyplot.ylabel(&quot;count&quot;)<br>plt.pyplot.title(&quot;horsepower bins&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*yn15Vg-2633XJK2TNv6t_g.png" /><figcaption>Distribution of bin.</figcaption></figure><p>Look at the data frame above carefully. You will find that the last column provides the bins for “horsepower” based on 3 categories (“Low”, “Medium”, and “High”).</p><p>We successfully narrowed down the intervals from 59 to 3!</p><h4>Indicator Variable (or Dummy Variable)</h4><p><strong>What is an indicator variable?</strong></p><p>An indicator variable (or dummy variable) is a numerical variable used to label categories. They are called “dummies” because the numbers themselves don’t have inherent meaning.</p><p><strong>Why do we use indicator variables?</strong></p><p>We use indicator variables so we can use categorical variables for regression analysis in the later modules.</p><p><strong>Example</strong></p><p>We see the column “fuel-type” has two unique values “gas” and “diesel”. Regressions don’t understand words, only numbers. To use this attribute in regression analysis, we convert “fuel-type” to indicator variables.</p><p>We will use panda’s method get_dummies to assign numerical values to different categories of fuel types.</p><pre>df.columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*7TksshElmbqBTAF2qzP8rQ.png" /><figcaption>Column names</figcaption></figure><p>Get the indicator variables and assign them to data frame “dummy_variable_1”:</p><pre>dummy_variable_1 = pd.get_dummies(df[&quot;fuel-type&quot;])<br>dummy_variable_1.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*bBxwgHnrCI7ci8-xZABREg.png" /></figure><p>Change the column name for clarity:</p><pre>dummy_variable_1.rename(columns={&#39;gas&#39;:&#39;fuel-type-gas&#39;, &#39;diesel&#39;:&#39;fuel-type-diesel&#39;}, inplace=True)</pre><pre>dummy_variable_1.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*8xvvBERUGNYpSAAqO7y8Gg.png" /></figure><p>In the data frame, column “fuel-type” has values for “gas” and “diesel” as 0s and 1s now.</p><pre># merge data frame &quot;df&quot; and &quot;dummy_variable_1&quot;<br>df = pd.concat([df, dummy_variable_1], axis=1)</pre><pre># drop original column &quot;fuel-type&quot; from &quot;df&quot;<br>df.drop(&quot;fuel-type&quot;, axis = 1, inplace=True)</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zf1ZxmpF7jK8ZxpD04tZwA.png" /><figcaption>Data frame after creating dummy variables.</figcaption></figure><p>The last two columns are now the indicator variable representation of the fuel-type variable. They’re all 0s and 1s now.</p><p>Similar to before, let’s create an indicator variable for the column “aspiration”.</p><pre># get indicator variables of aspiration and assign it to data frame &quot;dummy_variale_2&quot;<br>dummy_variable_2 = pd.get_dummies(df[&quot;aspiration&quot;])</pre><pre># change column names for clarity<br>dummy_variable_2.rename(colums={&quot;std&quot;:&quot;aspiration-std&quot;, &quot;turbo&quot;:&quot;aspiration-turbo&quot;}, inplace=True)</pre><pre># show first 5 instances of data frame &quot;dummy_variable_1&quot;<br>dummy_variable_2.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*VjAROrJ1G0aHkcq2Qqag1w.png" /></figure><p>Let’s merge the new data frame to the original data frame, then drop the column “aspiration”.</p><pre># merge the new dataframe to the original dataframe<br>df = pd.concat([df, dummy_variable_2], axis=1)</pre><pre># drop original column &quot;aspiration&quot; from &quot;df&quot;<br>df.drop(&quot;aspiration&quot;, axis=1, inplace=True)</pre><pre># Display new data frame<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAZ6x0D-HVm9y-NOxIxvsA.png" /><figcaption>Clean data frame</figcaption></figure><h3>Save Dataset</h3><p>Correspondingly, Pandas enables us to save the dataset to CSV. By using the dataframe.to_csv() method, we can add the file path and name along with quotation marks in the brackets.</p><p>For example, if you would like to save the data frame df as automobile.csv to your local machine, you may use the syntax below, where index = False means the row names will not be written.</p><pre>df.to_csv(&quot;clean_df.csv&quot;, index=False)</pre><h3>Summary</h3><ol><li><strong>Identify and Handle Missing Values: </strong>Drop rows with incomplete information and impute missing data using the mean values.</li><li><strong>Understand Data Formating:</strong> Wrangle features in a dataset and make them meaningful for data analysis.</li><li><strong>Apply normalization to a dataset:</strong> By understanding the relevance of using feature scaling on our data and how normalization and standardization have varying effects on your data analysis.</li></ol><p>In the <a href="https://medium.com/@varunsrivatsa27/data-analysis-with-python-exploratory-data-analysis-eda-part-2-c2460874d49f">next part</a>, let’s see what is meant by exploratory data analysis, and how we can perform computations on the data to calculate basic descriptive statistical information, and use that information to better understand the distribution of the data.</p><p>Please feel free to refer to the <a href="https://github.com/NXture/automobile-price-prediction/blob/master/Data-Wrangling.ipynb">Notebook</a> as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc571ab55259" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the art of visualization to communicate and share data. ]]></title>
            <link>https://medium.com/@varunsrivatsa27/using-the-art-of-visualization-to-communicate-and-share-data-10f617111bce?source=rss-35df1a22f691------2</link>
            <guid isPermaLink="false">https://medium.com/p/10f617111bce</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[graphic-design]]></category>
            <dc:creator><![CDATA[Varun Srivatsa]]></dc:creator>
            <pubDate>Thu, 16 Jun 2022 15:12:19 GMT</pubDate>
            <atom:updated>2022-06-16T15:12:19.802Z</atom:updated>
            <content:encoded><![CDATA[<p>As a Data Analyst, you’ll be exposed to a lot of data. People learn and absorb data in so many different ways, and one of the most effective ways this can happen is through visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rkWGLUj4K54lMSam" /><figcaption>Photo by <a href="https://unsplash.com/@isaacmsmith?utm_source=medium&amp;utm_medium=referral">Isaac Smith</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Data visualization (sometimes referred to as a “data viz”) is the graphical representation and presentation of data.</strong> In reality, it’s just putting information into an image to make it easier for others to understand. If you’ve ever looked at any kind of map, whether it’s paper or online, then you know exactly how helpful visuals could be.</p><p>Data visualizations are definitely having a moment right now. Online we are surrounded by images that show information in all kinds of ways, but the history of data visualization goes back way further than the Web.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ajktNBL0hv1SVm0zAoD10g.jpeg" /><figcaption>Cantino planisphere — Wikipedia</figcaption></figure><p>Visualizing data begin long ago with maps, which are the visual representation of geographic data. Above is the map of the known world from 1502. Map makers continued to improve their visualizations as new lands were charted. New data were collected about those locations, and new methods for visualizing the data were created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*QDEm-Uv0c7HyGEenupm2Uw.png" /><figcaption>Chart by William Playfair (1821) depicting wages line plot prices of wheat</figcaption></figure><p>Scientists and mathematicians began to truly embrace the idea of arranging data visually in the 1700s and 1800s. The bar graph mentioned above is from 1821 and it doesn’t look too different from the bar graphs that we see today. But since the beginning of the digital age of data analytics in the 1990s, the scope and reach of visualizations have grown along with the data they graphically represent. As we keep learning how to more efficiently communicate with visuals, the quality of our insights continues to grow too.</p><p>Today we can quantify human behavior through data, and we’ve learned to use computers to collect, analyze and visualize that data. As an analyst in today’s world, you’ll probably split your time with data visuals in two ways:</p><ol><li><em>Looking at visuals in order to understand and draw conclusions about data.</em></li><li><em>Creating visuals from raw to tell a story.</em></li></ol><p>Either way, it’s always good to keep in mind that data visualizations will be your key to success. This is especially true once you reach the point where you’re ready to present the results of your data analysis to an audience. Getting people to understand your vision and thought process can feel challenging. But a well-made data visualization has the power to change people’s minds. Plus, it can help someone who doesn’t have the same technical background or experience as you form their own opinions. So here’s a quick rule for creating a visualization.</p><blockquote><strong>Your audience should know exactly what they’re looking at within the first five seconds of seeing it.</strong></blockquote><p>Basically, this means the visual should be clear and easy to follow. In the five seconds after that, your audience should understand the conclusion your visualization is making. Even if they aren’t totally familiar with the research you’ve been doing. They might not agree with your conclusion, and that’s okay. You can always use their feedback to adjust your visualization and go back to the data to do further analysis.</p><p>So now let’s talk about what we have to do to create a visualization that’s understandable, effective, and, most importantly, convincing. Let’s start from the beginning. Data visualizations are a helpful tool for fitting a lot of information into a small space. To do this, you first need to structure and organize your thoughts. Think about your objectives and the conclusions you’ve reached after sorting through data. Then think about the patterns you’ve noticed in the data, the things that surprised you, and, of course, how all of this fits together into your analysis. Identifying the key elements of your findings help set the stage for how you should organize your presentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1GPd6sASFpVz39y87BYdCA.png" /><figcaption>Data visualization made by David McCandless</figcaption></figure><p>Check out this data visualization made by David McCandless, a well-known data journalist. This graphic includes four key elements: the <strong>information</strong> or <strong>data</strong>, the <strong>story</strong>, the <strong>goal</strong>, and the <strong>visual</strong> form. It’s arranged in a four-part Venn diagram, which tells us that all four elements are needed for successful visualization.</p><p>Understanding data is crucial because it is a key building block for your visualization. The story or concept adds meaning to the data and makes it interesting, remember that the story and the data combined provide an outline of what you’re trying to show. The goal or function makes the data both useful and usable, the visual form creates both beauty and structure. With just two elements, you can create a rough sketch of a visual. This could work if you’re at an early stage, but won’t give you a complete visualization because you’d be missing other key elements. Even using three elements gets you closer, but you’re not quite finished. For example, if you combine information, goal, and visual form without any story, your visual will probably look fine, but it won’t be interesting. On their own, each element has value, but visualizations only become truly powerful and effective when you combine all four elements in a way that makes sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*pidxnwGWJ2cuYz3bXw_niQ.png" /><figcaption>Elements for successful visualization</figcaption></figure><p>And when you think about all of these elements together, you can create something meaningful for your audience. That’s why it’s so important for you as the analyst to pay close attention to each element. Other people might not know or understand the exact steps you took to come to the conclusions you’ve made, but that shouldn’t stop them from understanding your reasoning.</p><p>Basically, an effective data visualization should lead viewers to reach the same conclusion you did, but much more quickly. Because of the age we live in, we’re constantly being shown different ways to view and absorb information. This means that you’ve already seen lots of visuals you can reference as you design your own visualizations. You have the power to tell convincing stories that could change opinions and shift mindsets. That’s pretty cool. But you also have the responsibility to pay attention to the perspectives of others as you create these stories. So it’s important to always keep that in mind.</p><h4>Further reading</h4><ul><li><a href="https://www.ted.com/talks/david_mccandless_the_beauty_of_data_visualization?language=en#t-150183"><strong>The beauty of data visualization</strong></a><strong>:</strong> In this video, David McCandless explains the need for design to not just be beautiful, but for it to be meaningful as well. Data visualization must be able to balance function and form for it to be relevant to your audience.</li><li><a href="https://artscience.blog/home/the-mccandless-method-of-data-presentation"><strong>‘The McCandless Method’ of data presentation</strong></a><strong>:</strong> At first glance, this blog appears to be written by a David McCandless fan, and it is. However, it contains very useful information and provides an in-depth look at the 5-step process that McCandless uses to present his data.</li><li><a href="https://informationisbeautiful.net/"><strong>Information is beautiful</strong></a><strong>:</strong> Founded by McCandless himself, this site serves as a hub of sample visualizations that make use of the McCandless method. Explore data from the news, science, the economy, and so much more, and learn how to make visual decisions based on facts from all kinds of sources.</li><li><a href="https://informationisbeautiful.net/beautifulnews/"><strong>Beautiful daily news</strong></a><strong>:</strong> In this McCandless collection, explore uplifting trends and statistics that are beautifully visualized for your creative enjoyment. A new chart is released every day so be sure to visit often to absorb the amazing things happening all over the world.</li><li><a href="https://www.amazon.com/Street-Journal-Guide-Information-Graphics/dp/0393072959"><strong>The Wall Street Journal Guide to Information Graphics: The Dos and Don’ts of Presenting Data, Facts, and Figures</strong></a><strong>:</strong> This is a comprehensive guide to data visualization, including chapters on basic data visualization principles and how to create useful data visualizations even when you find yourself in a tricky situation. This is a useful book to add to your data visualization library, and you can reference it over and over again.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10f617111bce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to overcome the challenges posed by insufficient data]]></title>
            <link>https://medium.com/@varunsrivatsa27/how-to-overcome-the-challenges-posed-by-insufficient-data-c2a7d980c227?source=rss-35df1a22f691------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2a7d980c227</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[business]]></category>
            <dc:creator><![CDATA[Varun Srivatsa]]></dc:creator>
            <pubDate>Wed, 11 May 2022 08:20:09 GMT</pubDate>
            <atom:updated>2022-05-11T08:20:09.516Z</atom:updated>
            <content:encoded><![CDATA[<p>Every analyst has been in a situation where there is insufficient data to help with their business objective. Considering how much data is generated every day, it may be hard to believe, but it’s true. So let’s discuss what you can do when you have insufficient data. We’ll cover how to set limits for the scope of your analysis and what data you should include.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G4r93P2v11C8ycd2" /><figcaption>Photo by <a href="https://unsplash.com/@krisroller?utm_source=medium&amp;utm_medium=referral">Kristopher Roller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Dealing with insufficient data</h3><p>Imagine yourself as a data analyst at a support center. Every day, you receive customer questions logged in as support tickets.</p><p>You were asked to forecast the number of support tickets coming in per month to figure out how many additional people they needed to hire. It was important that you had sufficient data spanning back at least a couple of years because you had to account for year-to-year and seasonal changes. If you just had the current year’s data available, you wouldn’t have known that a spike in January is common and has to do with people asking for refunds after the holidays. Because you had sufficient data, you were able to suggest that we should hire more people in January to prepare.</p><p>Challenges are bound to come up, but the good news is that once you know your business objective, you’ll be able to recognize whether you have enough data. And if you don’t, you’ll be able to deal with it before you start your analysis. Now, let’s check out some of those limitations you might come across and how you can handle different types of insufficient data.</p><p>Say you’re working in the tourism industry, and you need to find out which travel plans are searched most often. If you only use data from one booking site, you’re limiting yourself to data from just one source. Other booking sites might show different trends that you would want to consider for your analysis. If a limitation like this impacts your analysis, you can stop and go back to your stakeholders to figure out a plan. If your data set keeps updating, that means the data is still incoming and might not be complete. So if there’s a brand new tourist attraction that you’re analyzing interest and attendance for, there’s probably not enough data. Or you can check with the stakeholders and ask about adjusting the objective. For example, you might analyze trends from week to week instead of month to month. You could also base your analysis on trends over the past three months and say, “Here’s what attendance at the attraction for month four could look like.” You might not have enough data to know if this number is too low or too high. But you would tell stakeholders that it’s your best estimate based on the data that you currently have.</p><p>On the other hand, your data could be older and no longer be relevant. Outdated data about customer satisfaction won’t include the most recent response. So you’ll be relying on the ratings for hotels or vacation rentals that might no longer be accurate. In this case, your best bet might be to find a new data set to work with.</p><p>Data that is geographically limited could also be unreliable. if your company is global, you wouldn’t want to use data limited to travel in just one country. You would want a data set that includes all countries.</p><h4>Types of insufficient data</h4><ol><li>Data from only one source</li><li>Data that keeps updating</li><li>Outdated data</li><li>Geographically-limited data</li></ol><p>These are just a few of the most common limitations you’ll come across and some ways you can address them.</p><h4>Ways to address insufficient data</h4><ol><li>Identify trends with the available data</li><li>Wait for more data if time allows</li><li>Talk with stakeholders and adjust your objective</li><li>Look for a new dataset</li></ol><p>The need to take these steps will depend on your role in your company and possibly the needs of the wider industry. But learning how to deal with insufficient data is always a great way to set yourself up for success.</p><h3>What to do when you discover a problem with your data</h3><p>When you are getting ready for data analysis, you might realize you don’t have the data you need or you don’t have enough of it. In some cases, you can use what is known as proxy data in place of the real data. Think of it as substituting oil for butter in a recipe when you don’t have butter. In other cases, there is no reasonable substitute and your only option is to collect more data.</p><p>Consider the following data issues and suggestions on how to work around them.</p><h4>Data issue 1: no data</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c9c43671906eb611ca028240e3a189e/href">https://medium.com/media/4c9c43671906eb611ca028240e3a189e/href</a></iframe><h4>Data issue 2: too little data</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acb7f899b8a894395d1741d2722c1377/href">https://medium.com/media/acb7f899b8a894395d1741d2722c1377/href</a></iframe><h4>Data issue 3: wrong data, including data with errors*</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86d0679a858cba511e9a920469d6f717/href">https://medium.com/media/86d0679a858cba511e9a920469d6f717/href</a></iframe><p><em>* Important note: sometimes data with errors can be a warning sign that the data isn’t reliable. Use your best judgment.</em></p><h4>Use the following decision tree as a reminder of how to deal with data errors or not enough data:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IO-ZWR3rfvGRve03Esl3UQ.png" /></figure><h4>Thankful? 😊</h4><p><em>A Clap 👏 might help this reach more audience!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2a7d980c227" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Metadata is just as important as the data itself]]></title>
            <link>https://medium.com/@varunsrivatsa27/metadata-is-just-as-important-as-the-data-itself-bdd2f5be0ab9?source=rss-35df1a22f691------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdd2f5be0ab9</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Varun Srivatsa]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 20:16:05 GMT</pubDate>
            <atom:updated>2022-04-24T20:16:05.845Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kg32t37EWwIm7A-W" /><figcaption>Photo by <a href="https://unsplash.com/@purzlbaum?utm_source=medium&amp;utm_medium=referral">Claudio Schwarz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Data Analytics</strong>, by design, is a field that thrives on collecting and organizing data.</p><p>Take a look at any data you find. What is it? Where did it come from? Is it useful? How do you know? This is where <strong>metadata</strong> comes in to provide a deeper understanding of the data. To put it simply, metadata is data about data. In database management, it provides information about other data and helps data analytics interpret the contents of the data within a database.</p><p>Regardless of whether you are working with a large or small quantity of data, metadata is the mark of a knowledgeable analytics team, helping to communicate about data across he business and making it easier to reuse data. In essence, metadata tells the who, what, when, where, which, how, and why of data.</p><h3>Elements of metadata</h3><p>Before looking at metadata examples, it is important to understand what type of information metadata typically provides.</p><ol><li><strong>Title and description:</strong> What is the name of the file or website you are examining? What type of content does it contain?</li><li><strong>Tags and categories:</strong> What is the general overview of the data that you have? Is the data indexed or described in a specific way?</li><li><strong>Who created it and when:</strong> Where did the data come from, and when was it created? Is it recent, or has it existed for a long time?</li><li><strong>Who last modified it and when:</strong> Were any changes made to the data? If yes, were the modifications recent?</li><li><strong>Who can access or update it:</strong> Is this dataset public? Are special permissions needed to customize or modify the dataset?</li></ol><h3>Examples of metadata</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g3B2-GpfMozuqVBd" /><figcaption>Photo by <a href="https://unsplash.com/@emilymorter?utm_source=medium&amp;utm_medium=referral">Emily Morter</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In today’s digital world, metadata is everywhere, and it is becoming a more common practice to provide metadata on a lot media and information you interact with. Here are some real-world examples of where to find metadata:</p><h4>Photos</h4><p>Whenever a photo is captured with a camera, metadata such as camera filename, date, time, and geolocation are gathered and saved with it.</p><h4>Emails</h4><p>When an email is sent or received, there is lots of visible metadata such as subject line, the sender, the recipient and data and time sent. There is also hidden metadata that includes server names, IP addresses, HTML format, and software details.</p><h4>Spreadsheets and documents</h4><p>Spreadsheets and documents are already filled with a considerable amount of data so it is no surprise that metadata would also accompany them. Titles, author, creation date, number of pages, user comments as well as names of tabs, tables, and columns are all metadata that one can find in spreadsheets and documents.</p><h4>Websites</h4><p>Every web page has a number of standard metadata fields, such a tags and categories, site creator’s name, web page title and description, time of creation and any iconography.</p><h4>Digital files</h4><p>Usually, if you right click on any computer file, you will see its metadata. This could consist of file name, file size, data of creation and modification, and type of file.</p><h4>Books</h4><p>Metadata is not only digital. Every book has a number of standard metadata on the covers and inside that will inform you of its title, author’s name, a table of contents, publisher information, copyright description, index, and brief description of the book’s contents.</p><h3>Data as you know it</h3><p>Knowing the content and context of your data, as well as how it is structured, is every valuable in your career as a data analyst. When analysing data, it is important to always understand the full picture. It is not just about the data you are viewing, but how the data comes together. Metadata ensures that you are able to find, use, preserve, and reuse data in the future. Remember, it will be your responsibility to manage and make use of data in its entirety.</p><h4><em>Thankful? 😊</em></h4><p><em>A Clap 👏 might help this reach more audience!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdd2f5be0ab9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The importance of identifying good data sources, which ROCCCs ]]></title>
            <link>https://medium.com/@varunsrivatsa27/the-importance-of-identifying-good-data-sources-which-rocccs-e6c8d7350339?source=rss-35df1a22f691------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6c8d7350339</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[decision-making]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Varun Srivatsa]]></dc:creator>
            <pubDate>Wed, 16 Mar 2022 15:46:56 GMT</pubDate>
            <atom:updated>2022-03-16T15:46:56.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f9UcNlClOCnExOjA" /><figcaption>Photo by <a href="https://unsplash.com/@volkanolmez?utm_source=medium&amp;utm_medium=referral">Volkan Olmez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>What is good? Let me put it this way. If I asked you to name a good song, I might not like it 🤷‍♂️. That’s because good is subjective. What I think is good and what you think is good might be different. So what about good sources? Are those subjective, too?</p><p>In some ways they are, but luckily, there’s some best practices to follow that’ll help us measure the reliability of data sets before you use them.</p><p>I think we can all agree that we all want good data. The more high quality data we have, the more confidence we can have in our decisions. Let’s see how we can go about finding and identifying good data sources.</p><p>A process I like to call R-O-C-C-C, not ROCK. Okay, I just made that up, but I believe acronyms are a really great way to help new information to stick in the brain. Now let’s get started.</p><h4>R for reliable.</h4><p>Like a good friend, good data sources are reliable. With this data you can trust that you’re getting accurate, complete and unbiased information that’s been vetted and proven fit for use.</p><h4>O is for original.</h4><p>There’s a good chance you’ll discover data through a second and third party source. To make sure you’re dealing with good data, be sure to validate it with the original source.</p><h4>Time for the first C. C is for comprehensive.</h4><p>The best data sources contain all critical information need to answer the question or find the solution. Think about it like this. You wouldn’t want to work for a company just because you found one great online review about it. You’d research every aspect of the organization to make sure it was the right fit. It’s important to do the same for your data analysis.</p><h4>The next C is for current.</h4><p>The usefulness of the data decreases as time passes. If you wanted to invite all current clients to a business event, you wouldn’t use a 10-year-old client list. The same goes for data. The best data sources are current and relevant to the task in hand.</p><h4>The last C is for cited.</h4><p>If you’ve ever told a friend where you heard that a new movie sequel was in the works, you’ve cited a source. Citing makes the information you’re providing more credible. When you’re choosing data source, think about three things. Who created the data set? Is it part of a credible organization? When was the data last refreshed?</p><p>If you have original data from a reliable organization and it is comprehensive, current, and cited, it <strong>ROCKS </strong>🤘, I mean it this time.</p><p>There’s a lots of places that are known for having good data. Your best bet is to go with the vetted public data sets, academic papers, financial data, and governmental agency data.</p><h3>What is “BAD” data?</h3><p>We found that if the data set is reliable, original, comprehensive, current and cited, it ROCCCs or more seriously it is good. Whereas, bad data sources are those which don’t ROCCC. They’re not reliable, original, comprehensive, current or cited. Even worse. they could be flat-out wrong or filled with human error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-1bH8qRXcBubCoPI" /><figcaption>Photo by <a href="https://unsplash.com/@saif71?utm_source=medium&amp;utm_medium=referral">Salman Hossain Saif</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Bad data can’t be trusted because it’s inaccurate, incomplete, or biased. This could be data that has sample selection bias because it doesn’t reflect the overall population. Or it could be data visualizations and graphs that are just misleading. So following points should be considered while examining a data.</p><p>If you can’t locate the original data source and you’re just relying on second or third party information, that can signal you may need to be extra careful in understanding your data.</p><p>Bad data sources are missing important information needed to answer the question or find the solution. What’s worse, they may contain human error, too.</p><p>Bad data sources are out of date and irrelevant. Many respected sources refresh their data regularly, giving you confidence that it’s the most current info available. For example, you can always trust <a href="https://data.gov/">Data.gov</a>, which is home to the U.S. government’s open data.</p><p>The last thing is to check whether your data source is cited or vetted. If it isn’t, it’s a no-go.</p><p>So to sum up, good data should be original data from a reliable organization, comprehensive, current, and cited. It should ROCCC! Otherwise, it’s bad data. If you need a great reliable data source, check out the <a href="https://www.census.gov/">U.S. Census Bureau</a>, which regularly updates their information.</p><p>It’s important for data analysts to understand and keep an eye out for bad data because it can have serious and lasting impacts. Whether it’s an incorrect conclusion leading to one bad business decision, or inaccurate information causing processes to fail and putting populations at risk, every good solution is found by avoiding bad data. For good data, stick with vetted public data sets, academic papers, financial data and governmental agency data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6c8d7350339" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The power of Data and Data-Driven decisions in Businesses]]></title>
            <link>https://medium.com/@varunsrivatsa27/the-power-of-data-and-data-driven-decisions-in-businesses-8be0212bbaf5?source=rss-35df1a22f691------2</link>
            <guid isPermaLink="false">https://medium.com/p/8be0212bbaf5</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Varun Srivatsa]]></dc:creator>
            <pubDate>Wed, 01 Dec 2021 17:23:45 GMT</pubDate>
            <atom:updated>2021-12-01T17:23:45.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PA6yMwJO57ZcPu4f" /><figcaption>Photo by <a href="https://unsplash.com/@grstocks?utm_source=medium&amp;utm_medium=referral">GR Stocks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data is everywhere. Today, we create so much data that scientists estimate 90 percent of the world’s data has been created in just the last few years.</p><p>Think of the potential here.</p><p>The more data we have, the bigger the problems we can solve and the more powerful our solutions can be. But responsibly gathering data is only part of the process.</p><p>We also have to turn data into knowledge that helps us make better solutions.</p><p>Now, let’s see why the accurate interpretation of data is key to data-driven decisions. We know that data is a powerful business tool and data analysts help their companies make data-driven decisions for great results. As a quick reminder, the goal of all data analysts is to use data to draw accurate conclusions and make good recommendations. That all starts with having complete, correct, and relevant data.</p><p>But keep in mind, it is possible to have solid data and still make the wrong choices. It is up to data analysts to interpret the data accurately.</p><h3><strong>When data is interpreted incorrectly, it can lead to huge losses. Consider the examples below.</strong></h3><h3>Coke launch failure</h3><p>In 1985, New Coke was launched, replacing the classic Coke formula. The company had done taste tests with 200,000 people and found that test subjects preferred the taste of New Coke over Pepsi, which had become a tough competitor. Based on this data alone, classic Coke was taken off the market and replaced with New Coke. This was seen as the solution to take back the market share that had been lost to Pepsi.</p><p>But as it turns out, New Coke was a massive flop and the company ended up losing tens of millions of dollars. How could this have happened with data that seemed correct? It is because the data wasn’t complete, which made it inaccurate. The data didn’t consider how customers would feel about New Coke replacing classic Coke. The company’s decision to retire classic Coke was a data-driven decision based on incomplete data.</p><h3>Mars orbiter loss</h3><p>In 1999, NASA lost the $125 million Mars Climate Orbiter, even though it had good data. The spacecraft burned to pieces because of poor collaboration and communication. The Orbiter’s navigation team was using the <strong>SI or metric system</strong> (newtons) for their force calculations, but the engineers who built the spacecraft used the <strong>English Engineering Units</strong> <strong>system</strong> (pounds) for force calculations.</p><p>No one realized a problem even existed until the Orbiter burst into flames in the Martian atmosphere. Later, a NASA review board investigating the root cause of the problem figured out that the issue was isolated to the software that controlled the thrusters. One program calculated the thrusters’ force in pounds; another program looking at the data assumed it was in newtons. The software controllers were making data-driven decisions to adjust the thrust based on 100% accurate data, but these decisions were wrong because of inaccurate assumptions when interpreting it. A conversion of the data from one system of measurement to the other could have prevented the loss.</p><h3><strong>When data is used strategically, businesses can transform and grow their revenue📈. Consider the examples below.</strong></h3><h3>Crate and Barrel</h3><p>At Crate and Barrel, online sales jumped more than 40% during stay-at-home orders to combat the global pandemic. Currently, online sales make up more than 65% of their overall business. They are using data insights to accelerate their digital transformation and bring the best of online and offline experiences together for customers.</p><p>BigQuery enables Crate and Barrel to “draw on ten times [as many] information sources<strong> </strong>(compared to a few years ago) which are then analyzed and transformed into actionable insights that can be used to influence the customer’s next interaction. And this, in turn, drives revenue.”</p><p>Read more about Crate and Barrel’s data strategy in <a href="https://www.thinkwithgoogle.com/future-of-marketing/digital-transformation/crate-and-barrel-digital-customer-experiences/"><em>How one retailer’s data strategy powers seamless customer experiences</em></a><em>.</em></p><h3>PepsiCo</h3><p>Since the days of the New Coke launch, things have changed dramatically for beverage and other consumer packaged goods (CPG) companies.</p><p>PepsiCo “hired analytical talent and established cross-functional workflows around an infrastructure designed to put consumers’ needs first. Then [they] set up the right processes to make critical decisions based on data and technology use cases. Finally, [they] invested in the right technology stack and platforms so that data could flow into a central cloud-based hub. This is critical. When data comes together, [they] develop a holistic understanding of the consumer and their journeys.”</p><p>Read about how PepsiCo is delivering a more personal and valuable experience to customers using data in <a href="https://www.thinkwithgoogle.com/marketing-strategies/data-and-measurement/pepsi-digital-transformation/"><em>How one of the world’s biggest marketers ripped up its playbook and learned to anticipate intent</em></a><em>.</em></p><h3>Key skills for triumphant results</h3><p>As a data analyst, your own skills and knowledge will be the most important part of any analysis project. It is important for you to keep a data-driven mindset, ask lots of questions, experiment with many different possibilities, and use both logic and creativity along the way. You will then be prepared to interpret your data with the highest levels of care and accuracy.</p><p>Note that there is a difference between making a decision with incomplete data and making a decision with a small amount of data. You learned that making a decision with incomplete data is dangerous. But sometimes accurate data from a small test can help you make a good decision.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8be0212bbaf5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>