<?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 Shambhu Gupta on Medium]]></title>
        <description><![CDATA[Stories by Shambhu Gupta on Medium]]></description>
        <link>https://medium.com/@kg.shambhu?source=rss-eb0e7e2ccaff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VTQN-hqsswQBf_Hm</url>
            <title>Stories by Shambhu Gupta on Medium</title>
            <link>https://medium.com/@kg.shambhu?source=rss-eb0e7e2ccaff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:11:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kg.shambhu/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[3 Techniques for Building a Machine Learning Regression Model from a Multivariate Nonlinear Dataset]]></title>
            <link>https://medium.com/data-science/3-techniques-for-building-a-machine-learning-regression-model-from-a-multivariate-nonlinear-dataset-88b25fc24ad5?source=rss-eb0e7e2ccaff------2</link>
            <guid isPermaLink="false">https://medium.com/p/88b25fc24ad5</guid>
            <category><![CDATA[nonlinear-data]]></category>
            <category><![CDATA[multivariate-regression]]></category>
            <category><![CDATA[polynomial-regression]]></category>
            <category><![CDATA[data-transformation]]></category>
            <category><![CDATA[nonlinear-regression]]></category>
            <dc:creator><![CDATA[Shambhu Gupta]]></dc:creator>
            <pubDate>Wed, 24 Aug 2022 11:55:24 GMT</pubDate>
            <atom:updated>2022-09-02T16:42:11.798Z</atom:updated>
            <content:encoded><![CDATA[<h4>Everything about Data Transformation, Polynomial Regression, and Nonlinear Regression</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P5TNcCkSYH2WIxrJ" /><figcaption>Photo by <a href="https://unsplash.com/@lidianikole?utm_source=medium&amp;utm_medium=referral">Lidia Estaban</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A Simple linear regression (SLR) model is simple to construct when the relationship between the target variable and the predictor variables is linear. When there is a nonlinear relationship between a dependent variable and independent variables, things become more complicated. In this article, I’ll show you three different approaches to building a regression model on the same nonlinear dataset:</p><p>1. Polynomial regression<br>2. Data transformation<br>3. Nonlinear regression</p><h3>The Dataset:</h3><p>The dataset that I have considered has been taken from Kaggle: <a href="https://www.kaggle.com/datasets/yasserh/student-marks-dataset">https://www.kaggle.com/datasets/yasserh/student-marks-dataset</a></p><p>The data consists of Marks of students including their study time &amp; number of courses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*IeozN4MwY-6uydsnnMu6PQ.png" /><figcaption>DataFrame details (Author Image)</figcaption></figure><p>If you examine the relationships of the target variables “Marks” w.r.to study time and number of courses, you will find that the relationship is non-linear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfMJGtEnu79R5BWA4nXt2w.png" /><figcaption>Nonlinear relationship between Dependent and Independent variables (Author Image)</figcaption></figure><h3>Challenge with a Simple Linear Model on this Dataset</h3><p>I tried to build a linear regression model using sklearn LinearRegression() model. I defined a function to calculate various metrics for the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/694c1c357c6c89d9588b84059c81978f/href">https://medium.com/media/694c1c357c6c89d9588b84059c81978f/href</a></iframe><p>and when I called this function for my model, I got the below output.</p><p><em>R2-Square Value: 0.94<br>RSS: 1211.696<br>MSE: 12.117<br>EMSE: 3.481</em></p><p>94% r2-score is not bad, but we will shortly see that this can get better with a non-linear regression model. The problem is more with the assumptions behind the linear regression model.</p><p><strong>SLR Assumption 1: Homoscedasticity</strong></p><p>Homoscedasticity means that the residuals have equal or almost equal variance across the regression line. By plotting the error terms with predicted terms we should confirm that there is no pattern in the error terms. However, in this case, we can clearly see that error terms has a certain shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGaXyl92tvBn_I_HEvEZ1w.png" /><figcaption>Homoscedasticity (Author Image)</figcaption></figure><p><strong>SLR Assumption 2: Error terms are normally distributed</strong></p><p>A bell-shaped distribution with a normal or nearly normal distribution should ideally be visible for the error terms. However, from the graph below, it is clear that we have a bi-model distribution. As a result, in this case, the assumptions of linear regression were broken.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vyynjfomTcHW1QfyJ6UAVw.png" /><figcaption>Distribution of Error Terms (Author Image)</figcaption></figure><p><strong>SLR Assumption 3: Error terms are independent of each other</strong></p><p>The auto-correlation between error terms should therefore not exist. However, the figures below reveal that the error terms appear to exhibit some degree of auto-correlation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YIIqos2L3ix4ld8tBXjEcQ.png" /><figcaption>Auto-Correlations among error terms (Author Image)</figcaption></figure><p>So far, We have verified that the data is nonlinear, yet we still build an SLR equation. Although we achieved a respectable r2-score of 94%, none of the SLR assumptions are met. SLR is therefore not a wise solution for this type of data. We will now investigate other techniques for improving the model on the same dataset.</p><h3>1. Modeling non-linear relationship using Polynomial Regression Model</h3><p>Non-linear regressions are a relationship between independent variables <strong><em>x</em></strong> and a dependent variable <strong><em>y</em></strong> which result in a non-linear function modeled data. Essentially any relationship that is not linear can be termed as non-linear, and is usually represented by the polynomial of <strong><em>k</em></strong> degrees (maximum power of <strong><em>x</em></strong>).</p><p><em>y</em><strong><em> </em></strong>= a <em>x</em>³ + b <em>x</em>² + c <em>x</em> + d</p><p>Non-linear functions can have elements like exponentials, logarithms, fractions, and others. For example: <em>y</em> = log(<em>x</em>)<br> <br>Or even, more complicated such as :<br><em>y</em> = log(a <em>x</em>³ + b <em>x</em>² + c <em>x</em> + d)</p><p><strong><em>But what happens if we have more than one independent variables</em>?</strong></p><p>For 2 predictors, the equation of the polynomial regression becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*02rMNXDX8C7Zls4wy2ew-g.png" /><figcaption>2-predictor polynomial equations</figcaption></figure><p>where, <br>- Y is the target,<br>- <em>x</em>1, <em>x</em>2 are the predictors or independent variables<br>- 𝜃0 is the bias,<br>- and, 𝜃1, 𝜃2, 𝜃3, 𝜃4, and 𝜃5 are the weights in the regression equation</p><p>For n predictors, the equation covers all feasible combinations of various order polynomials. This is known as Multi-dimensional Polynomial Regression and is notoriously difficult to implement. We will construct polynomial models of varying degrees and evaluate their performance. But first, let’s prepare the dataset for training.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0937cf3cb3ddacc3fe0db193a2cc3d2d/href">https://medium.com/media/0937cf3cb3ddacc3fe0db193a2cc3d2d/href</a></iframe><p>We can establish a pipeline and pass the degree and class of models that we wish to utilize to produce a polynomial of various degrees. This is what the code below does for us:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b649f22fcb056b8496cef5118537c7f/href">https://medium.com/media/7b649f22fcb056b8496cef5118537c7f/href</a></iframe><p>If you wish to view all of the coefficients and intercepts, use the following code block: Please keep in mind that the number of coefficients will vary depending on the degree of polynomial:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44093c4721a8aef7d8d8c5f9d28f9c80/href">https://medium.com/media/44093c4721a8aef7d8d8c5f9d28f9c80/href</a></iframe><p>And here is the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpOP6lkfG-wkc3MXRi72tg.png" /><figcaption>Coefficients/Intercepts for different degrees polynomial regression (Author Image)</figcaption></figure><p>This doesn’t give much information on the performance of each model, so will check r2 score.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/687cc068a82e67a092c377e659e3d2f8/href">https://medium.com/media/687cc068a82e67a092c377e659e3d2f8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*1HEj6SgFAMKiac1v0tBasQ.png" /><figcaption>r2-score for various degree of polynomial regression (Author Image)</figcaption></figure><p>So, we built polynomial equations up to degree 7 using sklearn pipeline method and found that degree 2 and above yielded 99.9% accuracy (as compared to ~ 94% by SLR). On the same dataset, we will now see another technique for building a regression model.</p><h3>2. Modeling Non-linear Relationships using Data Transformation</h3><p>The linear regression framework assumes that the relationship between the response and predictor variables is linear. To continue utilizing the linear regression framework, we have to modify the data so that the relationship between variables became linear.</p><p><strong>Some Guidelines for data transformations:</strong></p><ul><li>Both the response and the predictor variables can be transformed</li><li>If the residual plot reveals the presence of nonlinear relationships in the data, a straightforward strategy is to utilize nonlinear transformations of the predictors. In SLR, these transformations can be <em>log(x), sqrt(x), exp(x), reciprocal</em>, and so on.</li><li>It is critical that each regressor have a linear connection with the target variables. The transformation of dependent variables is one method for addressing the non-linearity issue.</li></ul><p><strong>In short, usually</strong>:</p><ul><li>- Transforming the y-values aids in dealing with error terms and may aid in non-linearity.</li><li>The non-linearity is mostly fixed by transforming the x-values.</li><li>For further information on data transformation, see <a href="https://online.stat.psu.edu/stat462/node/155/">https://online.stat.psu.edu/stat462/node/155/</a>.</li></ul><p>In our dataset, when we plotted the dependent variables <em>“Marks”</em> against “<em>time of study</em>” and “ <em>number of courses</em>”, we observed that Marks has non-linear relationship with time of study. Hence, we will do a transformation on the feature <strong><em>time of study</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-uSq_2cJZ0JgxkVTBE65Ew.png" /><figcaption>time of study showing non-linear behavior with Marks (Author Image)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f575c687e794e0ed75e3d4c577557a03/href">https://medium.com/media/f575c687e794e0ed75e3d4c577557a03/href</a></iframe><p>After applying the above transformation, we can plot <em>Marks</em> against new feature <em>time_study_sqaured </em>to see if the relationship has changed to linear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-Cp6iGcbhLLCnFJkckiUw.png" /><figcaption>The new feature exhibits a linear relationship (Author Image)</figcaption></figure><p>Our dataset is now ready for building a SLR model. On this converted dataset, we will now create a simple linear regression model with the sklearn LinearRegression() method. When we print the metrics after building the model, we get the following result:</p><p><em>R2-Square Value: 0.9996<br>RSS: 7.083<br>MSE: 0.071<br>EMSE: 0.266</em></p><p>A significant improvement over the previously built SLR model on the raw dataset (without any data transformation). We got a R2-Square Value of 99.9% as opposed to 94%. Now, we’ll validate the various assumptions of an SLR model to see if it’s a good fit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61t4MA6sBAspf0kPuehrJw.png" /><figcaption>All assumptions of a SLR model is Validated (Author Image)</figcaption></figure><p>So In this section, we transformed the data itself. Knowing that feature <em>time_study</em> is not linearly dependent with <em>Marks</em>, we created a new feature called<strong><em> time_study_squared</em></strong>, which was linearly dependent with <em>Marks</em>. Then we built a SLR model again and validated all the assumptions of a SLR model. We observed that all the assumptions are satisfied by this new model. Now, it’s time to explore our next and last techniques to build a different model on the same dataset.</p><h3>3. Modeling non-linear relationship using Non-Linear Regression Model</h3><p>For non-linear regression problem, we can try <em>SVR(), KNeighborsRegressor() or DecisionTreeRegression()</em> from sklearn library, and compare the model performance. Here, we will develop our non-linear model using the <strong>sklearn</strong> <strong>SVR()</strong> technique for demonstration purposes. SVR supports a variety of <a href="https://dataaspirant.com/svm-kernels/#t-1608054630727"><strong>Kernels</strong></a>. Kernels enable the linear SVM model to separate nonlinearly separable data points. We will test three alternative kernels with the SVR algorithm and observe how they affect model accuracy:</p><ul><li>rbf (default kernal for SVR)</li><li>linear</li><li>poly</li></ul><p><strong>i. SVR() using <em>rbf</em> kernal</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f1c5e1a9227b86840e412b6cbc316c2/href">https://medium.com/media/8f1c5e1a9227b86840e412b6cbc316c2/href</a></iframe><p>And here is the model metrics: Still a better R2-squared compare to our first SLR model.</p><p><em>R2-Square Value: 0.9982<br>RSS: 4053558.081<br>MSE: 0.363<br>EMSE: 0.602</em></p><p>A quick check on the error term distribution also seems to be OK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jHI4MWpXg5ifcjvZfW585g.png" /><figcaption>Error term distribution for SVR model with rbf kernel (Author Image)</figcaption></figure><p><strong>ii. SVR() using <em>linear</em> kernel</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfa2eda1c56a56cbe3fa91a09944070b/href">https://medium.com/media/cfa2eda1c56a56cbe3fa91a09944070b/href</a></iframe><p>And here is the model metrics when we used the linear kernel: The R2-squared values again <strong>dropped to ~93%</strong></p><p><em>R2-Square Value: 0.9350<br>RSS: 4063556.3<br>MSE: 13.201<br>EMSE: 3.633</em></p><p>And in this case also, error terms seem to be a near nor mal distribution curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_OnhLPtvW7sX97um2qdbCQ.png" /><figcaption>Error term distribution for SVR model with linear kernel (Author Image)</figcaption></figure><p><strong>iii. SVR() using <em>poly</em> kernel</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3830dd540a7a351383878ef100da303e/href">https://medium.com/media/3830dd540a7a351383878ef100da303e/href</a></iframe><p>And here are the model metrics with SVR poly kernel : The R2-squared value is 97%, which is higher than the linear kernel but lower than the rbf kernel.</p><p><em>R2-Square Value: 0.9798<br>RSS: 4000635.359<br>MSE: 4.087<br>EMSE: 2.022</em></p><p>And here is the error terms distributions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5uVmMYSOj599xhy1V-gGw.png" /><figcaption>Error term distribution for SVR model with poly kernel (Author Image)</figcaption></figure><p>So, In this section, we created a non-linear model using sklearn <a href="https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVR.html"><strong>SVR Model</strong></a> with 3 different kernels. We got the best R2-squared value whith rbf kernel.</p><ul><li>r2-score with rbf kernel = 99.82%</li><li>r2-score with linear kernel = 93.50 %</li><li>r2-score with poly kernel = 97.98 %</li></ul><h3>Conclusion:</h3><p>In this post, we started with a dataset that was not linearly dependent on the target variable. Before we could investigate alternative strategies for building a regression model on a non-linear dataset, we constructed a simple linear regression model with a r2-score of 94%. We then investigated three distinct methods for modelling a nonlinear dataset: Polynomial Regression, Data Transformations, and a nonlinear regression model (SVR). We discovered that polynomial degrees of 2 and higher resulted in a 99.9% r2-score, whereas SVR with a rbf kernel resulted in a 99.82% r2-score. In general, whenever we have a nonlinear dataset, we should experiment with several strategies and see which ones work best.</p><p><em>Find the data set and code here: </em><a href="https://github.com/kg-shambhu/Non-Linear-Regression-Model">https://github.com/kg-shambhu/Non-Linear-Regression-Model</a></p><p><em>You can contact me on LinkedIn: </em><a href="https://www.linkedin.com/in/shambhukgupta/">https://www.linkedin.com/in/shambhukgupta</a>/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88b25fc24ad5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/3-techniques-for-building-a-machine-learning-regression-model-from-a-multivariate-nonlinear-dataset-88b25fc24ad5">3 Techniques for Building a Machine Learning Regression Model from a Multivariate Nonlinear Dataset</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Descriptive Statistics: with the help of Gaussian, Left-Skewed, and Right-Skewed…]]></title>
            <link>https://medium.com/data-science/understanding-descriptive-statistics-with-the-help-of-gaussian-left-skewed-and-right-skewed-897b296382c6?source=rss-eb0e7e2ccaff------2</link>
            <guid isPermaLink="false">https://medium.com/p/897b296382c6</guid>
            <category><![CDATA[descriptive-statistics]]></category>
            <category><![CDATA[normal-distribution]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gaussian-distribution]]></category>
            <category><![CDATA[skewed-data]]></category>
            <dc:creator><![CDATA[Shambhu Gupta]]></dc:creator>
            <pubDate>Wed, 10 Aug 2022 12:55:30 GMT</pubDate>
            <atom:updated>2022-08-15T13:58:35.410Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Understanding Descriptive Statistics: with the help of Gaussian, Left-Skewed, and Right-Skewed Dataset</strong></h3><h4>Statistically re-engineer your data to make it skewed</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZNjBPODCqwcP9s7TsrpPPw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The normal distribution and its characteristics have been discussed extensively. We must also have a good understanding of its descriptive statistics. Have you, however, ever attempted to left- or right-skew a completely normally distributed dataset in order to test for its normality or observe the effects on its numerous descriptive statistics. If not, please continue since this is what we are going to do in this article.</p><h3><strong>Background:</strong></h3><p>Let me briefly present a Normal (or Gaussian) Distribution and Descriptive Statistics before we jump into Python Notebook and start editing the data.</p><p>The majority of values in a dataset with a normally distributed distribution cluster in the middle of the range, and the remaining values taper off symmetrically toward either extreme. Since most naturally occurring events are normally or roughly normally distributed, normal distribution is crucial. Examples of such variables include height, birth weight, shoe size, blood pressure, retirement age, marks scored, income distribution, and the price of commodities within an economy.</p><p><strong>Properties of normally distributed dataset:</strong></p><p>1. When plotted, the normally distributed dataset has a symmetric bell shape with the mean in the middle.</p><p>2. The mean, median, and mode are all equal.</p><p>3. It will only have one peak since it is unimodal.</p><p>4. Half of the values fall below and half above the mean, indicating that the distribution is symmetric about the mean.</p><p>5. It adheres to the <strong>Empirical Rule</strong>: The empirical rule, also referred to as the <em>three-sigma rule </em>or<em> 68–95–99.7 </em>rule, is a statistical rule which states that for a normal distribution,</p><ul><li>About 68% of values fall within one standard deviation of the mean.</li><li>About 95% of the values fall within two standard deviations from the mean.</li><li>Almost all of the values — about 99.7% — fall within three standard deviations from the mean.</li></ul><p>6. Coefficient of Skewness is Zero.</p><p><strong>Descriptive Statistics</strong>:</p><p>Descriptive statistics are summaries that quantitatively describe or list the characteristics of a specific dataset. We can get a good notion of the data distribution by looking at the descriptive statistics.</p><p><strong>Different types of descriptive statistics include:</strong></p><ul><li>Measure of Central Tendency — Mean, Median, and Mode</li><li>Measure of Dispersion — Range, IQR, Variance, and Standard Deviation</li><li>Positional Statistics — Minimum, Maximum, Deciles, and Percentile</li><li>Measure of Symmetry — Skewness and Kurtosis</li></ul><h3><strong>The Descriptive Statistics of a Perfectly Normal Distribution</strong></h3><p>Let’s start with a dataset that is normally distributed, then skew the distribution to the left and right to examine how the statistics change. I am going to begin with an excellent example of a normally distributed data from the field of biometry. This data is about “Housefly Wing Lengths” and has been taken from <a href="https://seattlecentral.edu/qelp/sets/057/057.html">Seattlecentral.edu </a>(<em>Sokal, R.R., and P.E.Hunter. 1955</em>).</p><p>There are total 100 records in the data and only it has only one column — “length”.</p><pre>df = pd.read_excel(&quot;s057.xls&quot;)<br>print(df.shape)<br>print(df.info())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*RMy1p_ZVtmyGmcHI1yYmjg.png" /><figcaption>Figure 1. Dataset Summary. Author Image.</figcaption></figure><p>To compute the different descriptive statistics, we can define the following functions in Python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59d5f30e16b13b1f7100b23bf80e2b33/href">https://medium.com/media/59d5f30e16b13b1f7100b23bf80e2b33/href</a></iframe><p>Let us now examine our dataset for various features of a normal distribution.</p><p><strong>Test 1: Normality Test</strong></p><p>We will use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.shapiro.html"><strong>SciPy Shapiro-Wilk test</strong> </a>to test the normality of the dataset. This tests the null hypothesis that the data was drawn from a normal distribution. i.e.</p><ul><li><em>H0: the data is normally distributed</em></li><li><em>H1: the data doesn’t follow a normal distribution</em></li></ul><p>In the SciPy implementation the p value can be interpreted as follows:</p><ul><li><em>p &lt;= alpha: reject H0, not normally distributed.</em></li><li><em>p &gt; alpha: fail to reject H0, i.e., normally distributed</em></li></ul><p>Results with a higher p-value often support the hypothesis that our sample was taken from a Gaussian distribution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13f0f60ed144804d044272b6b02a46cc/href">https://medium.com/media/13f0f60ed144804d044272b6b02a46cc/href</a></iframe><p>We can observe from the following output that our dataset is normally distributed.</p><blockquote>Test Statistics = 0.993, and p-value is 0.876<br>Data is Normally Distributed (fail to reject H0 as p-value is &gt; 0.05)</blockquote><p><strong>Test 2: Descriptive Statistics for a normal distribution:</strong></p><p>i. Mean = Median = Mode</p><p>ii. If the distribution is Uni-Modal</p><p>iii. If it has a bell-shaped symmetrical curve with mean at its center</p><p>iv. Skewness Coefficients = 0</p><p>To test the above four characteristics of a normal distribution, use the following code block. It will use the functions defined earlier for descriptive statistics.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b410eee372679fca36fb40cc700fa16c/href">https://medium.com/media/b410eee372679fca36fb40cc700fa16c/href</a></iframe><p>And here is the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*FNRcW-RNyJDqCDRa9d8fLw.png" /><figcaption>Figure 2. Descriptive Statistics with Histogram for a Normal Distribution. Author Image.</figcaption></figure><p>Looking at the above output, we can observe that:</p><ul><li>Mean, Median, and Mode are all equal (45.5)</li><li>The distribution is unimodal.</li><li>We have a symmetrical bell-shaped distribution with the mean at its center.</li><li>The skewness coefficient is zero.</li></ul><p><strong>Test 3: Check if it follows the Empirical Rule: 68–95–99.7 rule with 1–2–3 standard deviations</strong></p><p>A normally distributed dataset follows the <strong>Empirical Rule</strong> i.e. 68%, 95%, and 99.7% of the values lie within one, two, and three standard deviations of the mean, respectively. In order to test this property, we can use the following code block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/806fd6a6427f273cf8e54dba031d51ba/href">https://medium.com/media/806fd6a6427f273cf8e54dba031d51ba/href</a></iframe><p>and here is the output:</p><blockquote>Area covered from mean with +/- 1 sigma is: 68.27<br>Area covered from mean with +/- 2 sigma is: 95.45<br>Area covered from mean with +/- 3 sigma is: 99.73</blockquote><p><strong>Test 4: Outliers Check</strong></p><p>An outlier may or may not exist in a normal distribution. If there are no notable exceptions, everything is fine. We will first run this test on our normally distributed dataset. Then, we’ll run this test again on a left- or right-skewed dataset to determine whether data manipulation has resulted in any outliers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba6afa759e4b8e30371edcc5da675312/href">https://medium.com/media/ba6afa759e4b8e30371edcc5da675312/href</a></iframe><p>And we can see the output as follows: <em>Neither IQR nor 3-sigma techniques could find any outliers.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*iPVE_IYN25Oouc7qSk58Jw.png" /><figcaption>Figure 3: Result of Outlier Test. Author Image.</figcaption></figure><p>So far, we’ve examined and confirmed the parameters of a fully normal distribution. Now, we’ll skew the distribution to the left and right to see how it affects the normality test, descriptive statistics/visualization, and outlier presence.</p><h3>Change the data distribution to make it a left-skewed (or negatively- skewed) dataset</h3><p>We knew that a left-skew or a negatively skew dataset is one in which the tail of the distribution is longer on the left than on the right, and the median is closer to the third quartile than to the first. For such a distribution, we should also have Mode &gt; Median &gt; Mean.</p><p>We will clip or drop some of the values from the top percentile of our dataset to make it left skewed. This would ideally leave more data from the lower quantile, skewing the distribution somewhat negatively (or to the left).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/437f3e85d6e548bd2af43c9067817824/href">https://medium.com/media/437f3e85d6e548bd2af43c9067817824/href</a></iframe><p>And when you print the coefficients of skewness, you will notice that it’s non-zero negative value (-0.83 in this case).</p><blockquote>46.4<br>Resulting dataframe shape is: (50, 1)<br>New Skew value is: -0.83</blockquote><p>We’ve already created few functions in the beginning for testing or calculating the various parameters. We’ll call them one by one on the new dataset now (which is supposed to be a left-skew distribution) and see how they affect the different results.</p><p><strong>Test 1: Normality Test</strong></p><p>Running the same SciPy Shapiro-Wilk test on the new data frame <strong>df_left_skew</strong> yields this result.</p><blockquote>Test Statistics = 0.911, and p-value is 0.001<br>Data is NOT Normally Distributed (reject H0 as p-value is &lt; 0.05)</blockquote><p>So, we now have proof that our dataset no longer follows a normal distribution. Let’s look at its descriptive statistics and distribution plot to validate this.</p><p><strong>Test 2: Descriptive Statistics on Changed Data:</strong></p><p>Calling the previously defined function for descriptive statistics and plotting the histogram yields the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*73TZYFlFmJQLICf307OMNw.png" /><figcaption>Figure 4. Descriptive Statistics and Histogram for left-skewed (or negatively-skewed) dataset. Author Image.</figcaption></figure><p>So, with a left-skew dataset, we can see that:</p><ul><li>Mean, median, and mode are no longer overlapping.</li><li>In fact, we can notice that <strong>Mode&gt; Median&gt; Mean</strong> — justifying a left or negatively-skewed data.</li><li>a long-left tail, which causes the mean to be to the left of the peak and the median to be closer to the third quartile.</li></ul><p><strong>Test 3: Outliers Check</strong></p><p>In the negatively skew data, we will do one last check for outliers. A skewed dataset should ideally contain some outliers. Running the outliers test on this left skew dataset yields the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*lIliH4BafScdg8T8rQ01cw.png" /><figcaption>Figure 5: Outliers Presence in left-skewed dataset. Author Image.</figcaption></figure><p>We see that an outlier was spotted by the IQR approach but not by the 3-sigma method. Also, outlier in this case is below the minimum value of Q1 -1.5*IQR — indicating a negatively-skewed dataset. Please keep in mind that the <em>IQR approach only considers +/- 2.7*Sigma</em> for outlier discovery (hence less conservative), whereas the <em>3 Sigma (or Z-score) method examines +/- 3*Sigma </em>for outlier detection. Refer to this <a href="https://towardsdatascience.com/why-1-5-in-iqr-method-of-outlier-detection-5d07fdc82097"><strong>Blog</strong> </a>for more details on outliers detection.</p><h3>Change the data distribution to make it a right-skewed (or positively- skewed) dataset</h3><p>In the last section, We will clip or drop some of the values from the bottom percentile of our original dataset to make it a right-skewed distribution. This would ideally leave more data from the upper quantile, hence skewing the distribution somewhat positively (or to the right). We can use following code block to achieve this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99d81eead6dcfc08c59b2f41fb12c22f/href">https://medium.com/media/99d81eead6dcfc08c59b2f41fb12c22f/href</a></iframe><p>And this time, when you print the coefficients of skewness, you will notice that it’s non-zero positive value (0.83 in this case).</p><blockquote>44.6<br>Resulting dataframe shape is: (50, 1)<br>New Skew value is: 0.83</blockquote><p>Let’s quickly run the normality test, see the descriptive statistics, and also check for outliers.</p><p><strong>Test 1: Normality Test</strong></p><p>Running the same <em>SciPy Shapiro-Wilk test</em> on the new data frame <strong>df_right_skew</strong> yields this result.</p><blockquote>Test Statistics = 0.911, and p-value is 0.001<br>Data is NOT Normally Distributed (reject H0 as p-value is &lt; 0.05)</blockquote><p>So, we now have proof that our dataset no longer follows a normal distribution. Let’s look at its descriptive statistics and distribution plot to validate this.</p><p><strong>Test 2: Descriptive Statistics on right-skewed Data:</strong></p><p>We just need to pass the new data frame into previously defined function. The descriptive statistics and the histogram for the data frame <strong>df_right_skew </strong>looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*--pso_XEXFXegb5ENuGUeA.png" /><figcaption>Figure 6. Descriptive Statistics and Histogram for right-skewed (or positively-skewed) dataset. Author Image.</figcaption></figure><p>So, for a right-skewed dataset, we can see that:</p><ul><li>Mean, median, and mode are no more overlapping with each other.</li><li>In fact, we can notice that <strong>Mode &lt; Median &lt; Mean</strong>- justifying a right or positively skewed data.</li><li>a long right tail, hence the mean is also to the <strong>right</strong> of the peak.</li></ul><p><strong>Test 3: Outliers Check</strong></p><p>We can use the same code block and pass the new data frame <strong>df_right_skew </strong>to check if we have any outliers now. Running the outliers test on this right-skewed dataset yields the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*Cg4uQFLwyXJAwrIfu-87YA.png" /><figcaption>Figure 7: Outliers Presence in right-skewed dataset. Author Image.</figcaption></figure><p>We see that an outlier was spotted by the IQR method as it is less conservative than 3-sigma method as explained above. Please also note that outlier in this case is beyond the maximum value of Q3 +1.5*IQR — indicating a positively-skewed dataset.</p><h3>Conclusion:</h3><p>In this post, we began with a perfectly normally distributed dataset and tested its numerous properties in relation to a normal distribution. We then altered the data to create a left-skewed dataset and a right-skewed dataset. We also looked at how the descriptive statistics changed when the data was skewed to the left or right. This should have helped you understand how a skewed dataset’s statistics or histogram appears.</p><p><em>Find the data set and code here: </em><a href="https://github.com/kg-shambhu/Descriptive_Statistics">https://github.com/kg-shambhu/Descriptive_Statistics</a></p><p><em>You can contact me on LinkedIn: </em><a href="https://www.linkedin.com/in/shambhukgupta/">https://www.linkedin.com/in/shambhukgupta</a>/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=897b296382c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/understanding-descriptive-statistics-with-the-help-of-gaussian-left-skewed-and-right-skewed-897b296382c6">Understanding Descriptive Statistics: with the help of Gaussian, Left-Skewed, and Right-Skewed…</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploratory Data Analysis (EDA) — few practical considerations]]></title>
            <link>https://medium.com/@kg.shambhu/exploratory-data-analysis-eda-few-practical-considerations-824433ad1dfb?source=rss-eb0e7e2ccaff------2</link>
            <guid isPermaLink="false">https://medium.com/p/824433ad1dfb</guid>
            <category><![CDATA[eda]]></category>
            <category><![CDATA[openml]]></category>
            <category><![CDATA[practical-tips]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shambhu Gupta]]></dc:creator>
            <pubDate>Sat, 23 Jul 2022 07:17:38 GMT</pubDate>
            <atom:updated>2022-07-26T09:37:25.581Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Exploratory Data Analysis (EDA) — few practical considerations</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QFI-n-6v96aetel5dzzssw.jpeg" /><figcaption>Image Source: <a href="https://media.istockphoto.com/photos/concept-of-a-case-investigation-by-evidence-and-fingerprint-picture-id1333252780">Unsplash</a></figcaption></figure><p>This article explains some of the practical aspects when we do EDA on a given dataset. It also helps to understand the importance of doing an EDA before building a ML model. Some of the learnings from real time projects has been included in this article. I have also included a reference python notebook at the end that demonstrate some of the concept discussed here.</p><h3>1. Is it mandatory to do EDA before building ML model?</h3><p>An absolute necessity! Let me highlight some of the challenges while building a ML model. A good ML model depends on the correct choice of ML algorithm and the correct data. Remember the saying — “garbage in, garbage out”! So, it is very important that we feed the highest quality of data to our ML algorithm. Some of the major challenges in building a ML model are:</p><p>· <strong>Incomplete or insufficient training data</strong> — The data must be representative of all the business cases, and it should also be sufficient to reduce any possible bias.</p><p>· <strong>Data quality issue</strong> — The presence of too much noise, outliers, null values, missing values, non-standardized data adversely affects the ML model accuracy. The algorithm will not be able to generalize well on poor quality data.</p><p>· <strong>Availability of the right features/Derived Metrics</strong> — It is very important to feed only relevant data to the ML algorithm. Too many features or too less features create problems. There is a trade-off between the model accuracy and the model complexity, and we must balance them.</p><h3><strong>2. So, What is EDA?</strong></h3><p>It can be defined as the process to explore or investigate the given dataset and summarize the main characteristics w.r.to the business problems at hand. This is mostly done with the help of visualization. Imagine the below scenarios and try to answer yourself:</p><p>· Suppose you want to study the performance of a class student in one subject. What if the dataset is only for male students? Don’t you think that your study will be biased and will not be a true representation of the class as a whole?</p><p>· You sold 1000 quantity of a product, but revenue of that product is negative. Is that possible?</p><p>· Can the quantity sold be negative or can salary be negative?</p><p>· If a customer rating is allowed between 1–5 scale, what do you do when you see a rating of 7?</p><p>· How do you read the date 05/09/2022–5th September or 9th May?</p><p>By now, you must have started feeling the importance of EDA before building a ML model. EDA helps you to understand the data at hand and to address the data quality issue. In nutshell, EDA helps to identify (and minimize) the so called “<strong>garbage content</strong>” from the data. It helps us to answer two very important basic questions:</p><p>· <strong>Correctness</strong>: Is the data in the right shape or the right form to answer my business questions?</p><p>· <strong>Completeness</strong>: Does it capture all key events/ instances for our use case, or is it biased at source itself?</p><p>Lastly, EDA must be done keeping both domain and business problems in mind. A temperature of 50°C for an Indian city might look normal, whereas it might be an outlier for a European city. However, a temperature recording of 75°C for any city around the world should be flagged as erroneous.</p><h3><strong>3. Practical Consideration while Performing EDA</strong></h3><h4>3. 1 Data Understanding — Structural and Quality Investigation</h4><p><strong>Check Completeness of Data</strong></p><p>Often, incomplete data leads to an incomplete analysis and ultimately wrong or incorrect inferences. One must ensure that that data is complete w.r.to the business problem. For example, if you are trying to understand the customer behavior of a global company, it may not be enough if you have data only from a specific region, say APJ alone. Generally, the data will be stored in multiple tables or spread across multiple files or documents. You should carefully analyze all the relevant data sources and integrate the data as per your business needs.</p><p><strong>Inspect Your Data</strong></p><p>In this step, you import the data into python and try to inspect it at a high level. Python library <strong><em>pandas</em></strong> and <strong><em>numpy </em></strong>can be used here:</p><p>· Import your data [ <em>pd.read_csv()</em> ]</p><p>· Check data size/shape [ <em>df.shape </em>]</p><p>· Check columns and data type [ <em>df.info()</em> ] — Here, you should already have an idea to change the datatype of certain columns based on the content.</p><p>· Check the data distribution [ <em>df.describe()</em><strong> </strong>]: If you see the max values is greater than (mean + 3* Std. deviation) or the minimum value is than (mean -3* Std. deviation), you should be ready to remove the outliers later.</p><p>· Check some sample records [ <em>df.head().append(df.tail()</em>) ]: This will highlight the first and the last 5 records from the datasets. It will also hint if some header or footer is present in the dataset.</p><p><strong>Keep what makes sense — Delete irrelevant data</strong></p><p>· Headers/footers/page number/signatures etc. — should be deleted</p><p>· Any column that has the same values for each row (for example: Gender is all Male, or Region is APJ for all records) — should be deleted. It doesn’t add any information from EDA perspective.</p><p>· Any column that has all distinct values (ex: Customer ID, Session ID, Employee ID, Serial Number, Index etc..) — should be deleted.</p><p>· Any columns that have more than 90% null values — should be deleted.</p><p>· You can decide on the threshold cut-off based on your problem or domain specific knowledge. But any columns having more than 90% null doesn’t add much info w.r.to EDA.</p><p><em>df.isnull.sum()</em><strong> </strong>— will highlights number of null values per column</p><p><em>round(df.isnull().sum()/len(df.index), 3)*100)</em> — gives percentage of null values per column</p><p>· You should also check the number of values per rows and make a call if you want to delete some of the rows. There is no fixed rule that you should consider deleting the columns first or rows first. I usually delete the columns first as it also minimizes the null values in rows.</p><p>Library <a href="https://github.com/ResidentMario/missingno"><strong>missingno</strong></a> has a nice feature where you can see the distribution of null values either in a <em>matrix representation</em> or a <em>bar graph representation</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9rdQzVFs5m8nQXS7CPt-g.png" /><figcaption>Source: <a href="https://github.com/ResidentMario/missingno">https://github.com/ResidentMario/missingno</a></figcaption></figure><p><strong>Standardize the data</strong></p><p>The data within a column should have a standard representation i.e., it should be on a common scale. Some of the points you can think of:</p><p>· UoM — all data must be represented using the same UoM. Ex: KMPH vs MPH, KG vs LBS, CM vs MM etc.</p><p>· Currency — ensure that currency figures are the same. USD vs EUR etc.</p><p>· Date/Timestamp — should have a common representation using the same time zone.</p><p>· Data Scale/Decimal Notation — Ensure that you have the same representation for a thousand separators (at times comma (,) or dot(.) is used as separator)</p><p><strong>Missing Values Treatment:</strong></p><p>The best way to impute the missing value is that you populate the data from a reliable source. However, there may not be additional data, or it may be too time consuming. In such situation, we depend on the statistical method to impute the null or missing information. Some of the methods that can be used:</p><p>· Use mean or median for numerical column and Mode for categorical column</p><p>· Use the values from the preceding record</p><p>· Derive the values from an existing feature (such as area name from zip code, or day from date)</p><p>· Impute with a regression line</p><p>We can use classes like <a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html#sklearn.impute.SimpleImputer"><strong>SimpleImputer</strong></a> or <a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.IterativeImputer.html#sklearn.impute.IterativeImputer"><strong>IterativeImputer</strong></a> or <a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.KNNImputer.html#sklearn.impute.KNNImputer"><strong>KNNImputer</strong></a> from library <strong>sklearn</strong> to do the task.</p><p><strong>Caution</strong>: If the feature is numeric, do not blindly use mean or median to impute the values. There is a chance that the values might be encoded as numeric but represent a categorical variable. For example, if a categorical variable is already encoded as numeric values (say between 1 to 10). In such cases, we must use mode to impute the null values. In fact, the mean of this column might be a floating number and might not represent any valid data point. Using mean instead of mode as imputer in such cases will result in data inconsistency.</p><p>I will give one more <em>practical example</em>. In one of the use case, I had to fetch some of the customer metrics like number of tickets from other data sources, so that I could correlate customer ratings with different metrics. There were few customers for which there were no metrics. In such a case, we must replace the null values with 0 because a null value simply means absence of measure. By imputing the null values with mean or median would actually inflate the number and hence lead to wrong inferences.</p><p><strong>Remove Outliers</strong></p><p>· Outliers must be removed as they distort the general behaviour of the data, and they are non representative data points. That means they do not generalize the data and it can be considered as noise.</p><p>· The best way to identify the outliers is using the <strong>box plot</strong> in python with the help of the library <strong>matplotlib</strong>.</p><p>· To remove the outliers, you can either use <strong><em>IQR method</em></strong> (Q1–1.5*IQR to Q3+1.5*IQR) or <strong><em>Z-score method</em></strong> (-3*standard deviation to + 3*standard deviation). IQR method roughly deletes (-2.72*standard deviation to + 2.72 standard deviation) of the data.</p><p><strong>Code/De-code Your Data</strong></p><p>There may be a scenario where the data content might be coded as some values. For example, in road safety data, vehicle type is coded between 1–98. Or the day might be coded as between 0–6. There could be some argument that 0 represents a Sunday or Monday. The visualization of the data with these coded values might not look great as well. In such a situation, it is advisable to code/de-code the relevant values.</p><p>· Change the column name to a more meaningful name (or to rectify and spelling mistakes)</p><p>· Data content may be de-coded to represent meaningful values. (e.g. replace the values 0–6 by day of week)</p><p>· At times, you might want to encode the values so that you have a more concise visualization, especially when the values are a long text but take only a handful of values. For ex: different weather may have encoded like this:</p><p><em>1-Clear, Few clouds, Partly cloudy, Partly cloudy</em></p><p><em>2-Mist + Cloudy, Mist + Broken clouds, Mist + Few clouds, Mist</em></p><p><em>3-Light Snow, Light Rain + Thunderstorm + Scattered clouds, Light Rain + Scattered clouds</em></p><p><em>4-Heavy Rain + Ice Pallets + Thunderstorm + Mist, Snow + Fog</em></p><p>In this case, plotting the graph with these text values will take a lot of space and a good idea would be to code these values.</p><p><strong>Perform the Final Sanity Check</strong></p><p>In this step, domain knowledge and understanding of business problems is very important. The sanity check should be performed keeping the above two points in mind. I will try to give some examples here:</p><p>· As older transactions are not business critical, my task is to analyze data for the last 2 years only. Somehow, I see some historical data as well. In this case, I’ll delete any data beyond 2 years.</p><p>· I know that my customer rating can be in the range 1–5 only (5 being the highest), so I will delete any data where the rating is not in this range. This can also be flagged as a data quality issue to the relevant team.</p><p>· Any discounts cannot be more than 100%.</p><p>· There might be certain restrictions on how the internal/external customer data is represented. Please ensure that you have the right encoding there.</p><h3>3.2 Data Content Analysis</h3><p>In the first section, we did <strong>Structural investigation</strong> and <strong>Quality investigation </strong>into our dataset. Once the structure and quality of the dataset is understood and fixed, we move to the data content analysis phase where we will analyze the data content in detail. The most important point in this step is to identify the dependent variables. The content should be analyzed around the dependent variables and how it relates to other features in the dataset — numerical or categorical.</p><p><strong>Univariate Analysis</strong>:</p><p>· Numerical Feature: plots histograms [ df[col].plot(kind = ‘hist’) ]</p><p>· Categorical Feature: plot bar graphs [ df[col].plot(kind = ‘bar’) ]</p><p><strong>Multivariate Analysis</strong>:</p><p>· Numerical vs Numerical: sns.pairplot() or sns.heatmap()</p><p>· Categorical vs Categorical: sns.countplot(hue=…)</p><p>· Categorical vs Numerical: sns.boxplot() or sns.pairplot(hue=…)</p><p>Practically, it is not possible to analyze more than 15–20 features, so you must choose your features based on your domain knowledge. Another important point is to choose the right visualization to depict the result. For example, if a categorical variable has only two values, you might want to use a pie chart to show the percent distribution as compared to the bar chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*SG5GBtzLfOMqJ2oM04GhkA.png" /><figcaption>Choosing the right visualization (Author Image)</figcaption></figure><p>Similarly, if there is a time dimension, it would make sense to plot a radial plot rather than a simple bar chart for 24 hrs. data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*ebTLDygw8_PtKof7P-0jWQ.png" /><figcaption>Choosing the right visualization (Author Image)</figcaption></figure><p>A correlation matrix or a heatmap looks messy at times when we have more variables. You may want to focus only on most relevant variables in such cases. So, a good idea here would be to highlight some of the values based on correlation coefficients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*NVttlbQQjQZFH-QlE9AYsQ.png" /><figcaption>Highlighting the Correlation Coeff. (Author Image)</figcaption></figure><h3>3.3 Derived Features/Metrics</h3><p>Perhaps one of the most important and powerful tools for EDA and ML model building. With the right feature engineering, an average performing model can be turned into a more predictive model. However, business knowledge and domain expertise are very important for the right feature engineering. For example, features like weight and height may not have any visible relationship with an ailment, but a BMI is more likely to correlate with the said ailment. Similarly, individual customers may not depict any trends, but a proper customer segmentation might have some interesting trends. In general, you can do some of the following feature engineering on your dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0uMRnzeqpgoqbfnFIATFDw.png" /><figcaption>Feature Engineering (Author Image)</figcaption></figure><p>· Continuous Variables: Try to bin some of the numeric columns into a few categories (ex: age, salary, amount, interest rate, discounts, etc…)</p><p>· Time Variables: Calculate various time dimensions (for example day, week, month, year etc.) from a date column.</p><p>· New Features: create new features like BMI from height/weight</p><p>I have come across a dataset that lists multiple solutions a customer has in his landscape. My model accuracy increased by almost 10% when I created a feature called “#Solution” and populated the values like “less than or equal to two”, and “more than two”. I could do this as I know more solutions add to overall complexity and we should also not consider individual solution names rather we should consider the overall number of solutions.</p><h3>4. Reference Notebook for Hands-on</h3><p>In this article, I have highlighted some of the practical challenges that we face in general while we do EDA. These are not specific to a particular dataset. In fact, all of these might not be applicable for a given dataset or a given scenario. I tried to demo as much as I can on the <a href="https://www.openml.org/search?type=data&amp;sort=runs&amp;id=42803&amp;status=active">Road Safety Data</a> from <a href="https://www.openml.org/">Open ML</a>. You can refer to the notebook here: <a href="https://github.com/kg-shambhu/RoadSafetyData/blob/main/Exploratory%20Data%20Analysis%20(EDA)%20on%20Road%20Safety%20Data%20-%20Practical%20Considerations.ipynb">EDA on Road Safety Data</a></p><h3>4. Conclusion</h3><p>In this article, we looked at some of the practical aspects that should be considered while performing an EDA. We started by investigating the dataset from a data structure and data quality perspective. We discussed some of the steps to address some of the data quality issues. Then we started analyzing the data content, its distribution, and correlation among various numerical features. However, these are certainly not all the possible content investigation and data cleaning steps one could do.</p><p>It must be noted that a proper and detailed EDA is a time-consuming process. We often say that 80% of any data science project is data preparation and EDA. However, EDA must be performed keeping the business problem in mind and exploiting the domain expertise. Please remember that a clean and relevant dataset is more likely to yield a good model. I appreciate your time and look forward to hearing your feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=824433ad1dfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>