<?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 Gaurav Sharma on Medium]]></title>
        <description><![CDATA[Stories by Gaurav Sharma on Medium]]></description>
        <link>https://medium.com/@greatsharma?source=rss-40c34d041b23------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PCf9MM7_4vpltUkaE-LsEA.jpeg</url>
            <title>Stories by Gaurav Sharma on Medium</title>
            <link>https://medium.com/@greatsharma?source=rss-40c34d041b23------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 02:27:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@greatsharma/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[Compressing images using Linear Algebra]]></title>
            <link>https://medium.com/analytics-vidhya/compressing-images-using-linear-algebra-bdac64c5e7ef?source=rss-40c34d041b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdac64c5e7ef</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[image-compression]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[svd]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <dc:creator><![CDATA[Gaurav Sharma]]></dc:creator>
            <pubDate>Wed, 23 Sep 2020 08:08:49 GMT</pubDate>
            <atom:updated>2024-02-27T08:34:54.983Z</atom:updated>
            <content:encoded><![CDATA[<p>We all have studied some degree of <a href="https://analyticsvidhya.com/blog/2017/05/comprehensive-guide-to-linear-algebra/?utm_source=Backlink&amp;utm_medium=SEO"><strong>linear algebra</strong></a> in our high school and some of us even studied it rigorously in our graduation. But linear algebra is more power-full then we all thought. It comprises of algorithms/methods which helps a lot in the real world specially in the study and manipulation of images. Images are one of the highly used medium of communication in today’s digital and social world.</p><p>We all share thousands of images, memes etc. to our known ones. But when it comes to sharing large image files we need to compress it such that the size of image got reduced significantly keeping the image quality and content as good as possible. Images are represented as 3 <a href="https://www.analyticsvidhya.com/blog/2018/08/dimensionality-reduction-techniques-python/?utm_source=Backlink&amp;utm_medium=SEO"><strong>dimensional</strong></a>(2 for height and width and 1 for channel) array/matrix of pixels, and we all know whenever matrix is coined linear algebra appears automatically.</p><p>This story is divided into following parts -</p><ul><li>Linear algebra refresher</li><li>visualize what a matrix do to a vector</li><li>visualize what a matrix do to a shape</li><li>matrix factorization and SVD</li><li>Compressing small dummy image using SVD</li><li>Compressing big real image using SVD</li></ul><blockquote><strong>Note:</strong> This story contains lot’s of images (20+), so if you are reading this story in slow internet or even in mobile devices then you may face rendering issues and may miss some of the images. Also in the mobile device sometimes the images are automatically stretched by medium. So, it’s recommended to read on laptop/desktop.</blockquote><h3>Linear Algebra refresher</h3><p>The two core element of linear algebra are <strong>vector</strong> and <strong>matrix</strong>. Vector represents a point in euclidean space whereas matrix is a linear mapping which maps vectors from one space to other (both the spaces could be of same or different dimensions). Here I coined the term <strong>linear mapping</strong>, it means <em>the mapping from one vector space to another respects the underlying (linear) structure of each vector space i.e., it preserves the linearity, </em>(vector space is just an abstract representation). Mathematically, we write as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*Vd4YnSXbxZJnUFcrxoytwQ.png" /></figure><p>Here, L is the linear map also known as linear transformation.</p><p>This is all mathematical jargon, but what it really do geometrically? So,<em> if there is a vector in euclidean space then it will either scale it, or rotate it, or do both sequentially. </em>Let’s visualize what a matrix(linear mapping) do to a vector in euclidean space(R2 in this case).</p><h4>Visualize what a matrix do to a vector</h4><p>We will first create a random vector and random linear map.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a698a452d5cd2cd132f78cd88a12ef01/href">https://medium.com/media/a698a452d5cd2cd132f78cd88a12ef01/href</a></iframe><p>Now, we will transform random vector u using linear map M, this will give us transformed vector u which we call as v.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e750ce4b38f5e99331fccd9ea9d433f/href">https://medium.com/media/7e750ce4b38f5e99331fccd9ea9d433f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*tgs0ZUfZ8FPgQLOCnBdlSw.png" /></figure><p>So, we see that the linear map M do both scaling and rotation when applied to u.</p><blockquote>If M would have done only scaling to u then u would be called as <strong>eigen vector</strong> of linear map M and the amount by which M scales u is called <strong>eigen value</strong> corresponding to that eigen vector. Also, if M would have done only rotation to u then M is called as <strong>rotation matrix</strong> or <strong>rotational mapping</strong>.</blockquote><p><strong>So, a linear map/matrix either scales or rotates or does both to a vector in euclidean space.</strong></p><h4>Visualize what a matrix do to a shape</h4><p>We now visualize what a matrix/linear map do to a shape in euclidean space(R2 in this case).</p><p>We will take a unit circle centered at (2,2) and then apply linear map M to it and visualize how it got transformed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5d4f79cf8995e656c6b702ef459a51a/href">https://medium.com/media/f5d4f79cf8995e656c6b702ef459a51a/href</a></iframe><p><strong>circum_vectors</strong> are the vector points at the circumference of this unit circle. Now, we will transform these circum_vectors using M.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b6a0ada4b259d51fd47fc9e5903b725/href">https://medium.com/media/0b6a0ada4b259d51fd47fc9e5903b725/href</a></iframe><p>Now, let’s visualize how this mapping change the shape of circle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4d3c45a5d143d934f2c0452a961c093/href">https://medium.com/media/c4d3c45a5d143d934f2c0452a961c093/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*Y1G3NTU984zSybGClDNyjA.png" /></figure><p>So, we can see that this circle is transformed into an ellipse. This is because each vector point is scaled and rotated which result in this transformed ellipse. <em>Every point on the circle has an one-to-one mapping with points on the ellipse as the mapping is linear.</em></p><h4>Matrix factorization and SVD</h4><p>Matrix factorization is the most power-full tool in linear algebra, it is used extensively not just in mathematics but also in the field of data science and machine learning. Recommender systems uses matrix factorization heavily. <em>The idea is to factorize an unknown matrix into pieces whose properties are known to us or who are easy to manipulate.</em> There are many matrix factorization available but the most popular and fundamental is Singular value decomposition (SVD). <em>Any matrix no matter of what shape can be decomposed into three matrices using SVD.</em></p><p>We can decompose any linear transformation M into 3 transformations. These are -</p><ul><li>first rotating using V_T (right singular vectors)</li><li>then scaling using S (singular values)</li><li>then again rotating using U (left singular vectors)</li></ul><p>Here V_T, S, U are decomposed matrices of M. <em>So, any linear map can be decomposed into these three fundamental transformations, and this decomposition is called </em><strong><em>Singular value decomposition (SVD)</em></strong><em>.</em></p><figure><img alt="svd3.jpg" src="https://cdn-images-1.medium.com/proxy/1*uP9r0rkPbPcHnijvVyyAgg.jpeg" /></figure><figure><img alt="svd2.png" src="https://cdn-images-1.medium.com/proxy/1*XNWUlrQJXGeoCDqUMd0iUA.png" /></figure><p>Let’s apply SVD to the linear map M we used earlier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30f361eebcc356dcb46c1ae0d6603da1/href">https://medium.com/media/30f361eebcc356dcb46c1ae0d6603da1/href</a></iframe><h4>Transforming using SVD</h4><p>Now, we will transform above unit circle centered at (2,2) using these decomposed transformations in sequential manner and will see that indeed the end result is same as before.</p><p><strong><em>Whether apply M directly or first apply V_T then S and then U, will always gives the same result</em>.</strong> See below image,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*GwwPCzaerPM1aeFYam44QA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bf395fe100f9f8730fccd49248fd690/href">https://medium.com/media/2bf395fe100f9f8730fccd49248fd690/href</a></iframe><p>Now, let’s plot these transformations individually.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/927bc71a6c110f4a1eff83e4048e5edb/href">https://medium.com/media/927bc71a6c110f4a1eff83e4048e5edb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*MmFDPpFPcAJGWtsb0eqbqg.png" /></figure><blockquote>So, V_T rotated the original circle, then S scaled this rotated circle and finally U again rotate this scaled circle. All are done sequentially.</blockquote><p>So, we can see that indeed the end result is exactly the same. Note, these images are on different scale(see x ticks), this is done because if we plot all of them on same scale then circle will look very tiny.</p><h3>Image compression using SVD</h3><p>Now we will use this extremely powerful tool to compress images. We will see that how <em>the outer product of u and v corresponding to few topmost singular values can approximate the original image really well while reducing the image size significantly.</em></p><h4>Compressing dummy image</h4><p>In this section we will take a very small 7x7 dummy image. We first apply SVD to it, then see all the rank 1 images corresponding to all singular values. Then we will <strong>construct best rank i image by cumulating</strong> <strong>all rank 1 images corresponding to singular values from 1 to i</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*Jmghlt9i9ox_TkF-FjFAxA.png" /></figure><p>Below is the code for random 7x7 black-white image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/042d235090ffce4596d68b6f4f982f27/href">https://medium.com/media/042d235090ffce4596d68b6f4f982f27/href</a></iframe><p>Note, if you want to construct this same image then do pass the same seed 42. Also, this image is of rank 6.</p><p><em>Rank of a matrix is defined as the number of independent rows/columns in that matrix. It is always less then the minimum of number of rows and columns in that matrix.</em></p><p>Let’s visualize it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ffd7ae83107967080be2e2dd1edb168/href">https://medium.com/media/9ffd7ae83107967080be2e2dd1edb168/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*wgG6cGL8PAYnTy4kNWb9Zw.png" /></figure><p>Now, we will decompose this image using SVD.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c35ee50fbd8c1412eed6a5a9eea4df93/href">https://medium.com/media/c35ee50fbd8c1412eed6a5a9eea4df93/href</a></iframe><p>Below are all<strong> rank 1 images</strong>. These are constructed by taking the outer product of columns of U and rows of V_T and then multiplying/scaling by corresponding sigma value in S.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0280652b54ad350c336602555c666fb5/href">https://medium.com/media/0280652b54ad350c336602555c666fb5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TB-FMCzX1d2yMJwJQ-oeFQ.png" /></figure><p>We will use these rank 1 images to construct the image close to original image. We do this by cumulative sum of rank 1 images. Also by doing this we increase the rank of the matrix and hence information stored i.e., the constructed image will resemble more close to the original image as we cumulate more and more rank 1 images.</p><blockquote><strong>Note:</strong> At any step that approximated image is the best possible approximation of that rank for the image.</blockquote><h4>Best rank 1 approximation</h4><figure><img alt="CodeCogsEqn%282%29.gif" src="https://cdn-images-1.medium.com/proxy/1*XTXiudBP67H75GTtcpTyqw.gif" /></figure><p>The best rank 1 image is nothing but just the outer product of u1 with v1 and scaled by s1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/738e428d87ae86fc6b232824b16c7bc8/href">https://medium.com/media/738e428d87ae86fc6b232824b16c7bc8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*P5eoyxw7hvHlYiAvKX7o6g.png" /></figure><h4>Best rank 2 approximation</h4><figure><img alt="CodeCogsEqn%283%29.gif" src="https://cdn-images-1.medium.com/proxy/1*fDzk4PMK-8k9DYrhYhlHkg.gif" /></figure><p>The best rank 2 image is the sum of above best rank 1 image and outer product of u2 with v2 and scaled by s2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa667425e8ac2bf3d0dfcc18f1c5e5d6/href">https://medium.com/media/aa667425e8ac2bf3d0dfcc18f1c5e5d6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*mGTIfnPXu_vIukXw1PKTOg.png" /></figure><h4>Best higher rank approximation</h4><p>Similarly, <strong>the best rank i image is the sum of best rank (i-1) image and outer product of ui with vi scaled by si.</strong></p><blockquote>We will <strong>construct best rank i image by cumulating all rank 1 images corresponding to singular values from 1 to i</strong>.</blockquote><figure><img alt="CodeCogsEqn%284%29.gif" src="https://cdn-images-1.medium.com/proxy/1*QLZW_JpxlsDfw6Meae6UfQ.gif" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71ffd0f1eb7683d44bed894af0fa285d/href">https://medium.com/media/71ffd0f1eb7683d44bed894af0fa285d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2oU1LE6RLaJ99PH786mOQ.png" /></figure><p>We can see as we add more and more rank 1 images the approximated image get more and more close to original image and finally we get the original image.</p><blockquote>If the rank of image is <strong>r</strong> then adding all r rank 1 images gives us the same original image.</blockquote><p>But we won’t go till rank r after all it will give us no benefit and even require more space. So we stop earlier, in this case most of us will stop at <strong>best rank 4 or 5 approximation</strong>, because it gives an image close enough to the original image so that we get an good idea of what the image is. Also in this case all of us will stop at <strong>best rank 6 approximation</strong>, because rank_7 is same as rank_6. This is because, as the image is rank 6, the last singular value is 0, so it will not add anything to the image.</p><p>Let’s see how much space we saved by using best rank 3 image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a81b50016f8ff7f05e310f4cc8f3133/href">https://medium.com/media/4a81b50016f8ff7f05e310f4cc8f3133/href</a></iframe><p>So, even in the case of extremely tiny 7x7 image we saved around 8% space with a rank 3 approximation. Although this saving is not a lot as we are also compromising with the image quality, but in case of real life bigger images we save a lot space keeping the image quality almost same.</p><h4>Compressing real image</h4><p>For simplicity I am taking only gray-scale image. But the method can be easily mapped to colored images as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83a6c0b4da2c8e7b72657b0eb495fce6/href">https://medium.com/media/83a6c0b4da2c8e7b72657b0eb495fce6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*ahHd8dP4u55cZXND9NzFHA.png" /></figure><p>This image is very large in resolution so I am resizing it to smaller size.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94576d514d22a3d808034ee925ebd032/href">https://medium.com/media/94576d514d22a3d808034ee925ebd032/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*WwRlDz0WmhVI2GssQPnFqg.png" /></figure><p>Rank of the image is 300 (which is a lot). Let’s decompose it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b4c8ad79dd3a3e8b557c753bef67046/href">https://medium.com/media/1b4c8ad79dd3a3e8b557c753bef67046/href</a></iframe><p>Below are some rank 1 images corresponding to the top singular values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5001e5aa6525445f8ee1702febed5fe/href">https://medium.com/media/e5001e5aa6525445f8ee1702febed5fe/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZFsshc5766eUkMdtHxYzA.png" /></figure><p>Clearly we are not able to guess anything from these rank 1 images but magic will happen when we start cumulating them.</p><p>We would require some helper functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3efef022ec3d1f69dcc478555a685878/href">https://medium.com/media/3efef022ec3d1f69dcc478555a685878/href</a></iframe><p>As the SVD from numpy linalg package gives S not as a matrix but as array of values, so I defined a function which gives S as a diagonal matrix.</p><p><strong>perc_storage: </strong>Returns the percentage of storage taken by the compressed image.</p><p><strong>perc_energy: </strong>Returns the percentage of energy(sum of sigmas) taken by the compressed image.</p><p>As we need to decide the rank of image upto which we want to compress, but this can’t be done manually as this vary image to image. So, we will use the below functions for that, which returns optimal rank for given energy and storage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66ffbf325d88f573fe9f31c8473266b0/href">https://medium.com/media/66ffbf325d88f573fe9f31c8473266b0/href</a></iframe><p><strong>get_optimal_rank_by_energy:</strong> Gives the lowest rank for the given amount of energy.</p><p><strong>get_optimal_rank_by_storage:</strong> Gives the lowest rank for the given amount of storage.</p><p>Let’s decompose the image using SVD.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d18a0f995621a8c3f0a8c51d052164c6/href">https://medium.com/media/d18a0f995621a8c3f0a8c51d052164c6/href</a></iframe><p>We will find the optimal rank using above defined functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7920957ec377e951ce7d6cf92d93e69/href">https://medium.com/media/c7920957ec377e951ce7d6cf92d93e69/href</a></iframe><p>So we get the optimal rank for 85% energy and 30% storage.</p><p>Now let’s visualize compressed images of different ranks and compare them with original image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa856869fa3cadf9ce3d9f2352e46698/href">https://medium.com/media/aa856869fa3cadf9ce3d9f2352e46698/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bhS5lOSU-JsHGvD3KFQ5YQ.png" /></figure><blockquote>We can see that rank 50 is a very good approximation, as it contains 75% information content keeping the storage requirement below 30%. So, we get 75% information by reducing 71% space, which is a lot saving keeping the image content very enriched.</blockquote><p>Many of us will stop at rank 50 approximation, some of us may go till rank 75 approximation and those who wants more clear image may go till rank 100. There is always a trade-off between <strong>information retained</strong> and <strong>space required</strong>. It depends on your needs, <em>if you want more quality image then you may go to higher rank approximations providing more image space but if space is limited to you then you will stop at initial ranks retaining maximum information in given space limits.</em></p><p><strong>Below is the plot showing the trade-off of rank with different attributes.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39834a686e9367bdef9cbbd724c645c3/href">https://medium.com/media/39834a686e9367bdef9cbbd724c645c3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*NmqR-B-LDzW8GA4njzwk4w.png" /></figure><blockquote>You will get the <strong>entire documented jupyter notebook</strong> for this story from <a href="https://www.kaggle.com/gauravsharma99/compressing-images-using-linear-algebra?scriptVersionId=43268686"><strong>here</strong></a>, you just need to fork it. Also if you like the notebook then <strong>up-vote</strong>, it motivates me for creating further quality content.</blockquote><p><strong>If you like this story then do clap and also share with others.</strong></p><p>Also, have a read of my other stories which includes variety of topics including,</p><ul><li><a href="https://medium.com/@greatsharma04/statistical-analysis-using-python-e83f10ca3c82"><strong>statistical analysis in python</strong></a></li><li><a href="https://medium.com/analytics-vidhya/effect-of-multicollinearity-on-linear-regression-1cf7cfc5e8eb"><strong>multi-collinearity in linear-regression</strong></a></li><li><a href="https://medium.com/analytics-vidhya/facial-emotion-recognition-fer-using-keras-763df7946a64"><strong>facial emotion recognition using keras</strong></a></li></ul><p>and<a href="https://medium.com/@greatsharma04"> many more</a>.</p><p>Thank-you once again for reading my stories my friends :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdac64c5e7ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/compressing-images-using-linear-algebra-bdac64c5e7ef">Compressing images using Linear Algebra</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Facial Emotion Recognition using Convolutional Bidirectional LSTM]]></title>
            <link>https://medium.com/analytics-vidhya/facial-emotion-recognition-using-convolutional-bidirectional-lstm-49d4199024f?source=rss-40c34d041b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/49d4199024f</guid>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[facial-recognition]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Gaurav Sharma]]></dc:creator>
            <pubDate>Sat, 19 Sep 2020 11:37:19 GMT</pubDate>
            <atom:updated>2020-09-23T15:18:11.369Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second part in the <a href="https://medium.com/analytics-vidhya/facial-emotion-recognition-fer-using-keras-763df7946a64">Facial Emotion Recognition</a> series, it is recommended to read the first part before jumping here.</p><p>This story will walk you through how you can create a FER model using <strong>time-distributed Convolutional </strong>followed by<strong> Bidirectional LSTM</strong> in Tensorflow-Keras. I already discussed the introduction and application to this topic in the first part.</p><p>This story is divided into following sections,</p><ul><li>Why we need this approach</li><li>Inspecting and manipulating the data</li><li>Creating our own custom FER model from scratch</li></ul><h3>Why we need this approach?</h3><p>So, if you have gone through the first part, then you may ask what’s the need for this new approach? The answer is very simple and intuitive, as I told you in the end of part 1 that to apply the simple CNN based model to video I have to feed the video <strong>frame-by-frame</strong> i.e., <em>feed one frame at a time and predict the emotion on that frame</em>, and keep doing this for every frame(possibly skipping 4–5 frames in between because that will increase the fps but keeps the performance almost same).</p><p>So, <em>is there any way in which we can feed a small 2–3 seconds (60–90 frames for a 30fps video)?</em> and yes we can, by <em>time-distributing the CNNs</em>. But, we can do even more, because just like <em>words of a sentence share context with each other, frames of a video also shares context with adjacent frames</em>. So, our model can also learn from these contexts and for that we can use<em> bidirectional LSTMs</em>.</p><blockquote><strong>Note:</strong> To get the full out of this story, you should have some basic understanding of python and some basics of neural networks specifically CNN and LSTM.</blockquote><h3>Inspecting and Manipulating the data</h3><p>As we all know <em>adding intelligence to machine is more about letting them learn from data via some algorithm,</em> and of-course for that we need <strong>DATA</strong>. Data is the most important part of any machine learning/ deep learning project, because after all our trained model is a product of the data on which it is trained. I mean the better our data represent the real world the more our model behave like real and perform well in real world. Remember one thing <strong>“GARBAGE IN, GARBAGE OUT”</strong>, if we train on data containing lots of garbage then in production our model also throw garbage. So, DATA is the most important building block for any ML/DL task.</p><p>So, we need data for this FER task as well. We will train our model on that and then test it’s performance on data kept aside and also in real-time video stream. Note that this is a <strong>supervised learning</strong> problem i.e., the learned model y is a function of data x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/0*CiIFX-Bqbjd9j9vL.png" /></figure><p>For this task I am going to use a very popular data available at <a href="https://www.kaggle.com/">kaggle</a> called the <a href="https://www.kaggle.com/gauravsharma99/ck48-5-emotions"><strong>CK+48</strong></a><strong> </strong>data-set, <strong>each image is grey-scaled and of resolution 48x48.</strong> You can also use other datasets as well, there are few more data-sets which are publicly available, or you can create your own.</p><blockquote>We will get more insights in this data as we proceed, so stay tuned…</blockquote><p>Now we will wet our hands in some real python codes. Firstly import all needed libraries,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76b033b60f951184cd3625ad57405462/href">https://medium.com/media/76b033b60f951184cd3625ad57405462/href</a></iframe><p>Let’s inspect the data, we will check the number of emotion categories we have and the number of images in each of those categories.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faa781687f5493c19f0916e8ca0536cc/href">https://medium.com/media/faa781687f5493c19f0916e8ca0536cc/href</a></iframe><p>sadness and fear has very low number of images as compared to other classes.</p><pre>TOP_EMOTIONS = [&quot;happy&quot;, &quot;surprise&quot;, &quot;anger&quot;, &quot;sadness&quot;, &quot;fear&quot;]</pre><p>Unlike the data-set used in first part, this <em>CK+48 data-set contains directories of images and the directories are named after the emotion they contain. Within each directory we have bunch of images for that particular emotion class</em>.</p><p>One thing which is interesting about this data is that <em>the original data contains video clips</em>. But the data-set we are using contains the <strong>last 3 frames </strong>of each such video clip. Because in the upcoming model we won’t be feeding images(like in part 1) but rather tiny video clips i.e., collection of frames. So, <em>we need to bundle these 3 frames associated with each video clip into a single short 3 frame video clip</em> (although this clip is very short, in milliseconds, because a single second contains 30 frames in a 30fps video). Then we will feed these 3 frame videos into our model.</p><p>Below are the code snippets which will make the data compatible with our upcoming model. I will explain each of them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/380270a89da7b2e56e21c46594be9697/href">https://medium.com/media/380270a89da7b2e56e21c46594be9697/href</a></iframe><p>Here we created a default-dict called <strong>data</strong> whose keys are the emotion names and values are dict itself. The keys of this nested dict is the <em>video id</em> from which we have extracted last three frames, and the values of this nested dict is a list which contains the name of those last three frames. Have a look at the below image, it will be more clear to you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-rWILEseIiVaNb_jOUesOQ.png" /></figure><p>We will also need some helper functions to get the work done.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/465713015fb0ebf0cf2f1b32a6bb1bc7/href">https://medium.com/media/465713015fb0ebf0cf2f1b32a6bb1bc7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ea70ac333ed043fbae1387ecc33b9d7/href">https://medium.com/media/8ea70ac333ed043fbae1387ecc33b9d7/href</a></iframe><p>Here we are first iterating over the keys of dict data , then within each emotion class we are stacking those 3 frames associated with each video clip. This will give us something like below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*Ib1aGKcCYlDfLp2s2GcPcA.png" /></figure><p>Now we are almost done, all we need some stacking and reshaping which is done below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b0b14e107e4af8d18078bff6ce3f43e/href">https://medium.com/media/8b0b14e107e4af8d18078bff6ce3f43e/href</a></iframe><p>Now, we split the data into training and validation set. We will train on training data and validate our model on validation data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee8685d28dd6d3a7110374cc9e306948/href">https://medium.com/media/ee8685d28dd6d3a7110374cc9e306948/href</a></iframe><p>label_emotion_mapper , is the mapping from original class label to emotion name.</p><p>Let’s visualize the images of each emotion category.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77577db755d1d266ee75d2258f5d18d0/href">https://medium.com/media/77577db755d1d266ee75d2258f5d18d0/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*CNpMnS9tqBDG56HfJDcifQ.png" /></figure><h3>Creating our own custom FER Model</h3><p>We first need to normalize the image arrays, this is done because neural networks are highly sensitive to non-normalized data. We will use <strong>min-max normalization.</strong></p><p>For these gray-scaled images min=0, max=255 therefore we will divide the array by <strong>255 </strong>because,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*gDY0d2CRitVOU9o1.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fad31aa4bf0d216d2cd87f8574e42d54/href">https://medium.com/media/fad31aa4bf0d216d2cd87f8574e42d54/href</a></iframe><p>Below is a <em>Convolutional Neural Network (CNN), I used following settings :</em></p><ul><li>For generalization purpose <strong><em>dropouts</em></strong> are used at regular intervals.</li><li><strong><em>ELU</em></strong> is used as the activation function because firstly it avoids <em>dying relu problem</em> but it also performed well as compared to LeakyRelu, at-least in this case.</li><li><strong>he_normal</strong> is used as kernel initializer as it suits ELU.</li><li><strong>Batch Normalization</strong> is also used for better results.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20d021b15557e73cba203196d27ce050/href">https://medium.com/media/20d021b15557e73cba203196d27ce050/href</a></iframe><p>Now, we will time-distribute the above CNN model, then stack few Bidirectional LSTMs and then stack few dense layers at the end. Below is the function for that,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a7e75ebbfeae400709313f0f7d159bf/href">https://medium.com/media/2a7e75ebbfeae400709313f0f7d159bf/href</a></iframe><p>Unlike the first part, here I used just one callback called <strong>ReduceLROnPlateau</strong> for reducing learning rate whenever the validation accuracy plateaus. Batch size of 32 is used and trained for 100 epochs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/376e5686c497b486b1b33ecc90a4820d/href">https://medium.com/media/376e5686c497b486b1b33ecc90a4820d/href</a></iframe><p>Now you will see the difference in the input shape, unlike 4 dimensional array(in part 1) we now have 5 dimensional array(5th dimension is for batches of image). We then compile the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a763309a6842fa3cff851fce81aab11/href">https://medium.com/media/4a763309a6842fa3cff851fce81aab11/href</a></iframe><p>Let’s now train the model and log the training performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35937a8d272f1ce69979901331fb9b2a/href">https://medium.com/media/35937a8d272f1ce69979901331fb9b2a/href</a></iframe><p>Let’s plot the training and validation metrics,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bed426ac69c72329d05237ffe9c362cc/href">https://medium.com/media/bed426ac69c72329d05237ffe9c362cc/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*CRlaEtVpAw-cbc6_FVkoNQ.png" /></figure><p>The epoch’s history shows that accuracy gradually increases and achieved +86% accuracy on both training and validation set. Also, ReduceLROnPlateau is called whenever the accuracy plateau.</p><blockquote><strong>Note:</strong> The fluctuations in the epoch metrics is due to the fact that we have very low data for such a complex task.</blockquote><p>We will now visualize what we called a <strong>confusion-matrix</strong>, it is one of the most widely used evaluator for multi-class classification. It gives us a good glance of model’s performance on all classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a88e342ff8efb12d1af04f5e964c4abb/href">https://medium.com/media/a88e342ff8efb12d1af04f5e964c4abb/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*7VWOQzSVulbXVA4oLm-gMA.png" /></figure><blockquote>If we have more data to train then we will get better and more generalized model.</blockquote><p>Now, let’s visualize some predictions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7c8be6daa338525406e8d1001bdf5b4/href">https://medium.com/media/f7c8be6daa338525406e8d1001bdf5b4/href</a></iframe><blockquote><strong>Note</strong>: Here <strong>t</strong> is true label and <strong>p</strong> is predicted label</blockquote><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*2uRAoynQ1jl-sACvd3g8Sw.png" /></figure><p>Now what next? Should we stop here? No not at all. The purpose of any model is not just to train it and validate it but rather test/use it in the real world. I moved ahead way long with this project by trying many different models and more emotion classes. And at the end I integrated my model with <strong>OpenCV </strong>and tested it on videos.</p><p>Here, is a 2 minute demo video of the power of our model, in this I used many emotions and did cool annotations as well.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDGjV34robv8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDGjV34robv8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDGjV34robv8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/935893dabdd7c807e4c15d0a36aa1975/href">https://medium.com/media/935893dabdd7c807e4c15d0a36aa1975/href</a></iframe><p><a href="https://github.com/greatsharma/Facial_Emotion_Recognition">Here</a> is the full project hosted on Github.</p><blockquote>You can get the <strong>entire jupyter notebook</strong> for this story from <a href="https://www.kaggle.com/gauravsharma99/fer-using-convolutional-bidrectional-lstm">here</a>, you just need to fork it. Also if you like the notebook then <strong>up-vote</strong>, it motivates me for creating further quality content.</blockquote><p><strong>If you like this story then do clap and also share with others.</strong></p><p>Also, have a read of my other stories which includes variety of topics including,</p><ul><li><a href="https://medium.com/@greatsharma04/statistical-analysis-using-python-e83f10ca3c82"><strong>statistical analysis in python</strong></a></li><li><a href="https://medium.com/analytics-vidhya/effect-of-multicollinearity-on-linear-regression-1cf7cfc5e8eb"><strong>multi-collinearity in linear-regression</strong></a></li></ul><p>and<a href="https://medium.com/@greatsharma04"> many more</a>.</p><p>Thank-you once again for reading my stories my friends :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49d4199024f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/facial-emotion-recognition-using-convolutional-bidirectional-lstm-49d4199024f">Facial Emotion Recognition using Convolutional Bidirectional LSTM</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Facial Emotion Recognition (FER) using Keras]]></title>
            <link>https://medium.com/analytics-vidhya/facial-emotion-recognition-fer-using-keras-763df7946a64?source=rss-40c34d041b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/763df7946a64</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[facial-recognition]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Gaurav Sharma]]></dc:creator>
            <pubDate>Fri, 18 Sep 2020 10:52:51 GMT</pubDate>
            <atom:updated>2020-09-23T15:16:31.014Z</atom:updated>
            <content:encoded><![CDATA[<p>This story will walk you through FER, it’s applications and more importantly how we can create our own FER system using Tensorflow-Keras.</p><p>This story is divided into following sections,</p><ul><li>Introduction</li><li>Inspecting and manipulating the data</li><li>Creating our own custom FER model from scratch</li><li>Applications of FER systems</li></ul><h3>Introduction</h3><p>Facial Emotion Recognition (commonly known as FER) is one of the most researched field of computer vision till date and is still in continuous evaluation and improvement. The idea is, <em>can we detect the emotion a person is having by his/her facial expressions?</em> Of-course as a human we can very easily do that and in-fact we do this thousands of times every day. But <em>can we make our so called dumb-machines intelligent enough so they can also achieve human level performance on these emotion recognizing task?</em> See, because we humans have emotions that’s why we are easily able to detect other’s emotions but that’s not the case with machines.</p><p>The advancements in the field of computer vision are skyrocketing, these tasks are no more that difficult, at-least we are able to achieve good performance with very less amount of efforts. We will see how that can be done with few lines of python code.</p><blockquote><strong>Note:</strong> To get the full out of this story, you should have some basic understanding of python and some basics of neural networks specifically CNN.</blockquote><h3>Inspecting and manipulating the data</h3><p>As we all know <em>adding intelligence to machine is more about letting them learn from data via some algorithm,</em> and of-course for that we need <strong>DATA</strong>. Data is the most important part of any machine learning/ deep learning project, because after all our trained model is a product of the data on which it is trained. I mean the better our data represent the real world the more our model behave like real and perform well in real world. Remember one thing <strong>“GARBAGE IN, GARBAGE OUT”</strong>, if we train on data containing lots of garbage then in production our model also throw garbage. So, DATA is the most important building block for any ML/DL task.</p><p>So, we need data for this FER task as well. We will train our model on that and then test it’s performance on data kept aside and also in real-time video stream. Note that this is a <strong>supervised learning</strong> problem i.e., the learned model y is a function of data x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*U2ir3ULlXSPk-u8jYo7mrw.png" /></figure><p>For this task I am going to use a very popular data available at <a href="https://www.kaggle.com/ashishpatel26/facial-expression-recognitionferchallenge">kaggle</a>. It’s name is same as the task because it is collected for this purpose only. You can also use other datasets as well, there are few more which are publicly available, or you can create your own.</p><blockquote>We will get more insights in this data as we proceed, so stay tuned…</blockquote><p>Now we will wet our hands in some real python codes. Firstly import all needed libraries,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e10babe5a35bea03056fe26434b36b1/href">https://medium.com/media/7e10babe5a35bea03056fe26434b36b1/href</a></iframe><p>Let’s inspect the data,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31b0d1e76ca9abf6dd004bff9a05fbb7/href">https://medium.com/media/31b0d1e76ca9abf6dd004bff9a05fbb7/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*r4pt70atBB2REtIvadf-BA.png" /></figure><p>This data is not in image format but it’s in a format called data-frame. The pixels column of the data-frame contains all the pixel values. There total 96 pixel values associated with each image because <strong>each image is grey-scaled and of resolution 48x48.</strong></p><p>Now, we will check the number of emotion categories we have and the number of images in each of those categories.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e557117caab15c1d7a325a2f5f1fb0e/href">https://medium.com/media/8e557117caab15c1d7a325a2f5f1fb0e/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*pM6gzMEHYM7x4WIyo4tEkg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e2f67a52b971ede2b66029342ac21b5/href">https://medium.com/media/2e2f67a52b971ede2b66029342ac21b5/href</a></iframe><blockquote>So, there are 7 categories of emotions in this data-set and emotion <strong>disgust</strong> has the minimum images around 5–10% of other classes.</blockquote><p>Let’s visualize the images of each emotion category.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45a025706e3be939105a7dce34e01141/href">https://medium.com/media/45a025706e3be939105a7dce34e01141/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*Y7PLCBrpNmOo4GYYvlMOfA.png" /></figure><p>We can conclude following points from these images,</p><ul><li>The data contains a wide range of images like, male, female, kids, olds, white, black etc.</li><li>It contains some non-human images, like cartoons(first row, last column) and in-fact contains images that doesn’t contain any face but is either blank image or contain some text.</li><li>The data-set contains images in <strong>wild settings</strong>, by wild settings I mean they are not clicked in laboratory under proper lighting conditions(like <strong>ck+48</strong>). But rather <em>they are taken from web through web scraping.</em></li></ul><blockquote>For simplicity we will train our upcoming model on top three classes only i.e., <strong>3:Happy</strong>, <strong>4:Sad</strong> and <strong>6:Neutral</strong>.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1628d87b417c8e08dc49609826e81da/href">https://medium.com/media/d1628d87b417c8e08dc49609826e81da/href</a></iframe><h3>Creating our own custom FER Model</h3><p>We will create an <em>Convolutional Neural Network(CNN) </em>for this task and then we will feed batches of <strong>48x48x1</strong> gray-scaled images. But the current data we have is not in that format, so we need to make the data compatible for our model otherwise it will crash even before it start learning.</p><p>Below is the code which will make the data compatible with our upcoming model. I will explain it line by line.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56638b5a9055209c486a6c80e6cf3676/href">https://medium.com/media/56638b5a9055209c486a6c80e6cf3676/href</a></iframe><p>In<strong> line-1</strong>, I converted each flattened image into a square 3 dimensional image of size 48x48x1(note, as this is a grey-scaled image so there is only a single channel).</p><p>In <strong>line-2</strong>, I stacked all those images along the 4th dimension because we feed data as batches to our model rather than feeding one image at a time. This is because we will be using <strong>mini-batch gradient descent</strong> as our optimizer. In <strong>line-3 </strong>you can verify the shape.</p><p>Now our images(X) are ready but we also need to make our labels compatible with our model. From <strong>line 5–8</strong>, I am label encoding my categories.</p><p>le_name_mapping , is the mapping from original class label to new label. Like, the emotion <em>Happy</em> which was originally 3 is now labelled 0.</p><p>Now, will Split the data into training and validation set. We will train on training data and validate our model on validation data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65902991259cada25671b8107eb0bdee/href">https://medium.com/media/65902991259cada25671b8107eb0bdee/href</a></iframe><p>Now, we will normalize the image arrays, this is done because neural networks are highly sensitive to non-normalized data. We will use <strong>min-max normalization.</strong></p><p>For these gray-scaled images min=0, max=255 therefore we will divide the array by <strong>255 </strong>because,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*xVr_55LDXODCx339kwSm3Q.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f11e9871a53960c6165c684664f7e3a9/href">https://medium.com/media/f11e9871a53960c6165c684664f7e3a9/href</a></iframe><p>Below is a <em>Convolutional Neural Network (CNN), I used following settings :</em></p><ul><li>For generalization purpose <strong><em>dropouts</em></strong> are used at regular intervals.</li><li><strong><em>ELU</em></strong> is used as the activation function because firstly it avoids <em>dying relu problem</em> but it also performed well as compared to LeakyRelu, at-least in this case.</li><li><strong>he_normal</strong> is used as kernel initializer as it suits ELU.</li><li><strong>Batch Normalization</strong> is also used for better results.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/066e94006f21ca7e037e986d8707d085/href">https://medium.com/media/066e94006f21ca7e037e986d8707d085/href</a></iframe><p>I used two callbacks one is <strong>early stopping</strong> for avoiding over-fitting the training data and other <strong>ReduceLROnPlateau</strong> for reducing learning rate whenever the validation accuracy plateaus.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df47d13d1bba323afdd9ef392fe87987/href">https://medium.com/media/df47d13d1bba323afdd9ef392fe87987/href</a></iframe><p><strong>ImageDataGenerator </strong>is also used as this helps in model performance because we add some changes to the images which we may encounter a lot in real world like shearing, rotations etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1fe12279e75a96dbaf9bde3c195a1e7/href">https://medium.com/media/e1fe12279e75a96dbaf9bde3c195a1e7/href</a></iframe><p>I tried both <strong>Nadam</strong> and <strong>Adam </strong>optimizer but achieved similar performance. Batch size of 32 is used, and trained for a max 100 epochs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0963ea9d6929af9fdc94731fd986524/href">https://medium.com/media/e0963ea9d6929af9fdc94731fd986524/href</a></iframe><p>Let’s now train the model and log the training performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4e911136fc49f365fc31318052648c4/href">https://medium.com/media/d4e911136fc49f365fc31318052648c4/href</a></iframe><p>Let’s plot the training and validation metrics,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb5cb42ebcac51e8c6b7b845887a9697/href">https://medium.com/media/fb5cb42ebcac51e8c6b7b845887a9697/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*qfIUR-sQgNH4qm5JKSH__g.png" /></figure><p>The epoch’s history shows that accuracy gradually increases and achieved +83% accuracy on both training and validation set, but at the end the model started over-fitting training data and here the model automatically stopped because we have enabled early-stopping. Also, ReduceLROnPlateau is called whenever the accuracy plateau.</p><p>We should also save this model using save function and use this for latter use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11c7517f2bedac3d5da6833915b02968/href">https://medium.com/media/11c7517f2bedac3d5da6833915b02968/href</a></iframe><p>Let’s plot the distribution of training and validation metrics.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce96388883a5758e1a63bbf03943c4d0/href">https://medium.com/media/ce96388883a5758e1a63bbf03943c4d0/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*xn6GJOj1ddEhYSy7Fo8t0g.png" /></figure><p>We will now visualize what we called a <strong>confusion-matrix</strong>, it is one of the most widely used evaluator for multi-class classification. It gives us a good glance of model’s performance on all classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb4daaad526497965e376ce91d232171/href">https://medium.com/media/cb4daaad526497965e376ce91d232171/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*PkjUWvbi_PV_v06KgU_OJQ.png" /></figure><p>The confusion matrix clearly shows that our model is doing good job on the class happy but it&#39;s performance is low on other two classes. One of the reason for this could be the fact that these two classes have less data. But when I looked at the images I found <em>some images from these two classes are even hard for a human to tell whether the person is sad or neutral</em>. Facial expression depends on individual as well. Some person&#39;s neutral face looks more like sad.</p><p>Let’s inspect the errors,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0728d7ee5b1c7de0527026c8075317cf/href">https://medium.com/media/0728d7ee5b1c7de0527026c8075317cf/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*tgR-Tllsy4CHJkKFICNomg.png" /></figure><p>See, the first row 7th image <em>looks more like neutral rather than sad</em> and our model even predicted it neutral. Whereas the last image in second row is <em>very much sad rather than neutral </em>which indeed our model predicted. So,<strong> our model error rate is around 17% but some of the errors made by our model is due to the errors in the data itself.</strong></p><p>Now what next? Should we stop here? No not at all. The purpose of any model is not just to train it and validate it but rather test/use it in the real world. I moved ahead way long with this project by trying many different models and more emotion classes. And at the end I integrated my model with <strong>OpenCV </strong>and tested it on videos and even on real-time webcam stream. I did this by feeding video <strong>frame by frame</strong> to my model. I achieved good fps, close to real-time predictions.</p><p>Here, is a 2 minute demo video of the power of our model, in this I used many emotions and did cool annotations as well.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDGjV34robv8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDGjV34robv8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDGjV34robv8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/935893dabdd7c807e4c15d0a36aa1975/href">https://medium.com/media/935893dabdd7c807e4c15d0a36aa1975/href</a></iframe><p><a href="https://github.com/greatsharma/Facial_Emotion_Recognition">Here</a> is the full project hosted on Github.</p><h3>Applications of FER systems</h3><p>There are many applications and some are even emerging, I mentioned few of them :</p><ul><li>In customer satisfaction for a product(Visual sentiment analysis)</li><li>In medical diagnosis</li><li>Understanding human behaviour</li><li>For fun … :)</li></ul><blockquote>You can get the <strong>entire jupyter notebook</strong> for this story from <a href="https://www.kaggle.com/gauravsharma99/facial-emotion-recognition">here</a>, you just need to fork it. Also if you like the notebook then <strong>up-vote</strong>, it motivates me for creating further quality content.</blockquote><p><a href="https://medium.com/@greatsharma04/facial-emotion-recognition-using-convolutional-bidirectional-lstm-49d4199024f">Here</a> is the second part of this FER series, in this I explained how we can feed tiny video clips as input to the model. For that I used <strong>time-distributed Convolutional </strong>followed by<strong> Bidirectional LSTM. </strong>It’s a must read, you will surely learn something new.</p><p><strong>If you like this story then do clap and also share with others.</strong></p><p>Also, have a read of my other stories which includes variety of topics including,</p><ul><li><a href="https://medium.com/@greatsharma04/statistical-analysis-using-python-e83f10ca3c82"><strong>statistical analysis in python</strong></a></li><li><a href="https://medium.com/analytics-vidhya/effect-of-multicollinearity-on-linear-regression-1cf7cfc5e8eb"><strong>multi-collinearity in linear-regression</strong></a></li></ul><p>and<a href="https://medium.com/@greatsharma04"> many more</a>.</p><p>Thank-you once again for reading my stories my friends :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=763df7946a64" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/facial-emotion-recognition-fer-using-keras-763df7946a64">Facial Emotion Recognition (FER) using Keras</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effect of Multi-collinearity on Linear Regression]]></title>
            <link>https://medium.com/analytics-vidhya/effect-of-multicollinearity-on-linear-regression-1cf7cfc5e8eb?source=rss-40c34d041b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cf7cfc5e8eb</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[multicollinearity]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Gaurav Sharma]]></dc:creator>
            <pubDate>Thu, 17 Sep 2020 10:24:56 GMT</pubDate>
            <atom:updated>2020-09-23T15:19:56.773Z</atom:updated>
            <content:encoded><![CDATA[<p>This story is divided into following experiments -</p><blockquote><strong>Experiment 1 </strong>— Effect of highly correlated attributes on their respective coefficients<br><strong>Experiment 2 </strong>— Effect of no/less correlated attributes on their respective coefficients<br><strong>Experiment 3 </strong>— Effect of data with both high/low correlated attributes on their respective coefficients<br><strong>Experiment 4 </strong>— Effect of correlated attributes on model’s prediction</blockquote><p>And the end we will study <strong>VIF.</strong></p><p>Before starting we should clear some basics,</p><ul><li>The regression coefficient value associated with an attribute represents the <strong>mean change of the dependent variable given a one-unit shift in an independent variable</strong>.</li><li>We cannot compare two regression coefficients because they can be on different scale, for e.g. if coefficient of x1 is 2 and coefficient of x2 is 4 then we cannot directly say that x2 is more important than x1, because they can be on different scales. Like x1 is distance in km and x2 is weight in grams.</li><li>But we can compare two standardized regression coefficients.</li></ul><blockquote>Throughout the notebook I will directly compare regression coefficient because they are on the same scale as I cooked the data artificially.</blockquote><p><strong>Note:</strong> Whenever I say <strong>estimate of x</strong>, I mean <strong>estimate of coefficient of x</strong>.</p><p>Firstly, import all necessary libraries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/517bc45fcfe8fe5eaa1c570423cdd111/href">https://medium.com/media/517bc45fcfe8fe5eaa1c570423cdd111/href</a></iframe><h4>Experiment 1</h4><blockquote>Effect of highly correlated attributes on their respective coefficients.</blockquote><p>First we cook some artificial data,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9bd8dbd77c2864ddca1c336dfecd76f/href">https://medium.com/media/f9bd8dbd77c2864ddca1c336dfecd76f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b8a7ad0ef0bddbb63e886319dbcd5e6/href">https://medium.com/media/8b8a7ad0ef0bddbb63e886319dbcd5e6/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*klTikidLuzNxsk7-fhO9sw.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee23de1f5c100a4da730661b03591f59/href">https://medium.com/media/ee23de1f5c100a4da730661b03591f59/href</a></iframe><p>Now, we apply linear regression to estimate the coefficients of each attribute.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63d09449fcb56fe27aeaa70035548c24/href">https://medium.com/media/63d09449fcb56fe27aeaa70035548c24/href</a></iframe><h4>Interpretation of result</h4><p>These estimated coefficients means <em>one unit change in x1 changes on average approx. 2 units of y in same direction and one unit change in x2 changes on average approx. 2 units of y in opposite direction</em>. Which we know is true as we did these settings while cooking the data. So, when these 2 highly correlated features are feeded independently to the linear regression then the coefficient’s estimates are very close to true values.</p><blockquote>The slight errors in the estimated parameters is due to the noise in data, if we have clean data with no noise then the estimated parameters converges to true parameters.</blockquote><p>now, fit both x1 and x2</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14b4b18b79120d4868ff103a762c96d0/href">https://medium.com/media/14b4b18b79120d4868ff103a762c96d0/href</a></iframe><h4>Interpretation of result</h4><p>These estimated coefficients means <em>one unit change in x1 changes approx. 1 units of y in same direction and one unit change in x2 changes approx. 1 units of y in opposite direction.</em> Which we know is not true as we did different settings while cooking the data.</p><p>The reason for this is because the two features are highly correlated(<em>perfect correlation in this case</em>) their contribution is divided equally in changing the response. The coefficient of x1 no more interpreted as the change in y on 1 unit change in x1 but it’s now interpreted as <strong>change in y on 1 unit change in x1 given 1 unit change of x2</strong>, i.e., it is <strong>conditioned</strong> now. This is because if x1 &amp; x2 would have 0 correlation between them then we can keep x2 constant and change x1 by one unit and detect the change in y but now because of such a high correlation b/w them we can’t keep x2 constant on changing x1, if we change x1 a bit x2 also changes depending on it’s correlation with x1.</p><p>So long story short, if now someone looks at these coefficients then they interpret the results as <em>one unit change in x1 changes approx 1 units of y in same direction and one unit change in x2 changes approx 1 units of y in opposite direction</em>. <em>Such bad estimates are very dangerous because our interpretation of model results in critical decision making and if results are wrong then interpretation is wrong and hence decisions are wrong</em>. This may have critical effects in medical field as these two features could be some components of drugs and we may be interested in their effect on some disease(i.e., y in this case).</p><blockquote>So when 2 or more highly correlated features are feeded to the linear regression their estimates are very bad and can’t be trusted. Hence, multi-collinearity results in less reliable estimates and this reliability is inversely proportional with level multi-collinearity i.e., more multi-collinearity means less reliable coefficients.</blockquote><h4>Experiment 2</h4><blockquote>Effect of no/less correlated attributes on their respective coefficients.</blockquote><p>First we cook some artificial data,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea0387446672a03b04252b4ff577ab7b/href">https://medium.com/media/ea0387446672a03b04252b4ff577ab7b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0da7c162ca3a20a359278a3805684773/href">https://medium.com/media/0da7c162ca3a20a359278a3805684773/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*iLstC_ScugkYaOh1a2qq9g.png" /></figure><p>We can see from the plots that both x1 &amp; x2 are positively correlated with y but has very less correlation with each other and this is also verified by below pearson’s correlation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d9f2eb6e1e47ab9d65e89f21437705e/href">https://medium.com/media/3d9f2eb6e1e47ab9d65e89f21437705e/href</a></iframe><p>The low pearson’s correlation between x1 &amp; x2 suggests that there is very less correlation between them, and can even be rejected under significance level of 5%.</p><blockquote>So due to less multi-collinearity estimated coefficients are now more reliable.</blockquote><p>Now, we apply linear regression to estimate the coefficients of each attribute.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac4857db117cfd7149ff43c97af4dac1/href">https://medium.com/media/ac4857db117cfd7149ff43c97af4dac1/href</a></iframe><blockquote>Although the estimated parameters are quite reasonable but there are some errors in them and that’s not just due to the noise in data but also due to the fact that y depends on both x1 and x2 (as y=y1+y2)</blockquote><p>now, fit both x1 and x2</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/854d619d3fd4280ecc8d0ab4b1a2bbd3/href">https://medium.com/media/854d619d3fd4280ecc8d0ab4b1a2bbd3/href</a></iframe><p>We can see that due to very less multi-collinearity both the estimated coefficients are not affected a lot and even the estimates are improved after taking both x1 &amp; x2 because y is y1+y2. Hence, depending on both x1 &amp; x2, therefore using both the predictors which impact y we get better and more accurate estimates.</p><h4>Experiment 3</h4><blockquote>Effect of data with both high/low correlated attributes on their respective coefficients.</blockquote><p>First we cook some artificial data,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90807d4d77c9a8c2389b7b0a691625f5/href">https://medium.com/media/90807d4d77c9a8c2389b7b0a691625f5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7579b1b57b000179af30751cdc922fd8/href">https://medium.com/media/7579b1b57b000179af30751cdc922fd8/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*8uPh2aXgdzLkpF5KwoRUrA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db86b48ef926cd8a66de71b6eb17a84e/href">https://medium.com/media/db86b48ef926cd8a66de71b6eb17a84e/href</a></iframe><p>So basically x1 &amp; x3 are perfectly correlated but the pairs (x1,x2) &amp; (x2,x3) have very less correlation.</p><p>Now, we apply linear regression to estimate the coefficients of each attribute. We will first fit x1, x2 and x3 individually,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62e054da390cb5d8f8da5c14398343f2/href">https://medium.com/media/62e054da390cb5d8f8da5c14398343f2/href</a></iframe><p>now, fit x in pairs</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b03acfa371938b8342cce06a1e012a2/href">https://medium.com/media/5b03acfa371938b8342cce06a1e012a2/href</a></iframe><p>The coefficient estimates of x1, x2, x3 are pretty close to true parameters but a bit noisy and the reason is already explained above. Also <strong>due to high multi-collinearity estimates get highly affected when y is regressed on x1 &amp; x3 combined.</strong> But the estimates are improved when y is regressed on both x2 &amp; x3 due to the fact that y is composed of both (x1, x2) and x3 is nothing but -x2, hence regressor get everything that is needed to estimate true behaviour.</p><p>now, fit all x1, x2 and x3</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30280c94ab834fea398cf57dfe1b9abf/href">https://medium.com/media/30280c94ab834fea398cf57dfe1b9abf/href</a></iframe><p>So, if you followed the notebook then this result is not unexpected for you.</p><p>Because x1 &amp; x3 are perfectly correlated hence the estimates of their coefficient are affected a lot and in this case get exactly half due to correlation of -1. But you may have noticed that coefficient of x2 is not affected at all and even get improved. This is due to the fact that x2 has very low correlation with both x1 &amp; x3, hence multi-collinearity between x1 &amp; x3 has no affect on it’s estimates. Also the estimates are improved due to the fact that y depends on both x1 &amp; x2 and we provided both.</p><blockquote><strong>Ground Truth</strong><br> — one unit change in x1 changes 1 unit of y in same direction<br> — one unit change in x2 changes 2 units of y in same direction<br> — one unit change in x3 changes 1 unit of y in opposite direction</blockquote><blockquote><strong>Interpretation from results</strong><br> — one unit change in x1 changes 1 unit of y in same direction (which is absolutely False)<br> — one unit change in x2 changes 2 units of y in same direction (which is absolutely True)<br> — one unit change in x3 changes 1 unit of y in opposite direction(which is absolutely False)</blockquote><p>Although we see that multi-collinearity affects the estimated parameters but <strong>what about prediction?</strong> because in some rare cases we may not be that much interested in interpreting the results as compared to getting high prediction accuracy (though such cases are very rare, but the idea is we are happy if we get good overall predictions even though individual estimates are wrong).</p><h4>Experiment 4</h4><blockquote>Effect of correlated attributes on model’s prediction.</blockquote><p>We will use the same experiment_1 data and do a train-test split,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19013a7e15ac675a61fe9a73ffbd2d17/href">https://medium.com/media/19013a7e15ac675a61fe9a73ffbd2d17/href</a></iframe><p>we first fit x1 only,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/467d61070707d465f97939b027c48d40/href">https://medium.com/media/467d61070707d465f97939b027c48d40/href</a></iframe><p>now, fit both x1 and x2</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c12a2c314ac0f37a5be2044ff0cdcfea/href">https://medium.com/media/c12a2c314ac0f37a5be2044ff0cdcfea/href</a></iframe><blockquote>So multi-collinearity has no significant effect on the model’s performance and it’s kind of make sense because individual estimates are affecting each other only. You can think of this like if <strong>two correlated variables are just two entangled variables</strong>(where strength of entanglement is proportional to the strength of collinearity between them) such that if one changes other also changes therefore making the end result same.</blockquote><h4>Conclusions</h4><p>From these experiments we conclude following results</p><ul><li>If model has coupled/collinear features than their estimated coefficients are affected, hence can’t be trusted. Also the effect depends on degree/severity of collinearity, less collinearity have negligible effect and high collinearity have huge effect. (<strong>proved from exp1 &amp; exp2</strong>)</li><li>In a model the estimated coefficients are affected only for those features which are involved in collinearity with other. (<strong>proved from exp3</strong>)</li><li>Multi-collinearity doesn’t effect the predictive power of the model. (<strong>proved from exp4</strong>)</li></ul><h4>Long Story Short</h4><p>If model’s predictive performance is your only goal then no need to worry about multi-collinearity but if interpretation of fitted model is your primary goal or as important as performance then you should not rely your decisions on the bases of fitted model.</p><p>So, the next question that arise is do we need to find multi-collinearity manually and if so then what in case of large number of predictors. Isn’t there a tool for that? And the answer is we are not required to do it manually. Most of the tools uses <strong>Variance Inflation Factor(VIF)</strong> for finding the strength of multi-collinearity among predictors.</p><h4>Variance Inflation Factor</h4><p>VIF detects multi-collinearity in regression analysis for every predictor by taking that predictor, and regressing it against every other predictor in the model giving a R-squared value and then substituting it in the VIF formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*E8N9twHkW5V-WziDjzznXw.png" /></figure><p>where, R_{i}^{2} is the R-squared value of i-th predictor.</p><p>The value of VIF tells what percentage variance (i.e. the standard error squared) is inflated for each coefficient. For example, a VIF of 1.9 tells that the variance of a particular coefficient is 90% bigger than what you would expect if there was no multi-collinearity — if there was no correlation with other predictors.</p><blockquote>Interpretation of VIF:<br> 1 is not correlated.<br> 1–5 is moderately correlated.<br> &gt;5 is highly correlated.</blockquote><p>let’s define a function for VIF,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b75f5eef424ff9665f8865f84bc5b629/href">https://medium.com/media/b75f5eef424ff9665f8865f84bc5b629/href</a></iframe><p>we will use the same experiment_3 data,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cfca8f6a749285108079dc10b52560d/href">https://medium.com/media/3cfca8f6a749285108079dc10b52560d/href</a></iframe><p>let’s first fit the OLS on just x1 and x2 (they are not correlated),</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c38913f6f612a9f859362462798b1386/href">https://medium.com/media/c38913f6f612a9f859362462798b1386/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b6244c70dbd34e8394da1ddf1746e5e/href">https://medium.com/media/2b6244c70dbd34e8394da1ddf1746e5e/href</a></iframe><p>So, all the estimated parameters are same as the true parameters. Also, VIF of both x1 &amp; x2 is almost 1 indicating they are not correlated with each other hence <strong>every estimates and statistics calculated by OLS are correct and can be trusted.</strong></p><p>now, fit the OLS on all x1, x2 and x3 (note, x1 and x3 are correlated),</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/357c98a50d285c97b293a59df9457726/href">https://medium.com/media/357c98a50d285c97b293a59df9457726/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/205b3a405eae88f770d96a08adbcfb20/href">https://medium.com/media/205b3a405eae88f770d96a08adbcfb20/href</a></iframe><p>So, all the estimated parameters are not same as the true parameters. x1 &amp; x3 have wrong estimates due to perfect correlation but x2 has correct estimate due to no correlation. Also, VIF of both x1 &amp; x3 is infinity indicating that they are perfectly correlated with each other hence, <strong>their estimates and statistics calculated by OLS are incorrect and can’t be trusted.</strong> But x2 has no impact and we can trust all it’s estimates and statistics.</p><blockquote>Also note the warning [2], OLS automatically find such an high multi-collinearity in the design matrix.</blockquote><h4>Some techniques to deal with multi-collinearity</h4><ul><li>Step-wise removal of predictors having large VIF i.e., <strong>regress-remove-regress</strong> cycle until all VIF’s are in satisfying range.</li><li>Both ridge regression and lasso regression are addressed to deal with multi-collinearity or a mixture of these i.e., elastic-net regression.</li><li>Apply PCR(principal component regessor) but this will result in loss of model interpretation as principal components are hard to interpret and if that’s the case then you won’t apply it.</li></ul><p>Lasso regression,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2ee51e09e042670b5359c24d0ea29ed/href">https://medium.com/media/c2ee51e09e042670b5359c24d0ea29ed/href</a></iframe><p>ridge regression,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6299d07e151f897f9cafaaee012978da/href">https://medium.com/media/6299d07e151f897f9cafaaee012978da/href</a></iframe><p>elastic-net regression,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a4977e1de51afbff179c789d8d3d5ea/href">https://medium.com/media/6a4977e1de51afbff179c789d8d3d5ea/href</a></iframe><blockquote>We see that this regularized regressors moves one correlated variable close to zero resulting in better estimate of the other variable. This is because in this case one of the x1 &amp; x2 are redundant i.e., only one is needed hence it’s good to make one of them close to or equal to zero resulting in better estimates of the other.</blockquote><blockquote>You can get the <strong>entire documented jupyter notebook</strong> for this blog from <a href="https://www.kaggle.com/gauravsharma99/effect-of-multicollinearity-on-linear-regression">here</a>, you just need to fork it. Also if you like the notebook then <strong>up-vote</strong>, it motivates me for creating further quality content.</blockquote><p><strong>If you like this story then do clap and also share with others.</strong></p><p>Also, have a read of my other stories which includes variety of topics including,</p><ul><li><a href="https://medium.com/@greatsharma04/statistical-analysis-using-python-e83f10ca3c82"><strong>statistical analysis in python</strong></a></li><li><a href="https://medium.com/@greatsharma04/facial-emotion-recognition-fer-using-keras-763df7946a64"><strong>facial emotion recognition (fer) using keras</strong></a></li></ul><p>and<a href="https://medium.com/@greatsharma04"> many more</a>.</p><h4>References</h4><ul><li><a href="https://statisticsbyjim.com/regression/identifying-important-independent-variables/">identifying-important-independent-variables</a></li><li><a href="https://statisticsbyjim.com/regression/ols-linear-regression-assumptions/">classical assumptions for linear regression</a></li><li><a href="https://www.statisticshowto.datasciencecentral.com/variance-inflation-factor/">VIF</a></li></ul><p><strong>Thank-you once again for reading my stories my friends :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cf7cfc5e8eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/effect-of-multicollinearity-on-linear-regression-1cf7cfc5e8eb">Effect of Multi-collinearity on Linear Regression</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistical Analysis using Python]]></title>
            <link>https://medium.com/analytics-vidhya/statistical-analysis-using-python-e83f10ca3c82?source=rss-40c34d041b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/e83f10ca3c82</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[scipy]]></category>
            <category><![CDATA[statistical-anaylsis]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Gaurav Sharma]]></dc:creator>
            <pubDate>Wed, 16 Sep 2020 07:03:45 GMT</pubDate>
            <atom:updated>2020-09-18T11:01:41.093Z</atom:updated>
            <content:encoded><![CDATA[<p>If you already visited <a href="https://medium.com/@greatsharma04/eda-for-beginners-using-python-4fcd2b57d1f7"><strong>Part1-EDA</strong></a> then you can directly jump to <a href="https://medium.com/@greatsharma04/statistical-analysis-using-python-e83f10ca3c82#0e8a">this</a> (<strong>Statistical Analysis</strong> section).</p><p>This is a <strong>3 part series</strong> in which I will walk through a data-set analyzing it and then at the end do predictive modelling. I highly recommend to follow this series in the order given below but you can also jump to any part.</p><p><a href="https://medium.com/@greatsharma04/eda-for-beginners-using-python-4fcd2b57d1f7"><strong>Part 1, Exploratory Data Analysis(EDA)</strong></a><strong>:</strong><br> This part consists of summary statistics of data but the major focus will be on EDA where we extract meaning/information from data using plots and report important insights about data. This part is more about <strong>data analysis</strong> and <strong>business intelligence(BI)</strong>.</p><p><strong>Part 2, Statistical Analysis:</strong><br> In this part we will do many statistical hypothesis testing, apply estimation statistics and interpret the results we get. We will also validate this with the findings from part one. We will apply both parametric and non-parametric tests. We will report all the important insights we get in this part. This part is all about <strong>data science</strong> requires statistical background.</p><p><a href="https://github.com/greatsharma/MPG/tree/master/Modelling"><strong>Part 3, Predictive Modelling:</strong></a><br> In this part we will predict a response using given predictors. This part is all about <strong>machine learning</strong>.</p><h4>Meta-Data, Data about Data</h4><p>I am using the <a href="https://archive.ics.uci.edu/ml/datasets/auto+mpg">auto mpg</a> data for EDA taken from the <a href="https://archive.ics.uci.edu/ml/index.php">UCI repository</a>.</p><p><strong>Title:</strong> Auto-Mpg Data<br><strong>Number of Instances:</strong> 398<br><strong>Number of Attributes:</strong> 9 including the class attribute<br><strong>Attribute Information:</strong></p><pre>1. mpg — continuous<br>2. cylinders — multi-valued discrete<br>3. displacement — continuous<br>4. horsepower — continuous<br>5. weight — continuous<br>6. acceleration — continuous<br>7. model year — multi-valued discrete<br>8. origin — multi-valued discrete<br>9. car name — string (unique for each instance)</pre><p>This data is not complex and is good for analysis as it has a nice blend of both categorical and numerical attributes.</p><p>This is <strong>part 2</strong> i.e., Statistical Analysis. I won’t stretch this part too long and do following things in sequential manner.</p><ol><li><strong>Some Pre-processing of the data</strong>, exact same as<a href="https://medium.com/@greatsharma04/eda-for-beginners-using-python-4fcd2b57d1f7"> <strong>Part1-EDA</strong></a>.</li><li><strong>Tests for independence between two categorical attributes</strong></li><li><strong>Normality Test for numeric attributes</strong></li><li><strong>Correlation between numeric attributes</strong></li><li><strong>Parametric and Non-Parametric test for samples</strong></li></ol><blockquote>I will make use of <strong>hypothesis-testing</strong> heavily throughout the notebook, so it is also a good to go notebook for those who are looking for how to apply hypothesis-testing in data science and machine learning.</blockquote><p>Firstly, import all necessary libraries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b07d5e76991f6b444bb347c34285909e/href">https://medium.com/media/b07d5e76991f6b444bb347c34285909e/href</a></iframe><blockquote>The coming few cells involve <strong>data cleaning</strong>, this includes dealing with missing values, duplicate data if any and aligning the data. I already covered this in <a href="https://medium.com/@greatsharma04/eda-for-beginners-using-python-4fcd2b57d1f7">part1</a>. So you can skip to <a href="https://medium.com/@greatsharma04/statistical-analysis-using-python-e83f10ca3c82#0e8a">this</a> cell if you already visited part1.</blockquote><p>We will first import the data into a pandas data-frame and inspect it’s properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0248d43da5bcac7b3b9908d88ab7204d/href">https://medium.com/media/0248d43da5bcac7b3b9908d88ab7204d/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*hgaOYnV0K34DT_sEXTUSsg.png" /></figure><p>The data is in rectangular(tabular) form, with 398 entries, each having 9 distinct attributes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdbc7c0c0b32c92fa1a3b6aa566db6ea/href">https://medium.com/media/cdbc7c0c0b32c92fa1a3b6aa566db6ea/href</a></iframe><p>To inspect meta-data (i.e., data about data), we can use an inbuilt pandas function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/873103fd326d428714a13d48e66cc72d/href">https://medium.com/media/873103fd326d428714a13d48e66cc72d/href</a></iframe><p>df.info() , describes many things about the data, like data type of each column, memory usage etc.</p><p>Now, I will make two distinct list for categorical and numerical column names as the analysis differ for both the types. For that I will introspect the datatype of each column and if it is of type object then it&#39;s categorical, else numerical.</p><p>I will use these two lists heavily throughout the analysis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27ac1fb81d07af7f142e5550edc94912/href">https://medium.com/media/27ac1fb81d07af7f142e5550edc94912/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f3bddc4ea210f51a639791d5119a1c5/href">https://medium.com/media/1f3bddc4ea210f51a639791d5119a1c5/href</a></iframe><p>As there are very few unique values for cylinders and model_year, so it’s safe to make them categorical instead numeric. <em>This conversion will be helpful during analysis as I will bifurcate some attributes on the basis of other</em>.</p><p>Lists should be updated,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8be12b1654673c494088b9e40ca61fe/href">https://medium.com/media/a8be12b1654673c494088b9e40ca61fe/href</a></iframe><p>Now, inspect for nans in the data. I will check for nans column-wise.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e08dd1f4d70b29bf7a642824db7efd7b/href">https://medium.com/media/e08dd1f4d70b29bf7a642824db7efd7b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57ff6a7b3746fe03f98392607cc67342/href">https://medium.com/media/57ff6a7b3746fe03f98392607cc67342/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*moy0ZkhZ6DOodkcbagrDGA.png" /></figure><p>The nan-row proportion in the data is 6 / len(df) = 0.01507. So, horsepower consists all 6 nan rows, comprising of around 1.5% of data. As this fraction is very low so it’s safe to drop the nan rows for now.</p><blockquote><strong>Note:</strong> If the nan proportion is large (more than 5%) then we won’t drop it but instead impute missing values or can even treat missing as another attribute.</blockquote><p>For now remove all nan rows as they are just 1.5%.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78271c066b35429a53d576a817a694dc/href">https://medium.com/media/78271c066b35429a53d576a817a694dc/href</a></iframe><p>Let’s see how many duplicate entries are there and drop them if there are any.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da6517228312e64599ee8ea5fd40d341/href">https://medium.com/media/da6517228312e64599ee8ea5fd40d341/href</a></iframe><p>So, there are no duplicate rows.</p><p>The coming code cell is already explained in-depth in <a href="https://medium.com/@greatsharma04/eda-for-beginners-using-python-4fcd2b57d1f7"><strong>Part1-EDA</strong></a> so please refer that if you feel uncomfortable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/673570d2574660aba190de561a2faeaf/href">https://medium.com/media/673570d2574660aba190de561a2faeaf/href</a></iframe><p>Before we move ahead it’s a good practice to group all variables together having the same type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/938b7074f4673a01f64f1a05e042437c/href">https://medium.com/media/938b7074f4673a01f64f1a05e042437c/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*zpfHsaSBwSFlv55yFX1kog.png" /></figure><h3>Statistical Analysis</h3><p>Before moving we should first have a good understanding of various terms used in statistics. Otherwise as we move we will surely lost while interpreting the results.</p><ul><li><strong>Population:</strong> The entire data or entire possible observations.</li><li><strong>Sample:</strong> A subset of observations taken from population. As the sample size increases sample will represent the population more closely(<strong>Law of Large Numbers</strong>).</li><li><strong>Parameters:</strong> It’s the property of population which we are interested in and never know the exact value unless we do analysis on entire population(which is never the case) e.g, mean(mu).</li><li><strong>Estimates:</strong> It’s sample idea/value about the population parameters. The entire goal of statistics is to make these sample estimates as close as population parameters e.g, average(x bar) is the best possible sample estimate of mean.</li><li><strong>Descriptive Statistics:</strong> It’s for summarizing data.</li><li><strong>Inferential Statistics:</strong> It’s for drawing conclusions about the population from samples eg., estimating population mean using sample average.</li><li><strong>Parametric Statistics:</strong> Statistical methods where we assume a distribution of the data such as Gaussian.</li><li><strong>Non-Parametric Statistics:</strong> Statistical methods where we do not assume any distribution of the data i.e., distribution free.</li><li><strong>Statistical Hypothesis Tests:</strong> Methods that quantify the likelihood of observing the result given an assumption or expectation about the result. We will talk on this more later.</li><li><strong>Estimation Statistics:</strong> Methods that quantify the uncertainty of a result using confidence intervals.</li></ul><h4>Statistical Hypothesis Tests</h4><p>The idea of Statistical Hypothesis Tests is very simple and straight forward. We first assumes something about the data like two samples has same mean etc. And then we find the likelihood of observing the given data assuming this assumption as true. If the likelihood is close to zero then we <strong>reject the assumption</strong> and if the likelihood has value greater than some threshold(set by us) then we <strong>fail to reject the assumption</strong>.</p><p>In statistics lingo the assumption is called <strong>Hypothesis</strong>, the likelihood we get is called <strong>p-value</strong>, the threshold we set is of two types either <strong>level of significance</strong> or <strong>critical value</strong> and the test we use is called <strong>Statistical Hypothesis Tests</strong>.</p><p>So if the likelihood we get is very close to zero then that mean <strong>assuming this hypothesis to be true the likelihood of observing/occurring this data is very less</strong> so that suggests there is something wrong with our assumption. So in the example to means of 2 samples, if the resulted p-value is very close to zero than we can say that <strong>assuming the two samples having the same mean the data we have in hand is very less likely to be generated hence there is something wrong with our assumption and hence we reject it.</strong></p><blockquote><strong>Note:</strong> all this is probabilistic and we can do mistakes sometimes and there are known name for those mistakes namely False Positive and False Negative.</blockquote><h4>Hypothesis</h4><p>There are two type of hypothesis namely-<br><br> <strong>Null Hypothesis, <em>H_0</em> </strong>— A null hypothesis, proposes that no significant difference exists in a set of given observations.<br> <strong>Alternate Hypothesis, <em>H_1 </em></strong>— An alternate hypothesis, proposes that there is a significant difference exists in a set of given observations.</p><p>For the purpose of these tests in general,</p><p><strong><em>H_0</em></strong>: Variable A and Variable B are independent<br><strong><em>H_1</em></strong>: Variable A and Variable B are not independent.</p><blockquote><strong>Note:</strong> H_0 and H_1 are complement of each other.</blockquote><h4>p-value</h4><p>It’s the probability of data given the assumption in a statistical test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*kmFjwUIybSr0MBZ75gzMYw.png" /></figure><p>The <strong>statistical significance</strong> of any finding is done by interpreting the p-values. P-value tells us that whether are findings are due to same real change or they are just random fluctuations.</p><ul><li><strong>p-value ≤ alpha</strong>: significant result, reject null hypothesis.</li><li><strong>p-value &gt; alpha</strong>: not significant result, fail to reject the null hypothesis.</li></ul><p>A p-value can be calculated from a test statistic by retrieving the probability from the test statistics cumulative density function (CDF).</p><p>Some tests return a test statistic value from a specific data distribution that can be interpreted in the context of critical values. A <strong>critical value</strong> is a value from the distribution of the test statistic after which point the result is significant and the null hypothesis can be rejected.</p><ul><li><strong>Test Statistic &lt; Critical Value</strong>: not significant result, fail to reject null hypothesis.</li><li><strong>Test Statistic ≥ Critical Value</strong>: significant result, reject null hypothesis.</li></ul><p><strong>Note:</strong> The most common value for significance level used throughout the data science and ML is 5% i.e., alpha=0.05 and we will be using this same value throughout this notebook.</p><p><a href="https://qphs.fs.quoracdn.net/main-qimg-0138e6d464b3ff6320971528e4e72c04">refer this decision tree</a></p><p>Throughout the blog I am assuming the value of alpha as 0.05</p><pre>ALPHA = 0.05</pre><h4>Tests for independence between two categorical variables</h4><h4>Pearson’s Chi-square test</h4><p>The Chi-square statistic is a <strong>non-parametric statistic</strong> tool designed to analyze group differences when the dependent variable is measured at a nominal level(ordinal data can also be used). It is commonly used to compare observed data with data we would expect to obtain according to a specific hypothesis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*78D8WzhRFxtqkskqbqwLUQ.png" /></figure><p>Where,<br> O : Observed (the actual count of cases in each cell of the table)<br> E : Expected value (calculated below)<br> chi ^{2} : The cell Chi-square value</p><p><strong>Assumptions</strong><br> <strong>1.</strong> The test becomes invalid if any of the expected values are below 5<br> <strong>2.</strong> The p value calculated is not exact but approximate and converges to exact on increasing data(so not good for small sample size)<br> <strong>3.</strong> The number of observations must be 20+</p><p>So, if the expected cell counts are small, it is better to use an exact test as the chi-squared test is no longer a good approximation in such cases. To overcome this we will be using fisher exact test.</p><h4>Fisher’s exact test</h4><p>Fisher’s exact test is used to determine whether there is a significant association between two categorical variables in a contingency table. Fisher’s exact test is an alternative to Pearson’s chi-squared test for independence. While actually valid for all sample sizes, Fisher’s exact test is practically applied when sample sizes are small. A general recommendation is to use Fisher’s exact test- instead of the chi-squared test — whenever more than 20 % of cells in a contingency table have expected frequencies &lt; 5.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0eafd662efd8e5307ee8e9f4e4355bd/href">https://medium.com/media/b0eafd662efd8e5307ee8e9f4e4355bd/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*vT0PppuWaMl4PyZ4EMRd3g.png" /></figure><p>So chi2 assumption failed for every pair but it&#39;s not that we can&#39;t apply, we can but the results are not reliable. But the contingency table of origin and model_year is still good to try as most values are &gt;= 5.</p><p><strong><em>H_0</em></strong>: origin are model_year are independent, alpha=0.05</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c4316e253dc355568670366dcdafa76/href">https://medium.com/media/7c4316e253dc355568670366dcdafa76/href</a></iframe><p>We will use chi2_contingency function of scipy,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbd7687299865a0734c7a9b0c91ddbf4/href">https://medium.com/media/dbd7687299865a0734c7a9b0c91ddbf4/href</a></iframe><p>For more information execute help(stats.chi2_contingency) .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0822b423977f2d1e8beb49f34636451/href">https://medium.com/media/b0822b423977f2d1e8beb49f34636451/href</a></iframe><p>scikit-learn also has chi2 test available, let’s use it to test dependency of all categorical attributes with mpg_level .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2a25e5f91c3d2a22c3897ebba6a5d2b/href">https://medium.com/media/a2a25e5f91c3d2a22c3897ebba6a5d2b/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*SgE8vCIhERBToRdoVZygHg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ab83fe451a2df47ceb489ecde6b7234/href">https://medium.com/media/9ab83fe451a2df47ceb489ecde6b7234/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*LttXYRE1v-a8HeqGFw6i4A.png" /></figure><h4>Statistical Tests for Numerical Attributes</h4><p>Following are the numerical/continuous attributes in our data-set.</p><pre>nums = [&#39;mpg&#39;, &#39;displacement&#39;, &#39;horsepower&#39;, &#39;weight&#39;, &#39;acceleration&#39;]</pre><h4>Normality Test</h4><p>I divided normality test into two parts -</p><h4>1. Visual Normality Checks</h4><p>We will visually check for normality using -</p><ol><li>Histogram</li><li>Quantile-Quantile plot</li></ol><h4>2. Statistical Normality Tests</h4><p>There are three statistical tests for checking the normality of data -</p><ol><li>Shapiro-Wilk Test (only for gaussian distribution)</li><li>D’Agostino’s K 2 Test (only for gaussian distribution)</li><li>Anderson-Darling Test (for many other distributions as well)</li></ol><p>I will use Shapiro-Wilk Test but you can try other as well.</p><h4>Visual Normality Checks</h4><p>From these distributions generated in <a href="https://medium.com/@greatsharma04/eda-for-beginners-using-python-4fcd2b57d1f7"><strong>Part1-EDA</strong> </a>we can clearly see that acceleration is gaussian, mpg and weight are right-skewed or maybe log-normal.</p><figure><img alt="image.png" src="https://cdn-images-1.medium.com/proxy/1*U3SHa7rI70nmzDmqmRNKrg.png" /></figure><p>A <strong>log-normal distribution</strong> is a distribution of a random variable whose logarithm is normally distributed. Thus, if the random variable X is log-normally distributed, then Y = ln(X) has a normal distribution.</p><p>We will check whether mpg and weight are log-normal or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e903b611ed8f138b7daa7feeec7e44e7/href">https://medium.com/media/e903b611ed8f138b7daa7feeec7e44e7/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*CoQVtirk6ykhjDXZAEFJCg.png" /></figure><p>So after applying log transformation we find that weight is not log-normal but mpg visually <strong>looks like log-normal</strong>.</p><p>Let’s check for normality using quantile-quantile plots. Below is the quantile-quantile plots on original data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69588b46befac2bae264eb79894ab560/href">https://medium.com/media/69588b46befac2bae264eb79894ab560/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*3MZJXB0LjTf88x-5XDg5rg.png" /></figure><p>So, both histplot &amp; qqplot of acceleration indicates that it is indeed close to gaussian.</p><h4>Statistical Normality Tests</h4><p>We will do hypothesis testing for the normality of numerical attributes using the shapiro wilk test.</p><p><strong><em>H_0</em></strong>: Data is drawn from normal distribution, alpha=0.05</p><p>Let’s define a function which test the null hypothesis for columns of the data-frame under significance level alpha.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b29c63fe719297f0189e8672dd3a8c43/href">https://medium.com/media/b29c63fe719297f0189e8672dd3a8c43/href</a></iframe><p>Oops, we expected acceleration to be normally distributed but are test rejected it. The p-value is 0.03, so we rejected it under the significance level of 5% but if it was 2.5% then we would have failed to reject the null-hypothesis. We won’t change the p-value now otherwise it will be <strong>p-hacking</strong>. One possible reason for the rejection of H_0 is maybe our data is not scaled and I think scaling it helps.</p><p>We will now apply power transform to <strong>make the data more gaussian like</strong>. And after that check for normality on the transformed data.</p><p><strong>Power Transform</strong>: It transforms data feature-wise to make it more Gaussian-like. Power transforms are a family of parametric, monotonic transformations that are applied to make data more Gaussian-like. This is useful for modeling issues related to heteroscedasticity (non-constant variance), or other situations where normality is desired just like here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73230ee669170603aefab2225a404fff/href">https://medium.com/media/73230ee669170603aefab2225a404fff/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*mV2_olJPcvllBM23pB21ng.png" /></figure><blockquote><strong>Note</strong>: on removing nans from the data-frame the power transformer is making the entire weight column 0. I am unable to find the reason for this and asked the sklearn community and update the notebook once I figured this out. If you detect the reason for that then please comment.</blockquote><p>For now we will leave weight.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/219ecbb6e09df42e7415b2c917752281/href">https://medium.com/media/219ecbb6e09df42e7415b2c917752281/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*-_i1wS2OE8acbGSMR5qCMA.png" /></figure><p>Power transforms does two things, first it scaled the data i.e., now data is centered at 0 and also made the distribution more gaussian-like simultaneously preserving the original structure. It does so by applying transformations like square-root, log etc.</p><p>acceleration is still gaussian, skewness is removed from mpg &amp; weight making mpg gaussian-like. Also the distribution for displacement is improved now it&#39;s bimodal which respects the observation.</p><blockquote>One thing you have noticed that after applying power transform distribution of mpg &amp; weight is quite similar to what we get on applying log transform. Infact the power transform of sklearn indeed applies log transforms, refer <a href="https://scikit-learn.org/stable/modules/preprocessing.html#preprocessing-transformer">this</a>.</blockquote><p>Let’s now check for normality using quantile-quantile plots. Below is the quantile-quantile plots on transformed data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cb30d54a362c4513f6d4f06920cf445/href">https://medium.com/media/1cb30d54a362c4513f6d4f06920cf445/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*RZmOOp-_6AmdtPLUZTLv1g.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae974a3a0d9f02a8845578cf85c7051d/href">https://medium.com/media/ae974a3a0d9f02a8845578cf85c7051d/href</a></iframe><p>Indeed on normalizing the data the likelihood of observing acceleration assuming it&#39;s normal is very high as compared to earlier.</p><blockquote>So, acceleration is normally distributed both visually and statistically.</blockquote><p>Un-normalized data can sometimes lead to some wrong insights also. For eg,</p><p>In <a href="https://medium.com/@greatsharma04/eda-for-beginners-using-python-4fcd2b57d1f7"><strong>Part1-EDA</strong></a> we plotted the relationship and from these plots it’s seems that although all the attributes have a monotonic relation with mpg but the relations are not seeming exactly linear.</p><figure><img alt="image.png" src="https://cdn-images-1.medium.com/proxy/1*CRUnfBQt6MukFYbA2Etv9w.png" /></figure><p>But in transformed data all relations are purely linear.</p><figure><img alt="image.png" src="https://cdn-images-1.medium.com/proxy/1*6u2SumeQryZpA35PGPoWOA.png" /></figure><p><strong>Note:</strong> Almost everyone is <strong>homoscedastic</strong> but acceleration is seeming bit more <strong>hetroscedastic</strong>.</p><h4>Tests for correlation between two continuous variables</h4><h4>Covariance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*MstIZHpSzND0snsDcdU1cQ.png" /></figure><p>The use of the mean in the calculation suggests the need for each data sample to have a Gaussian or Gaussian-like distribution hence its <strong>parametric statistic</strong>. Also it’s hard to interpret because it can take any value.</p><h4>Linear Association (Pearson’s Correlation)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*bmYYCH49IB8fXRNfXdiFMA.png" /></figure><p>The Pearson correlation coefficient is just a <strong>normalized covariance</strong> between the two variables to give an interpretable score such that,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*0psVZI_QucS1VmdWFE4M9g.png" /></figure><p>It can be used to summarize the strength of the linear relationship between two data samples. The use of mean and standard deviation in the calculation suggests the need for the two data samples to have a Gaussian or Gaussian-like distribution hence it’s a <strong>parametric statistic</strong>.</p><p>As a statistical hypothesis test, the method assumes that the samples are uncorrelated (fail to reject H_0).</p><p><strong>Assumptions of pearson correlation</strong>:<br> <strong>1.</strong> Both variables should have a Gaussian or Gaussian-like distribution.<br> <strong>2.</strong> Relationship between the variables should be linear.<br> <strong>3.</strong> Homoscedasticity i.e., a sequence of random variables where all its random variables have the same finite variance.</p><p>Also Pearson is quite sensitive to outliers.</p><p>Two variables may be related by a nonlinear relationship, such that the relationship is stronger or weaker across the distribution of the variables. In these cases, even when variables have a strong association, Pearson’s correlation would be low. Further, the two variables being considered may have a non-Gaussian distribution. To properly identify association between variables with non-linear relationships, we can use rank-based correlation approaches.</p><h4>Ordinal Association (Rank correlation)</h4><p>Rank correlation refers to methods that quantify the association between variables using the ordinal relationship between the values rather than the specific values. In this we first sort data in ascending order, then assign integer rank to them and then use it to find the correlation b/w variables. Because no distribution for the values is assumed, rank correlation methods are referred to as distribution-free correlation or non-parametric correlation.</p><p>Four types of rank correlation methods are as follows:</p><h4>1. Spearman’s Rank Correlation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*hzmCxWo46UdPIVsEKkr3Kg.png" /></figure><p>Spearman’s Correlation is a <strong>non-parametric rank correlation</strong> and is also interpretable because,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*buM7vPTU6ccaaXC3aMaYZQ.png" /></figure><p>In this instead of calculating the coefficient using covariance and standard deviations on the samples themselves, these statistics are calculated by converting the raw data into rank data hence non-parametric. <strong>This is a common approach used in non-parametric statistics.</strong></p><p>As a statistical hypothesis test, the method assumes that the samples are uncorrelated (fail to reject H_0).</p><h4>2. Kendall’s Rank Correlation</h4><p>The intuition for the test is that it calculates a normalized score for the number of matching or concordant rankings between the two samples. As such, the test is also referred to as Kendall’s concordance test.</p><p>As a statistical hypothesis test, the method assumes that the samples are uncorrelated (fail to reject H_0).</p><h4>3. Goodman and Kruskal’s Rank Correlation</h4><h4>4. Somers’ Rank Correlation</h4><p><strong>Types of Correlation</strong>:<br> <strong>Positive:</strong> both variables change in the same direction.<br> <strong>Neutral:</strong> no relationship in the change of the variables.<br> <strong>Negative:</strong> variables change in opposite directions.</p><p>The statistical test only tells the likelihood of an effect. It doesn’t tell us the size of the effect. The results of an experiment could be significant, but the effect so small that it has little consequence or the result could be insignificant, but the effect is large.</p><p><strong>Effect size:</strong> It is the size or magnitude of an effect or result as it would be expected to occur in a population. Unlike <strong>significance tests</strong> which just tells how likely is the effect, <strong>effect size</strong> actually tells the value of the effect occurred. So it gives us more power.</p><p><strong>We will find the effect test for the relation of </strong><strong>mpg with other numerical features</strong>. i.e., we will be getting an absolute value instead of likelihood which quantify how much correlation is there b/w mpg and other numerical features.</p><p>But all the above association tests not only gives the effect size but also the p-value. So can look at both the values. We will be using spearman but you can use any other accept pearson because all numerical variables doesn&#39;t satisfies the pearson&#39;s assumptions.</p><p>So for all correlation test b/w mpg and other attribute our null hypothesis will be,</p><p><strong><em>H_0</em></strong>: mpg and other attribute are not correlated, alpha=0.05</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fbaf062ba866751a243514d039a426c/href">https://medium.com/media/4fbaf062ba866751a243514d039a426c/href</a></iframe><blockquote>So all the H_0 are rejected under the significance level of 5%. Accept `acceleration` all the other correlations are very high and this is also evident from our previous plots.</blockquote><p>We now create a data-frame for the correlation b/w every pair.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/083a1fce3b80dbe099eb1e916861bb6d/href">https://medium.com/media/083a1fce3b80dbe099eb1e916861bb6d/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*tkU3ZomwSs1KItCrykVk4w.png" /></figure><blockquote>Correlation of pairs (mpg, acceleration), (displacement, acceleration) and (weight, acceleration) is moderate whereas remaining all pairs has very high correlation between them.</blockquote><p>We will now test whether two samples has the same mean or not. For this we have two types of significance tests for two different conditions.</p><h4>Parametric Statistical Significance Tests</h4><ol><li><strong>Student’s t-test</strong> — It tests whether the two independent normal distributed samples has the same mean or not.</li><li><strong>Analysis of Variance Test (ANOVA)</strong> — It tests whether the two or more independent normal distributed samples has the same mean or not.</li></ol><blockquote>ANOVA is same as t-test but for more than 2 variables. So either we can apply t-test pair-wise of apply ANOVA once. Also ANOVA only tells whether all samples are same or not, it doesn’t quantify which samples differ or by how much.</blockquote><h4>Non-Parametric Statistical Significance Tests</h4><ol><li><strong>Mann-Whitney U Test</strong> — Non-parametric equivalent of Student’s t-test.</li><li><strong>Kruskal-Wallis H</strong> — Non-parametric equivalent of ANOVA (it’s for median).</li></ol><p>We will apply appropriate test depending on the sample, i.e., if samples are normally distributed then parametric tests otherwise non-parametric tests.</p><p>Let’s test whether acceleration in japan and usa has the same mean. First we check whether acceleration of both japan and usa are normally distributed or not and then apply the applicable tests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07daf9dee35d5ea743f0864e23e36e41/href">https://medium.com/media/07daf9dee35d5ea743f0864e23e36e41/href</a></iframe><pre>So both are normally distributed so we can apply parametric test.</pre><p><strong><em>H_0</em></strong>: <em>acceleration of japan</em> and <em>acceleration of usa</em> has same sample mean, alpha=0.05</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e3b17fb3140e6db2cdf824c8e6f4de9/href">https://medium.com/media/9e3b17fb3140e6db2cdf824c8e6f4de9/href</a></iframe><p>because the variance is not same for the two distributions hence equal_var=False</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2fa643092955a5a83be25dee4abc339/href">https://medium.com/media/c2fa643092955a5a83be25dee4abc339/href</a></iframe><p>Let’s test whether horsepower across all the regions has the same distribution or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11fc58eadca070d442001d2402329e13/href">https://medium.com/media/11fc58eadca070d442001d2402329e13/href</a></iframe><blockquote>So all of them are not normally distributed so we will apply non-parametric test.</blockquote><p><strong><em>H_0</em></strong>: Sample distributions are equal for horsepower across region, alpha=0.05</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d325e1baf688364549fd0eba5233f98/href">https://medium.com/media/4d325e1baf688364549fd0eba5233f98/href</a></iframe><p>Test whether acceleration has same distribution for samples with mpg_level high &amp; medium.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8497fad365ecebfb1d64fcddf7ca33c7/href">https://medium.com/media/8497fad365ecebfb1d64fcddf7ca33c7/href</a></iframe><p>Test for mpg distribution across the years.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f98cb4235855ed7a73b4da5170f2b69/href">https://medium.com/media/1f98cb4235855ed7a73b4da5170f2b69/href</a></iframe><h4>Relation between Categorical and Continuous attributes</h4><p>We will use feature_selection api of sklearn for this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0f9ecc6de32655223ce797a2d47bfeb/href">https://medium.com/media/b0f9ecc6de32655223ce797a2d47bfeb/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*a-QcIbCYAXPH-7i24nrQyA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6445f658d8b62ef082300b177488b27e/href">https://medium.com/media/6445f658d8b62ef082300b177488b27e/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*l4iqS25iGHyRG-keitstVg.png" /></figure><p>So we are done for now. We did some good statistical analysis and also explored various statistical tests provided to us by scipy and scikit-learn. We did a lot and can extend it further but you get the idea.</p><p>The next part is <a href="https://github.com/greatsharma/MPG/tree/master/Modelling"><strong>predictive modelling</strong></a><strong> </strong>which is mostly about machine learning. As machine learning itself is a big thing so it’s tough to incorporate it in a single blog. You can refer to my <a href="https://github.com/greatsharma/MPG/tree/master/Modelling"><strong>this</strong></a><strong> </strong>repository, it’s the continuation of this series and includes <strong>feature_engineering</strong>, <strong>cross validation</strong>, <strong>losses</strong>, <strong>metrics</strong>, <strong>testing different pipelines</strong>, <strong>hyper-parameter tuning</strong> and <strong>auto-ml </strong>as well. There is a lot to learn in that repository.</p><blockquote>You can get the <strong>entire documented jupyter notebook</strong> for this blog from <a href="https://www.kaggle.com/gauravsharma99/statistical-analysis-on-mpg-data">here</a>, you just need to fork it. Also if you like the notebook then <strong>up-vote</strong>, it motivates me for creating further quality content.</blockquote><p><strong>If you like this story then do clap for it and also share with others.</strong></p><p>Also, have a read of my other stories which includes variety of topics including,</p><ul><li><a href="https://medium.com/analytics-vidhya/effect-of-multicollinearity-on-linear-regression-1cf7cfc5e8eb"><strong>Effect of Multi-collinearity on Linear Regression</strong>,</a> you will surely learn the nitty-gritty details of multi-collinearity and linear regression.</li><li><a href="https://medium.com/@greatsharma04/facial-emotion-recognition-fer-using-keras-763df7946a64"><strong>Facial emotion recognition</strong></a> using keras.</li></ul><p>and<a href="https://medium.com/@greatsharma04"> many more</a>.</p><h4>References</h4><p>The following material has been used as source and guidance-</p><ul><li>Data source: <a href="https://archive.ics.uci.edu/ml/datasets/auto+mpg">https://archive.ics.uci.edu/ml/datasets/auto+mpg</a></li><li>Statistical Methods for ML by Jason Brownlee. Most of the definitions are taken from this awesome book.</li><li><a href="https://cyfar.org/what-data-analysis">https://cyfar.org/what-data-analysis</a></li></ul><p><strong>Thank-you once again for reading my stories my friends :)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e83f10ca3c82" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/statistical-analysis-using-python-e83f10ca3c82">Statistical Analysis using Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EDA for beginners using Python]]></title>
            <link>https://medium.com/analytics-vidhya/eda-for-beginners-using-python-4fcd2b57d1f7?source=rss-40c34d041b23------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fcd2b57d1f7</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[seaborn]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Gaurav Sharma]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 09:32:15 GMT</pubDate>
            <atom:updated>2020-09-23T15:13:55.754Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploratory Data Analysis(EDA)</h3><p>This is a <strong>3 part series</strong> in which I will walk through a data-set, analyzing it and then at the end do predictive modelling. I recommend to follow the parts in sequential order but you can jump to any part.</p><p><strong>Part 1, Exploratory Data Analysis(EDA):</strong><br> This part consists of summary statistics of data but the major focus will be on EDA where we extract meaning/information from data using plots and report important insights about data. This part is more about <strong>data analysis</strong> and <strong>business intelligence(BI)</strong>.</p><p><a href="https://medium.com/@greatsharma04/statistical-analysis-using-python-e83f10ca3c82"><strong>Part 2, Statistical Analysis</strong></a><strong>:</strong><br> In this part we will do many statistical hypothesis testing, apply estimation statistics and interpret the results we get. We will also validate this with the findings from part one. We will apply both parametric and non-parametric tests. We will report all the important insights we get in this part. This part is all about <strong>data science</strong> and requires some statistical background if possible.</p><p><a href="https://github.com/greatsharma/MPG/tree/master/Modelling"><strong>Part 3, Predictive Modelling:</strong></a><br> In this part we will predict a response using given predictors. This part is all about <strong>machine learning</strong>.</p><h4>Meta-Data, Data about Data</h4><p>I am using the <a href="https://archive.ics.uci.edu/ml/datasets/auto+mpg">auto mpg</a> data for EDA taken from the <a href="https://archive.ics.uci.edu/ml/index.php">UCI repository</a>.</p><p><strong>Title:</strong> Auto-Mpg Data<br><strong>Number of Instances:</strong> 398<br><strong>Number of Attributes:</strong> 9 including the class attribute<br><strong>Attribute Information:</strong></p><pre>1. mpg — continuous<br>2. cylinders — multi-valued discrete<br>3. displacement — continuous<br>4. horsepower — continuous<br>5. weight — continuous<br>6. acceleration — continuous<br>7. model year — multi-valued discrete<br>8. origin — multi-valued discrete<br>9. car name — string (unique for each instance)</pre><p>This data is not complex and is good for analysis as it has a nice blend of both categorical and numerical attributes.</p><p>This is <strong>part 1</strong> i.e., EDA. I won’t stretch this part too long and do following things in sequential manner.</p><ol><li><strong>Some Pre-processing of the data</strong>, this includes dealing with missing values, duplicate data if any and then aligning the data.</li><li><strong>EDA on categorical attributes</strong>, this includes analyzing their distributions and relations with other cat.(categorical) attributes.</li><li><strong>EDA on numerical attributes</strong>, this includes analyzing their distributions and relations with other num.(continuous/numerical) attributes.</li><li>Then we will analyze the <strong>relation b/w numerical &amp; categorical attributes</strong>.</li></ol><p>I will use <strong>seaborn</strong> heavily throughout the notebook, so it is also a good go to notebook for those who are looking for EDA using seaborn.</p><p>Firstly, import all necessary libraries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6da9d57c52891ac18fa46e5f76b3c1d8/href">https://medium.com/media/6da9d57c52891ac18fa46e5f76b3c1d8/href</a></iframe><p>We will first import the data into a pandas data-frame and inspect it’s properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddf488d398e62a879a3079633143860e/href">https://medium.com/media/ddf488d398e62a879a3079633143860e/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*hgaOYnV0K34DT_sEXTUSsg.png" /></figure><p>The data is in rectangular(tabular) form, with 398 entries, each having 9 distinct attributes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7ca34dca8651c14e01b4d73819ffd55/href">https://medium.com/media/a7ca34dca8651c14e01b4d73819ffd55/href</a></iframe><p>To inspect meta-data (i.e., data about data), we can use an inbuilt pandas function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6241e4b7b04760437f18e9d4c628e5a/href">https://medium.com/media/e6241e4b7b04760437f18e9d4c628e5a/href</a></iframe><p>df.info() , describes many things about the data, like data type of each column, memory usage etc.</p><p>Now, I will make two distinct list for categorical and numerical column names as the analysis differ for both the types. For that I will introspect the datatype of each column and if it is of type object then it&#39;s categorical, else numerical.</p><p>I will use these two lists heavily throughout the analysis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27d4a2cc4d4e06bec98e4225ca388bfd/href">https://medium.com/media/27d4a2cc4d4e06bec98e4225ca388bfd/href</a></iframe><p>Let’s see how many unique values are there in each column.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8281fbd89565acfd2946e432ab07e81/href">https://medium.com/media/c8281fbd89565acfd2946e432ab07e81/href</a></iframe><p>As there are very few unique values for cylinders and model_year, so it’s safe to make them categorical instead numeric. This conversion will be helpful during analysis as I will be bifurcating some attributes on the basis of other.</p><p>So, lists need to be updated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bf6243227b5b02e7ade9753049f4f6e/href">https://medium.com/media/0bf6243227b5b02e7ade9753049f4f6e/href</a></iframe><p>Now, inspect for nans in the data. I will check for nans column-wise.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edf0c044c31d1417f2661671f42da91c/href">https://medium.com/media/edf0c044c31d1417f2661671f42da91c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2370429440f7b4267277222e81c6a81b/href">https://medium.com/media/2370429440f7b4267277222e81c6a81b/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*moy0ZkhZ6DOodkcbagrDGA.png" /></figure><p>The nan-row proportion in the data is 6 / len(df) = 0.01507. So, horsepower consists all 6 nan rows, comprising of around 1.5% of data. As this fraction is very low so it’s safe to drop the nan rows for now.</p><blockquote><strong>Note:</strong> If the nan proportion is large (more than 5%) then we won’t drop it but instead impute missing values or can even treat missing as another attribute.</blockquote><p>For now remove all nan rows as they are just 1.5%.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/803fa743665cee5b8500123487b9d0ad/href">https://medium.com/media/803fa743665cee5b8500123487b9d0ad/href</a></iframe><p>Let’s see how many duplicate entries are there and drop them if there are any.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37568f8dff53d1da8cf38ad768ba7cf8/href">https://medium.com/media/37568f8dff53d1da8cf38ad768ba7cf8/href</a></iframe><p>So, there are no duplicate rows.</p><p>Before we move ahead it’s a good practice to group all variables together having the same type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bad3997d1ff1a56b3a88e59a4c1f87b/href">https://medium.com/media/3bad3997d1ff1a56b3a88e59a4c1f87b/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*xlQPUhuvfRFJzl6OnlHBvg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6177f1f610f2abc8bb4775709a3966a8/href">https://medium.com/media/6177f1f610f2abc8bb4775709a3966a8/href</a></iframe><p>Now we are all good to go for some in-depth analysis.</p><h4>Analysis on Categorical Attributes</h4><p>The analysis includes both descriptive stats and EDA.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a312b592069957e091d2878adea33b56/href">https://medium.com/media/a312b592069957e091d2878adea33b56/href</a></iframe><p>I will first slice out the categorical columns from original data-frame and then do analysis on it, keeping the original data untouched. At the end I will incorporate needed changes in the original data-frame.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/004106e11fbb98200ccf5084e14b21c7/href">https://medium.com/media/004106e11fbb98200ccf5084e14b21c7/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*TNszMRhceuWQhHAGZCvNNg.png" /></figure><p>As origin and name consists of text data so it needs some pre-processing. We will remove all extra spaces from each string, otherwise the same string with different spacing will be treated as different categories which should not be the case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eef2446d06ef48d643f1fd45d97eff34/href">https://medium.com/media/eef2446d06ef48d643f1fd45d97eff34/href</a></iframe><p>I will create an artificial categorical attribute named mpg_level which categorizes mpg into low, medium and high. This is done for two reasons, first it will help a lot in EDA i.e., I can bifurcate plots on the basis of mpg and secondly this is easy to understand as compared to numbers.</p><p>I am dividing mpg into three regions as,</p><blockquote>[min, 17) -&gt; low<br> [17, 29) -&gt; medium<br> [29, max) -&gt; high</blockquote><p>Also the choice of the range is analytical and can be anything till it seems to be reasonable.</p><blockquote><strong>Note:</strong> This is feature-engineering and mostly done in predictive modelling but it makes sense to introduce it here.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d45373a01764331456af6d10ce343fe/href">https://medium.com/media/9d45373a01764331456af6d10ce343fe/href</a></iframe><p>Let’s inspect the unique characters in origin, cylinders and model_year. I am leaving name because it is almost unique for each entry in this case, hence nothing interesting to inspect it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d937b64b967cb906a08671540f266c50/href">https://medium.com/media/d937b64b967cb906a08671540f266c50/href</a></iframe><p>Although descriptive stats for categorical attributes are not much informatic but still it’s worth looking once. Also pandas describe function is only for numeric data and in df_cat cylinders and model_year are the only numeric type.</p><pre>df_cat.describe()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*2v7X_rf2Y_kDMNAx0qa5nQ.png" /></figure><p>It seems that most of the values in cylinders are 4 and (min, max) is (3, 8).</p><h4>Analysis of Distribution</h4><p>Now we analyze the distribution for each categorical attribute and make some insights from the plots.</p><p>In case of categorical variables an ideal (or atleast loved) distribution is uniform or uniform-like, below is an uniform distribution.</p><figure><img alt="image.png" src="https://cdn-images-1.medium.com/proxy/1*dI5g7o62EVqOf7ChXOARfA.png" /></figure><p>Let’s plot the distribution for different categorical attributes in our data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cdcca1d263d3db1536b005ca002b3f9/href">https://medium.com/media/2cdcca1d263d3db1536b005ca002b3f9/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*BkEKPhJHVBC2v37uIpCElQ.png" /></figure><p>Let’s calculate the proportion of dominant classes in each category.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baa909728901a424b32a1c8e9ef4ceef/href">https://medium.com/media/baa909728901a424b32a1c8e9ef4ceef/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e1b3e2ac9dcbdd7e38e7c31da353caf/href">https://medium.com/media/4e1b3e2ac9dcbdd7e38e7c31da353caf/href</a></iframe><h4>Insights</h4><ul><li>origin is highly imbalanced, usa alone consists of 62.5% of data whereas japan &amp; europe are having similar proportion. We will see this dominance in future analysis. We will try to find the reason for this in our further analysis.</li><li>cylinders is highly imbalanced, 4 alone consists of 50.77% of data. Whereas 8 &amp; 6 are nearly in same proportion but 3 &amp; 5 collectively accounts for only 7 entries i.e., 1.8% of entire data. We will see this huge proportional imbalance in cylinders in future analysis.</li><li>mpg_level is highly imbalanced, medium alone consists of 52.3% of data while low &amp; high are in the same proportion. This dominance is due the fact of our thresholding while manufacturing this feature because the medium range is broader hence it consists of more data points. It won&#39;t be there in original mpg feature as it is continuous.</li><li>model_year is considerably balanced which is good.</li></ul><p><em>Now we analyze </em><em>car&#39;s name.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d5e10bbde43af5d87e3124b74423d05/href">https://medium.com/media/3d5e10bbde43af5d87e3124b74423d05/href</a></iframe><p>Firstly, even though name is categorical but it has a lot categories and this even makes sense because product names generally varies a lot in any domain. So it’s not fruitful to do analysis on car names as these are names just like product id and seems to hold no important insights.</p><p>But one thing to be noticed here is that each car name starts with a company name, so maybe the case that there are very few companies in the data-set and it will be fruitful to extract them as separate feature and do analysis on that. So let’s do it.</p><p>I will create a new attribute named as car_company by extracting the first word from all names. I will also remove the car company from each car name because it is not needed now, and also rename column name to car_name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ecd3c208e1f1519006b3566048d6aaa/href">https://medium.com/media/2ecd3c208e1f1519006b3566048d6aaa/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*BU4uKgkrvSQq2zEjMSOMdQ.png" /></figure><p><em>Now, check for total unique values in </em><em>car_company.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6985f3122885b92fe43dcd338a82110c/href">https://medium.com/media/6985f3122885b92fe43dcd338a82110c/href</a></iframe><p>Great this is what we wished and indeed we get. Our idea that there will be few car companies involved in this data is indeed correct. Because the number of categories are less we can now do analysis on that. So we took a step in right direction just by our in-tuition.</p><p><em>Now, we analyze the distribution of </em><em>car_company.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/583fceafa29710914878832a5d2f00a3/href">https://medium.com/media/583fceafa29710914878832a5d2f00a3/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*RpfB44FjNcwMs_WMacrpQg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fa56a03451e0e2e7a8f3e569bf03263/href">https://medium.com/media/8fa56a03451e0e2e7a8f3e569bf03263/href</a></iframe><h4>Insights</h4><ul><li>We found that car_name has a lot categories, close to total data points. So it&#39;s not fruitful to do analysis on that as it is unique for most of the points and also in most cases names are safe to be avoided as they doesn&#39;t have correlations with other.</li><li>We then create an artificial attribute named car_company by extracting company names from car names. We find that there are much few car companies as compared to car names (around 8 times less).</li><li>We then found that the distribution of car_company is not uniform and most of the proportion is covered by top 15 car companies. Whereas ford and chevrolet alone comprises of around 23% (almost a quarter).</li></ul><h4>Conclusion</h4><ul><li>Every categorical attribute except model_year is highly imbalanced and far from uniform distribution. In all cases most of the data is comprised of top few categories.</li><li>Although model_year is not perfectly uniform but we can think it as uniform-like distribution. This is a digestible assumption for two reasons, first we can clearly see in plot that indeed the distribution is uniform-like and also this is not the entire population but a sample of it so may be in large run it will converge to uniform which may be the true population distribution (<strong>Law of Large Number</strong>).</li></ul><p>Now we will analyze how different features behaves on changing other features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e04d38601b9e8ba5e3fd93da609c237e/href">https://medium.com/media/e04d38601b9e8ba5e3fd93da609c237e/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*oYPIs1XWwfohW_dnwNwM-g.png" /></figure><h4>Insights</h4><p>We can clearly see the impact of imbalanced categories in our bifurcated plots.</p><p><strong>cylinders bifurcated by origin</strong></p><ul><li>Japan is the only origin with vehicles having 3 cylinders.</li><li>Europe is the only origin with vehicles having 5 cylinders.</li><li>USA is the only origin with vehicles having 8 cylinders.</li><li>All origins has 4 cylinder vehicles and in almost equal proportion, also because 4 is dominating in cylinders.</li><li>All origins has 6 cylinder vehicles but dominated by USA due the fact that it is dominating in origin.</li></ul><p><strong>mpg_level bifurcated by origin</strong></p><ul><li>Japan doesn’t have any vehicle with low mpg_level whereas europe has negligible vehicles with low mpg_level and almost all vehicles that has low mpg_level are from usa.</li><li>Japan has the most vehicles with high mpg_level.</li><li>USA has the most vehicles with medium mpg_level (again due to the fact that most vehicles belongs to USA).</li></ul><p><strong>mpg_level bifurcated by cylinders</strong></p><ul><li>Vehicles with low mpg_level has either 6 or 8 cylinders and most of them has 8 cylinders.</li><li>Almost all vehicles with high mpg_level has 4 cylinders and with very few (less than 5) has 5–6 cylinders.</li><li>Most vehicles with medium mpg_level has 4,6 &amp; 8 cylinders. This is due to the fact that most of the vehicles has these number of cylinders as we inspected in cylinder distribution earlier.</li></ul><p><em>Let’s analyze mpg_level with cylinders bifurcated by origin.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7354135353b280c08b8fe4a20a1dc9c2/href">https://medium.com/media/7354135353b280c08b8fe4a20a1dc9c2/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*pu8A6hYRG8D4W4PFrsNHDg.png" /></figure><h4>Insights</h4><ul><li>Japan doesn’t have any cylinder with low mpg_level and most of it’s vehicles have high mpg_level with mostly 4 cylinders(this we already inspected from earlier plots as well, nothing new).</li><li>Almost every vehicle in europe has 4 cylinders and most of them are medium or high.</li><li>USA has few vehicles with high mpg level as compared to other knowing the fact that most of the vehicles belongs to USA.</li></ul><p><strong>Note:</strong> Although these insights can be detected from earlier plots but it was bit hard and bifurcation helped us and we extracted even more meaning from data.</p><h4>Conclusion</h4><ul><li>Japan is leading in case of mpg level with most of it’s vehicles having high mpg_level. It has more than twice vehicles with high mpg compared to other origins.</li><li><strong>It seems like as number of cylinders increases mpg decreases in general.</strong></li></ul><p><em>Let’s analyze model_year,</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fb2b775f31922ccb5d5ee2492518cdb/href">https://medium.com/media/1fb2b775f31922ccb5d5ee2492518cdb/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*rrE47T1BKIBOb0cz-4GBxg.png" /></figure><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*DuZAB72uQ-x2BV_359qviA.png" /></figure><h4>Insights</h4><ul><li>As year progresses manufacturing of low mpg car decreases and eventually stopped after 79.</li><li>As year progresses manufacturing of high mpg car increases and infact after 79 their manufacturing was 1.5–2 times as compared to vehicles with medium mpg.</li><li>Throughout the years there is no significant change in manufacturing of vehicles with medium mpg and infact from 74–79 their manufacturing was more than the sum of remaining two.</li><li>From the scatter plot we can clearly see an upward linear trend i.e., as year progress mpg increases.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d2590c9a563bd9637aea2bd94846aff/href">https://medium.com/media/3d2590c9a563bd9637aea2bd94846aff/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*pUA1fnSR1tzhQDY3hom_ww.png" /></figure><h4>Insights</h4><ul><li>As the year progresses vehicles with more cylinders (8 &amp; 6) decreases significantly.</li><li>As the year progresses vehicles with less cylinders increases.</li><li>One important thing to be noticed that throughout the years vehicles with 4 cylinders have significant proportion and infact in the 80’s most of the vehicles has 4 cylinders.</li><li>These results make sense because as year progresses technology advances vehicles with low mpg and more cylinders looses focus and vehicles with high mpg and less cylinders are the new stars.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e83b75405957f4863835af81a9c4a3d/href">https://medium.com/media/1e83b75405957f4863835af81a9c4a3d/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*2DW27KjIAb0V6pYGwd0I7A.png" /></figure><h4>Insights</h4><ul><li>In the starting year manufacturing in USA is dominated completely.</li><li>As the year progresses japan and europe started manufacturing more vehicles. Infact, in the year 80 both japan and europe manufactured more than USA. This may be due to something because throughout the years USA dominates and suddenly there is a considerable decrease in their manufacturing. This may have something to do in USA in year 80.</li><li>Initially europe manufactures more vehicle then japan but then japan exceeds it after 76.</li></ul><p><em>Let’s analyze car_company,</em></p><p>As car_company contains a lot categories and most of them has very low proportion so we will analyze only the top 15 car companies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19d6c21df830a4e5873c7f8de2e0bf10/href">https://medium.com/media/19d6c21df830a4e5873c7f8de2e0bf10/href</a></iframe><p>We can see that top 15 car companies alone manufactures 83% of vehicles.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5951cc670710b5ccf395c82451a0dc94/href">https://medium.com/media/5951cc670710b5ccf395c82451a0dc94/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*H1KtU9G2k12nM5TPh8SnHg.png" /></figure><h4>Insights</h4><ul><li>Top manufacturing companies have all mpg level vehicles but companies with less vehicles focuses more on high or medium mpg vehicle.</li><li>All top manufacturing companies are from usa and that is the reason why usa has most of the vehicles in data-set (this is one of our key findings). We now answered this question asked earlier by us.</li><li>All top manufacturing companies focuses on vehicles with cylinders 4, 6 &amp; 8 equally, but the companies with less manufacturing generally uses less cylinders in their vehicles.</li><li>We are done with the analysis of categorical attributes and found lots of interesting things and answered many unknown questions. Now we will incorporate the required changes of df_cat into df.</li></ul><p>Every attribute except car_name is of interest and participated in our analysis. So we will not add car_name to our data-frame as it is of no interest. This is feature reduction and is an integral part of feature engineering.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/271258a1e6b2250f69da3ee42f1b134c/href">https://medium.com/media/271258a1e6b2250f69da3ee42f1b134c/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*2Wav5F8x0RXzIp_-8a9LQQ.png" /></figure><p>Save these changes to a new file.</p><pre>df.to_csv(&quot;mpg_cated.csv&quot;, index=False)</pre><h4>Analysis on Numerical Attributes</h4><p>The analysis includes both descriptive stats and EDA.</p><pre>df = pd.read_csv(&quot;mpg_cated.csv&quot;)<br>df.head()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*2Wav5F8x0RXzIp_-8a9LQQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f4ad2170bacccf29da63a51160d0ce5/href">https://medium.com/media/5f4ad2170bacccf29da63a51160d0ce5/href</a></iframe><p>I will first slice out the numerical columns from original data-frame &amp; then do analysis on it keeping the original data untouched, and at the end incorporate needed changes in the original data-frame.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7f3fd33373dd96f9f933b6196a98dc4/href">https://medium.com/media/d7f3fd33373dd96f9f933b6196a98dc4/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*eoAoHAl12OLnABQcYuwCVg.png" /></figure><h4>Analysis of Distribution</h4><p>Now we analyze the distribution for each numerical attribute and make some insights from the plots.</p><p>In case of numerical variables an ideal (or atleast loved) distribution is gaussian or gaussian-like, for a gaussian it&#39;s various distribution plots look like below,</p><figure><img alt="image.png" src="https://cdn-images-1.medium.com/proxy/1*YwrFZ3FE7HkW0ahodjA18Q.png" /></figure><p>Let’s plot the distribution for different numerical attributes in our data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e49fc76704ad0603e503d4b5bca5b8ef/href">https://medium.com/media/e49fc76704ad0603e503d4b5bca5b8ef/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*t63QPNwYhnh9BKtZbe2slw.png" /></figure><h4>Insights</h4><ul><li>acceleration is the only distribution which is gaussian. There are few values in acceleration which lie outside the whiskers(the bars extending outwards from the box), these are fliers/outliers.</li><li>distributions of mpg &amp; weight seems to be right-skewed gaussian.</li><li>distributions of displacement &amp; horsepower seems to be far from gaussian.</li></ul><p>Currently we are analyzing the distributions just from plots, in the next phase(statistical analysis) we will do hypothesis testing for the normality of these distributions.</p><p>Let’s analyze the outliers using tukey formula.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88766871ce886043e5f44d85b13f1a68/href">https://medium.com/media/88766871ce886043e5f44d85b13f1a68/href</a></iframe><p>acceleration and horsepower are the only attributes with tukey outliers and we can also notice this from the above boxplots as well.</p><pre>df.iloc[list(tukey_outliers(df_num.acceleration).index)]</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*eO67IjIMF0b4HxBlNuP3nA.png" /></figure><pre>df.iloc[list(tukey_outliers(df_num.horsepower).index)]</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*EO2roXr1wReJJ3lTS9e3RQ.png" /></figure><h4>Insights</h4><ul><li>Outliers in acceleration seems to be random nothing conclusive. One thing we can notice that none of them are from japan.</li><li>Outliers in horsepower are not seeming random, there is a lot common in them</li><li>All of them are from usa (maybe because vehicles from usa are in majority).</li><li>All of them has 8 cylinders.</li><li>All of them has low mpg level.</li><li>All of them has weight in the range 4000.</li><li>Most of them has displacement in range 400.</li><li>Most of them were manufactured in early years(before 74).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e78d402c172f4ba173c4666af1b38e5d/href">https://medium.com/media/e78d402c172f4ba173c4666af1b38e5d/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*BwQXMV0TAXRojBpj-NVxeQ.png" /></figure><p>See data is not scaled properly, we need to scale it for modelling but it works fine for analysis.</p><p><strong>Now we analyze relationship between different numerical attributes</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48002878415b67b42c9955ec5fd8dc41/href">https://medium.com/media/48002878415b67b42c9955ec5fd8dc41/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*yWhGvLnMSST1s7HU_8Q0xg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e2069b0a8a4c4079db3111389aefa84/href">https://medium.com/media/4e2069b0a8a4c4079db3111389aefa84/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*wwTsLunnLJgcBKBvFYv5Kw.png" /></figure><h4>Insights</h4><ul><li>as mpg increases displacement, horsepower &amp; weight decreases but acceleration increases.</li><li>as horsepower increases displacement &amp; weight increases but acceleration decreases.</li><li>as weight increases displacement increases but acceleration decreases.</li><li>as acceleration increases displacement decreases.</li></ul><blockquote>So all numerical attributes are related with each other.</blockquote><p>Now we bifurcate these relationships with different categories. In this plot we analyze the relationship of horsepower &amp; acceleration bifurcated by origin, mpg_level &amp; cylinders in a single plot.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/280c1d28a988469267018ab051d84e7a/href">https://medium.com/media/280c1d28a988469267018ab051d84e7a/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*inLUcZfSgngowPGG-4zS3Q.png" /></figure><h4>Insights</h4><ul><li>In every region there is a negative relation b/w horsepower &amp; acceleration.</li><li>vehicles with low mpg has low acceleration and high horsepower.</li><li>vehicles with more cylinders has low acceleration and high horsepower.</li></ul><p>In this plot we analyze the relationship of weight &amp; horsepower bifurcated by origin, mpg_level &amp; cylinders in a single plot.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59002e9a49c4081721566915e5f15bb0/href">https://medium.com/media/59002e9a49c4081721566915e5f15bb0/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*PAz_SUxlCAuCh6A73z2Tkg.png" /></figure><h4>Insights</h4><ul><li>In every region there is a positive relation b/w weight &amp; horsepower.</li><li>vehicles with low mpg has high weight &amp; horsepower.</li><li>vehicles with more cylinders has high weight &amp; horsepower.</li><li>on bifurcating we didn’t found anything new.</li></ul><p><strong>Analysis of relationship between numerical and categorical attributes</strong></p><p><strong>Note:</strong> I am using boxen and violin plots for this but we can also use stripplot.</p><blockquote><em>Variation of numerical features with origin</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c208680c3f5fae7cf8d21b69726bc4ae/href">https://medium.com/media/c208680c3f5fae7cf8d21b69726bc4ae/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*5r_WwXAk-ktM_DpQ4g6UcA.png" /></figure><h4>Insights</h4><ul><li>vehicles of usa has less mpg on an average as compared to japan &amp; europe.</li><li>vehicles of usa has more displacement, horsepower and weight as compared to japan &amp; europe.</li><li>all vehicles has relatively same acceleration irrespective of the origin but distribution of acceleration from usa is more spreaded due to the fact that it comprises a lot vehicles compared to other.</li></ul><blockquote><em>Variation of numerical features with mpg_level</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/604f7dc3ff3238ced94f48123e4cb08e/href">https://medium.com/media/604f7dc3ff3238ced94f48123e4cb08e/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*jWDw8ZoLLsgQTsI7yHdNzw.png" /></figure><h4>Insights</h4><ul><li>as mpg_level increases displacement decreases on average.</li><li>as mpg_level increases horsepower decreases on average.</li><li>as mpg_level increases weight decreases on average.</li><li>vehicles with low mpg_level usually has less acceleration compared to other whereas vehicles with medium and high mpg_level has same acceleration.</li></ul><blockquote><em>Variation of numerical features with cylinders</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93b00d06bb359fbfe65c9cd787126de4/href">https://medium.com/media/93b00d06bb359fbfe65c9cd787126de4/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*R_YQ1xyGOF_Xz63pWlfuCQ.png" /></figure><h4>Insights</h4><ul><li>as cylinders increases from 3 to 4 mpg also increases but on further increasing the cylinders mpg starts decreasing.</li><li>displacement increases in polynomial order as cylinders increases.</li><li>as cylinders increases from 3 to 5 horsepower decreases but on further increasing the cylinders it starts increasing.</li><li>on increasing cylinders vehicle’s weight increases on average (very obvious).</li><li>as cylinders increases from 3 to 5 vehicle’s acceleration also increases but on further increasing the cylinders it starts decreasing(maybe due to the fact that vehicles with more cylinders have more weight and hence less acceleration).</li></ul><blockquote><em>Variation of numerical features with model_year</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd9cdf8fbad89bc01841362f4b5ec83d/href">https://medium.com/media/fd9cdf8fbad89bc01841362f4b5ec83d/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*UuuXgd_geryp89knfTkJwg.png" /></figure><blockquote><em>Variation of numerical features with model_year bifurcated by origin.</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af44d5f4d9aa24263687babe51edcb93/href">https://medium.com/media/af44d5f4d9aa24263687babe51edcb93/href</a></iframe><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*dyZ2SafWCij9aL-APKrC_A.png" /></figure><h4>Insights</h4><ul><li>as year progresses there is an increase in mpg across all origins(this we already observed in analysis on categorical data).</li><li>as year progresses there is a slight decrease in displacement, horsepower &amp; weight of the vehicles belonging to usa but there is no significant change in japan &amp; europe.One thing we can observe is that in the 80&#39;s all vehicles have similar displacement because unlike the 70&#39;s the distribution is not spread out (i.e., distribution is <strong>short fatty</strong> instead of <strong>tall skiny</strong>).</li><li>throughout the years acceleration remains relatively the same across all regions.</li></ul><p>So we are done for now. We did some good amount of EDA and also explored various plotting features provided to us by seaborn. I highly recommend you all to use seaborn because it’s easy and simple. Also you can use plotly to construct all the graphs in this notebook. Plotly plots are not only visually awesome but are also interactive and due to this they take much more memory specially scatter plots (as they need to store every data-point information to enable interactivity). That’s why I didn’t included any plotly plots.</p><blockquote>You can get the <strong>entire documented jupyter notebook</strong> for this blog from <a href="https://www.kaggle.com/gauravsharma99/eda-on-mpg-data/">here</a>, you just need to fork it. Also if you like the notebook then <strong>up-vote</strong>, it motivates me for creating further quality content.</blockquote><p><strong>If you like this story then do clap for it and also share with others.</strong></p><p>In the next part we will do some <a href="https://medium.com/@greatsharma04/statistical-analysis-using-python-e83f10ca3c82"><strong>Statistical Analysis</strong></a>.</p><p>Thank-you for reading m</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fcd2b57d1f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/eda-for-beginners-using-python-4fcd2b57d1f7">EDA for beginners using Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>