<?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 Thapa on Medium]]></title>
        <description><![CDATA[Stories by Gaurav Thapa on Medium]]></description>
        <link>https://medium.com/@gauravalley62?source=rss-11f796e1c93b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*eVU0k7V7BxrxlO4dmdu74A.jpeg</url>
            <title>Stories by Gaurav Thapa on Medium</title>
            <link>https://medium.com/@gauravalley62?source=rss-11f796e1c93b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:47:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gauravalley62/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[The Three Regressions]]></title>
            <link>https://medium.com/analytics-vidhya/the-three-regressions-e4c159afc157?source=rss-11f796e1c93b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4c159afc157</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Gaurav Thapa]]></dc:creator>
            <pubDate>Mon, 23 Nov 2020 18:33:55 GMT</pubDate>
            <atom:updated>2020-11-24T16:26:25.681Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring the math behind multiple, ridge and lasso regression</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E3F_GxM2QrMOLrQ0" /><figcaption>Photo by <a href="https://unsplash.com/@sctgrhm?utm_source=medium&amp;utm_medium=referral">Scott Graham</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When I first started my journey with Data Science and Machine Learning, I was overwhelmed by the sheer amount of information that was available on the internet. Overtime I realized that the majority of information was just the same thing being presented in different ways; most of the things that I actually wanted to learn or dive deep into were pretty scarce, if at all present. Thus, to help anyone who has the same questions as I had before, I will try to present discussions on topics which are often encountered but have relatively less detailed information available.</p><p>Here, we shall discuss the detailed mathematical background of Linear, Multiple, Ridge and Lasso regressions. Before we start, we shall recall some important definitions and properties which will be important for the said derivations.</p><blockquote><strong>Some Definitions and Properties</strong></blockquote><p><strong>Random Variable (RV)</strong></p><p>Let us consider a random experiment <em>E</em> and let <em>S </em>be its corresponding sample space. A random variable can be defined as a function that assigns a real number <em>X(s) </em>to every element<em> s</em> of <em>S </em>i.e. it assigns a value to every outcome of the experiment <em>E</em>.</p><p><strong>Discrete Random</strong></p><p>If a RV <em>X </em>can take either a finite or countably infinite number of values, then <em>X </em>is said to be a discrete RV.</p><p><strong>Probability Mass Function (pmf)</strong></p><p>If <em>X</em> is a discrete RV that takes the values <em>x1</em>, <em>x2</em>, <em>x3</em>, …, such that <em>P(X=xi)=pi</em>, where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*2HPQRH8jfq8Bus9aVay23w.png" /></figure><p>then <em>pi </em>is called the probability mass function.</p><p><strong>Continuous RV</strong></p><p>If a RV <em>X</em> can take all the values in an interval, then <em>X</em> is said to be a continuous RV.</p><p><strong>Probability Density Function (pdf)</strong></p><p>If <em>X</em> is a continuous RV and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*yUzG2CyQB0ifh2S9qMK44w.png" /></figure><p>then <em>f(x)</em> is called the probability density function.</p><p><strong>Mathematical Expectation or Arithmetic Mean</strong></p><p>If <em>X</em> is discrete RV with pmf <em>P(X=xi)=pi, i=1, 2, 3,…</em>; the mathematical expectation or the arithmetic mean of <em>X</em> is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*zQ5pUsaSl-eI4Ror1o3OVw.png" /></figure><p>If <em>X</em> is a continuous RV with pdf <em>f(x)</em>, then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*SJmkwkNlMKvg3x0aF-lu6Q.png" /></figure><p><strong>Moments</strong></p><p>Let <em>X</em> be a RV. The <em>r</em>-th order non-central moment about any value ‘<em>a</em>’ is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*z14dicW7lEvOVjgHw1q-SQ.png" /></figure><p>Such moments are called central moments.</p><p><strong>Variance</strong></p><p>The second order central moment is called the variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*T92C7JkiA3j5PzJPhh9qpw.png" /></figure><p><strong>Property of Variance:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*CMEZp-UBLrTLHpa5OAJKxg.png" /></figure><p>Proof: We know that,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*PDlwgS1cOE0o3-AhORoc_w.png" /></figure><p><strong>Standard</strong> <strong>Deviation</strong></p><p>The positive square root of variance is called the standard deviation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*Bq_Lz2iju5A8He5V7WDlwg.png" /></figure><p><strong>Normal Distribution</strong></p><p>A continuous RV <em>X </em>is said to follow a normal distribution with parameters <em>mu </em>and <em>sigma </em>if its pdf is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*JbghJLC1MMov-Ac2a2GTfg.png" /></figure><p>It can be symbolically denoted as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*jrIR8uFmnFwQzWsaNwx_zA.png" /></figure><p><strong>L1 and L2 norm</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*SlJB_XzQw55plXBsGOXPxA.png" /></figure><p>Let us consider an <em>n</em>-dimensional Euclidean space. Any vector <em>x </em>belonging to this space is in the form <em>x=(x1, x2,…, xn)</em>. Here, the length of <em>x </em>is measured as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*Trd3RRVXiwms7oMhptbqzQ.png" /></figure><p>This is called the Euclidean norm or the L2 norm.</p><p>The L1 norm is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*gf45rSaRTVZwrP2N78kRQw.png" /></figure><p>The distance derived using this norm is called the Manhattan distance.</p><p><strong>Singular Matrix</strong></p><p>An <em>n*n</em> square matrix <em>X </em>is said to be non-singular if <em>det(X)</em> is not 0 and singular if <em>det(X)=0</em>.</p><p><strong>Transpose of a matrix</strong></p><p>Let <em>X </em>be an <em>m*n</em> matrix. Then, the <em>n*m</em> matrix obtained by interchanging the rows and columns of <em>X </em>is called the transpose of <em>X</em>, denoted by <em>X^T</em>.</p><p><strong>Transpose Properties</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*8dRDoy6591r37drSFfv-QQ.png" /></figure><p><strong>Linear Dependence and Independence</strong></p><p>A set of vectors is said to be linearly dependent if at least one of the vectors can be represented as a linear combination of the others i.e. if one of them lies in the span of the others. If not, then it is said to be linearly independent.</p><p><strong>Rank of a Matrix</strong></p><p>The rank of a matrix is the maximum number of linearly independent column vectors in the matrix.</p><p><strong>Collinearity and Super-collinearity</strong></p><p>If some of the independent predictor variables in the data are highly linearly related, then we can say that the data has collinearity. When we have two or more independent variables which are perfectly linearly dependent, then the data possesses super-collinearity.</p><p><strong>Method of Lagrange Multiplier</strong></p><p>The method of Lagrange multipliers is used to find the local maxima and minima of a function subject to equality constraints. The method consists of reformulation of the given problem resulting in the creation of a function called the Lagrangian function which is then solved to find the stationary points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*LJg8xb-MmUmwtygiyqcrTg.png" /></figure><blockquote><strong>Correlation Coefficient</strong></blockquote><p>Let <em>X</em> and <em>Y</em> be two RVs corresponding to a random experiment. Let the experiment be repeated <em>n</em> number of times so that we end up with pairs of values <em>(x1, y1)</em>, <em>(x2, y2)</em>,…, <em>(xn, yn)</em>, which are plotted on a graph paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*zd-cuqqdib-S9f-bkH-gxw.png" /></figure><blockquote><strong>Equation of the Simple Regression Line</strong></blockquote><p>In the graph that we had obtained while deriving the correlation coefficient, let us suppose that <em>Y</em> is dependent on <em>X</em>. Let the equation of the regression line be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*gJmxgj8puB-jTITi9cK_sw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*-_14yOG8TwopHWOpIxC5bA.png" /></figure><blockquote><strong>Error in Estimate of Y</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*uHDlpAz3ImhjKikixCF2hQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*DTcwwB7Xj6GWBWkd476ofQ.png" /></figure><blockquote><strong>Multiple Regression</strong></blockquote><p>Let us consider <em>n</em> number of samples with each sample having <em>p </em>characteristics, where <em>n&lt;p</em>. Here, the <em>n*p</em> dimensional data matrix <em>X </em>is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*P59VLbncpssM8GKW2AD4Fg.png" /></figure><p>Let Y be the response variable, where <em>Y=(Y1, …, Yn)^T</em>.</p><p>Using the linear regression form,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*xvmoz-iaQf9D01y8pl_Q7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*NDvHdxaR5KBLXCAqyZhhXQ.png" /></figure><blockquote><strong>Maximum Likelihood (ML) Estimators</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*--GlMqrypc4v1gw-A_R6cw.png" /></figure><p>Although the likelihood can be calculated by taking this product, we prefer to use the log-likelihood instead. Either way is acceptable since the concavity of the logarithmic function ensures that the maximization of the likelihood coincides with the maximization of the log-likelihood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*5qAX9QGD1dUgryuwscgK6Q.png" /></figure><p>Now, in order to get the value of <em>beta </em>that maximizes the log-likelihood, we shall first take the partial derivative of <strong>Eq. 15</strong> with respect to <em>beta</em>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*Ovxdgp5jU5kiWHRT406DIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*VJbvLXViIFCcxHF-K3Gm4g.png" /></figure><blockquote><strong>Properties of the ML Estimators</strong></blockquote><p>Here,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*VrfylRskETYwdXHCvowJew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*mDZScKnIdLKbA-QVQ6sGYQ.png" /></figure><blockquote><strong>Predictions</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*YOnWxkWgv2ba8irNXSGTOg.png" /></figure><blockquote><strong>Need for Regularization</strong></blockquote><p>Let <em>X </em>be an <em>n*p</em> high dimensional data matrix. So, <em>n&lt;p</em>.</p><p>Then, <em>rank(X)≤=n</em>.</p><p>Also, any subspace spanned by the columns of <em>X </em>has dimension<em>≤n</em>.</p><p>We know that <em>n&lt;p</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*j-Q8tC_pyBRjwRVV2nlXuA.png" /></figure><blockquote><strong>Ridge Regression</strong></blockquote><p>It is a type of regularized regression which is used when the data suffers from multi-collinearity. It can be formulated as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*iRbXNkOLSvRO-W-BkTqSjA.png" /></figure><blockquote><strong>Properties of Ridge Estimators</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*x1xIxSXndjJj3lrFe--9wQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*3gj_QKFyAP4NYTB5yP3rYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*bez2nJkg-z4FBSoCM_duKA.png" /></figure><blockquote><strong>Lasso Regression</strong></blockquote><p>We have seen that the parameter of the linear regression model in ridge regression are obtained by minimizing the term,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*xF24MLFXaI8Z7xt-gUkGrA.png" /></figure><p>Here, the term</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*k9grmUYSiB69kPLjUh23SA.png" /></figure><p>referred to as the ridge penalty, is a function whose choice is arbitrary. In other words, we can use a penalty of our choice in this term to be minimized. In lasso regression, the penalty is taken to be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*L_oOrkEs6r5oAeylw4LfvQ.png" /></figure><p>which is called the lasso penalty. Thus, the difference between the ridge and lasso penalty is their respective use of the L2 and L1 norm i.e. in ridge, the penalty term is taken as <em>lambda </em>times the sum of the squared differences while in lasso, the penalty is taken as <em>lambda </em>times the absolute values of the regression parameters.</p><p>Unlike ridge regression, the lasso regression problem has no closed form solution except when <em>X </em>is orthogonal.</p><p>Let us suppose that <em>X </em>is orthogonal. Then,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*-hafj2PyuefWr24WjiIzxw.png" /></figure><p>Now, the lasso regression can be formulated as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*SOzwoaVsQZUBb84ZVpVEIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*DIeHKlrk5Nf0OQ0FbD8tUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*I6nr64dDfitEZHfoCgbs2Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4c159afc157" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/the-three-regressions-e4c159afc157">The Three Regressions</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[Classifying Text Reviews of Amazon Products Using Naive Bayes]]></title>
            <link>https://medium.com/analytics-vidhya/classifying-text-reviews-of-amazon-products-using-naive-bayes-4a21c6fabaff?source=rss-11f796e1c93b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a21c6fabaff</guid>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Gaurav Thapa]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 10:58:29 GMT</pubDate>
            <atom:updated>2020-10-06T12:47:03.799Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1MmJ3y9WhLQlpFN0we3Og.jpeg" /></figure><p>As previously <a href="https://medium.com/analytics-vidhya/the-naivety-of-naive-bayes-72c2a1738f80">mentioned</a>, Naive Bayes is an excellent Machine Learning algorithm when it comes to text classification. Classifying text data generally includes a lot of pre-processing in the form of text mining, before it is suitable for building models. Text mining is the process of transforming raw, unstructured text data into a meaningful, structured form in order to extract valuable insights. Here, we shall construct a simple Naive Bayes model which will take text reviews of Amazon products and classify them as either “Positive” or “Negative”.</p><h4>The Initial Steps</h4><p>The Amazon Fine Reviews <a href="https://www.kaggle.com/snap/amazon-fine-food-reviews">dataset </a>used here has been taken from Kaggle. The original full dataset contains 35172 rows with 10 features, of which we just need the features representing the product <em>Score</em>, the review <em>Summary</em> and the full review <em>Text</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*uTRSjVDY6_0q37goDSnN-w.png" /><figcaption>Fig 1. A subset of the Amazon dataset with necessary features.</figcaption></figure><p>We shall first construct the <em>Response</em> variable from the <em>Score</em> feature by labeling the rows with <em>Score</em>&gt;3 as “Positive” and others as “Negative”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M7-MfOFhGsFPvInhohMrIQ.jpeg" /><figcaption>Fig 2. Barplots for the different review scores (top) and different responses (bottom).</figcaption></figure><p>Our aim is to build a model that can receive rows of text data and classify the corresponding <em>Response </em>as either “Positive” or “Negative”. The text data can be either the review <em>Summary </em>or the review <em>Text</em>. For a simple and efficient model, we shall consider the review <em>Summary</em>.</p><h4><strong>Corpus Creation and Cleaning</strong></h4><p>Before we reach the model building stage, the raw text data has to go through several steps in order to obtain a useful form. We start by creating a corpus from the review <em>Summary</em>, which is just a collection of the <em>Summary </em>text files. We transform all the letters of the corpus to lower case then start the cleaning process by getting rid of unnecessary numbers, punctuation, unnecessary words (known as stopwords which includes frequently used words like “I”, “or”, “and”, “the” and so on), taking just the roots of words (like single word for “go”, “goes”, “going”) and finally deleting all the unnecessary white spaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*-nwnrd4J0vE-ThtKum9jQg.png" /><figcaption>Fig 3. Creation and cleaning of the corpus.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8ryBUKKCw_Df5_GzXXw1Q.jpeg" /><figcaption>Fig 4. Texts in the corpus before (left) and after (right) the cleaning process.</figcaption></figure><p>After cleaning the corpus, the text files are left with just those words which, contrary to the words that we got rid of, may be useful in classification .</p><h4><strong>Document Term Matrix</strong></h4><p>Now with the cleaned corpus, we shall form a Document Term Matrix(DTM). A DTM is a matrix where each row corresponds to a text file in the corpus, the columns consist of all the terms found in the corpus and each (<em>i</em>, <em>j</em>)-th entry is the frequency of appearance of the <em>j</em>-th term in the <em>i</em>-th text file. Oftentimes a DTM resembles a sparse matrix, i.e. a matrix which has a very few number of non-zero values. Thus, we usually take a subset of the DTM by removing some sparse terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*4H6M8FWcR8WvUF4yGrREwQ.png" /><figcaption>Fig 5. Taking a subset of the DTM by removing sparse terms.</figcaption></figure><p>Here, we have set sparsity level at 0.99965 which means that we shall be removing terms for which at least 99.965% cells are zero. There is no particular rule for setting the sparsity value; different levels lead to different number of terms and therefore different values for accuracy.</p><h4>Visualization and Word Cloud</h4><p>We can make barplots showing the frequency of different words occurring in the text files. Here, we have first partitioned the text files according to their <em>Response </em>type and made the aforementioned barplots for each partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmzyY0xKPbparAUyZePQ3w.jpeg" /><figcaption>Fig 6. Barplots showing the frequency of words appearing in Positive (top) and Negative (bottom) responses.</figcaption></figure><p>Also when we are dealing with text files, we can make use of something called a word cloud for visualization. A word cloud is an image which displays the words occurring in our DTM as a cloud where the size of each word signifies its frequency. So, the above barplots can be represented in the form of the following word clouds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z6JAq0bqVeU22JOrhAqzIQ.jpeg" /><figcaption>Fig 7. Word clouds for the words occurring in Positive (left) and Negative (right) responses.</figcaption></figure><h4><em>Working of Naive Bayes</em></h4><p>Let us roughly see how Naive Bayes works in text classification. Suppose we have a review saying “great product” in our corpus and we want to classify its <em>Response</em>. Naive Bayes first calculates the probabilities of the “Positive” and “Negative” responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*wPI5YNGS43Q2ISFv_2aKYQ.png" /></figure><p>Next, it calculates the probabilities of getting the word ‘great’ in both a “Positive” and in a “Negative” review. It does the same for the word “product”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*tUBn-bD9KFiL-rkKWvlvhw.png" /></figure><p>The calculations done so far can be summarized in the form of a frequency table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*9QF0YHnUlCwFi0q5gi7e7g.png" /></figure><p>Now, the Naive Bayes classifier calculates scores which help indicate whether the review is “Positive” or “Negative”. For the “Positive” label, the score is calculated as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*JNBjuMp8DPL8DDleZN_Wtw.png" /></figure><p>Similarly, for the “Negative” label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*ybQc-3IeGHgXeU9cJco2_Q.png" /></figure><p>These two scores are respectively proportional to the probabilities of the review being a “Positive” one or a “Negative” one, given the fact that the review says “great product”. Since the score for the “Positive” label is greater, Naive Bayes classifies the review as “Positive”.</p><h4><em>Fitting an H2O Naive Bayes Model</em></h4><p>Since Naive Bayes works best when all the independent variables are categorical, we shall convert the frequency of each term into a factor variable with labels “Yes” if frequency is more than 0, and “No” if it is equal to 0. Then we split the data into train and test datasets in the ratio of 8:2. Using simple <em>prop.table()</em> function, we can check if the distribution of the <em>Response </em>labels in the two datasets are equal and also get a baseline accuracy. Since roughly 77% of the data has <em>Response </em>as “Positive” in both the datasets, so even if we label all the data as “Positive”, we are sure to get an accuracy of 77%(baseline).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*Ky8MC3BtAVBkNR7OUYSzBA.png" /><figcaption>Fig 8. Getting a baseline accuracy.</figcaption></figure><p>Now we proceed to make an H2O Naive Bayes model from the training data. To account for any term which is present in the training data but might be missing in the testing data, we take the value of the hyperparameter <em>laplace </em>equal to 1. This ensures that we do not get the probability of any term from the testing data which is not present in the training data as 0. The said model gives us results with accuracy of almost 83%, which is better than the baseline.</p><h4>Model Improvement: N-Gram Tokenizer</h4><p>So far we have only considered the occurrence of single words in the text files while determining the <em>Response </em>type<em>.</em> In the two barplots shown in Fig. 6, we can see many words appearing in both the Positive and Negative responses. Thus, it is difficult to clearly interpret the word-to-response association by merely looking at the single words.</p><p>Tokenization is the process of splitting the text into a list of tokens, which can be anything: individual characters, words or even sentences. What an n-gram tokenizer does is split each text file into sequences containing n consecutive words. Adjacent words offer more meaning to their association with the corresponding <em>Response </em>type and therefore might lead to better results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*MHORyWMLb7w19bhKIWblnQ.png" /><figcaption>Fig 9. Creating a DTM using a 2-gram tokenizer.</figcaption></figure><p>Just like the aforementioned Fig. 6, we can make barplots showing the frequency of different two-word combinations occurring in the text files according to their <em>Response </em>type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xcwLrdDEUMXkPGkAo0f7Cg.jpeg" /><figcaption>Fig 10. Barplots showing the frequency of two-word combinations appearing in Positive (top) and Negative (bottom) responses.</figcaption></figure><p>Now, we can just follow the same steps as before; the only difference being that instead of single words, we are now considering a two-word combination of consecutive words occurring in the text files in order to predict the <em>Response </em>label.</p><p>The full code is available <a href="https://github.com/gauravalley/Amazon-Review-Classification">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a21c6fabaff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/classifying-text-reviews-of-amazon-products-using-naive-bayes-4a21c6fabaff">Classifying Text Reviews of Amazon Products Using Naive Bayes</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[The Naivety of Naive Bayes]]></title>
            <link>https://medium.com/analytics-vidhya/the-naivety-of-naive-bayes-72c2a1738f80?source=rss-11f796e1c93b------2</link>
            <guid isPermaLink="false">https://medium.com/p/72c2a1738f80</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naive-bayes]]></category>
            <dc:creator><![CDATA[Gaurav Thapa]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 17:41:35 GMT</pubDate>
            <atom:updated>2020-06-20T16:21:47.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*EtPS18Bm20js8aC9h-K9ig.jpeg" /></figure><p>What the developers wanted to achieve through Machine Learning was to enable computers to have minds of their own and learn to make decisions by themselves. Such an objective, as we know by the current state of the field, requires complex algorithms running on advanced GPUs which would in turn require huge investments. In the early stages of development, the simplicity of the computer systems led to simple ML algorithms- Linear Regression, Logistic Regression and Naive Bayes Classifier, which were based on the principles of Probability and Statistics. Although many advancements have been made in the field, these algorithms have stood the test of time and are still used as staple algorithms for checking the efficiency of other ML algorithms.</p><p>Here, we shall talk about the Naive Bayes Classifier by first establishing a fundamental theorem in Probability and Statistics- the Bayes Theorem, and see how Naive Bayes differs from the Bayes Theorem i.e. the <em>‘Naive’</em> in Naive Bayes Classifier.</p><h4><strong>Some Basic Definitions and Properties</strong></h4><p>An experiment in which all the possible outcomes are known but the outcome of a particular performance of the experiment cannot be predicted, is said to be a random experiment. The set of all such possible outcomes of a random experiment is called its sample space, <em>S</em>. The probability of any event <em>E</em> is defined as the number of favorable outcomes divided by the total number of possible outcomes i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*SMK4r5oa1pfFO5c9VxUhXQ.png" /></figure><p>For any event <em>E</em>, the following properties hold:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*cQTR7uiHj3_Ax78bPSb2ew.png" /></figure><p>The union of two events <em>A </em>and <em>B </em>i.e. <em>AUB</em>, is the event that either <em>A </em>or <em>B </em>or both occur. Their intersection is the event that both of occur simultaneously. The conditional probability<em> P(A|B)</em> is the occurrence of <em>A </em>assuming that <em>B </em>has already happened.</p><p><strong>Prop 1</strong>. If <em>A </em>and <em>B </em>are any two events, then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*P1wh1IRVewX10AVs4UZ7hQ.png" /></figure><p>Two events <em>A</em> and <em>B</em> are said to be mutually exclusive if they cannot occur simultaneously. On the other hand, they are said to be independent if the occurrence of one does not depend on the occurrence or non-occurrence of the other.</p><p><strong>Prop 2.</strong> If <em>A</em> and <em>B</em> are two independent events, then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*iyKm_ogRzn4HtJ5-qv9PRg.png" /></figure><p><strong>Prop 3.</strong> If <em>A</em>, <em>B</em> and <em>C</em> are three events, then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*C57AMqcFaMMPsFuopneLhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*AOWWSUpMhzOhJS17IP9HCw.png" /></figure><p><strong>Prop 4.</strong> For any two events <em>A </em>and <em>B</em>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*D15ij4Q0QfPSFmqAri7K4Q.png" /></figure><h4>Total Probability Theorem</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*-gIC3S0JM7PDdRC2jBwEoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*thon08d-PnrA_2d3CSsQOg.png" /></figure><p><strong>Corollary 1.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*eCnFdRSZ8jIsP6X5V2VqHw.png" /></figure><h4>Bayes’ Theorem</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*zeYIrXyG87oqDbFJ82xK_A.png" /></figure><p><strong>Corollary 1.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*690OF_A7p2eHJ6ypujGyqA.png" /></figure><p><strong>Corollary 2.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*KqDaCS6S0CgKeJ5S5myY4w.png" /></figure><p>The simplicity of Bayes’ Theorem is accompanied by its vast use in the field of Probability and Statistics. In simple words, it calculates the posterior probability of an event based on its prior probability and those of the other conditions which might be related to it. Thus, for a given hypothesis <em>H</em> and data <em>D</em>, by Bayes’ Theorem,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*WdF7plYDJ86kkoxwyuoN-A.png" /></figure><p>, where <em>P</em>(hypothesis|data) is the posterior probability of <em>H</em> given that <em>D</em> has occurred and <em>P</em>(hypothesis) is its prior probability. Since <em>D</em> might be related to <em>H</em>, we also require the prior (i.e. <em>P</em>(data)) and the posterior (i.e. <em>P</em>(data|hypothesis) probabilities of <em>D</em>.</p><h4>Naive Bayes’ Classifier</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*0bC37zkFb5sTESjOukxXFQ.png" /></figure><p>Now, if we have a multi-class classification problem requiring crisp results such that each sample goes to exactly one class, then every sample is labelled with the class that gives the maximum value for the numerator, since the denominator is independent of the class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lxiz0JJP1e1_r2eZc7FRJw.png" /></figure><p>, which is the equation used by a Naive Bayes’ Classifier.</p><p>If instead of crisp multi-class classification, for each sample, we want to compare its probability of belonging to one class with its probabilities of belonging to other remaining classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*TEEnXfy7zqjk8XJhxq3GRQ.png" /></figure><p>So, we can see that the Naive Bayes’ Classifier adds a major assumption that the features are independent of each other, to the already established Bayes’ Theorem of Probability. This assumption is a very strong one since in most of the real world scenarios, the features are seen to be dependent on each other. This is particularly true when we are dealing with text data for classification such as creating spam filters. However the Naive Bayes’ Classifier does an excellent job even if the features are not independent and is considered to be a major ML algorithm for spam filters and other such text classifications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72c2a1738f80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/the-naivety-of-naive-bayes-72c2a1738f80">The Naivety of Naive Bayes</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[COVID-19 in India: A Data Study]]></title>
            <link>https://medium.com/analytics-vidhya/covid-19-in-india-a-data-study-8814f9a3dea9?source=rss-11f796e1c93b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8814f9a3dea9</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[india]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Gaurav Thapa]]></dc:creator>
            <pubDate>Sat, 23 May 2020 20:58:04 GMT</pubDate>
            <atom:updated>2020-05-24T16:51:30.084Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*lD9cfv2_-0_igo0LygzuGg.jpeg" /><figcaption>Image Source: Google</figcaption></figure><p>The ongoing COVID-19 pandemic caused by the SARS-CoV-2 has already infected about 5.2 million people and caused around 340k deaths worldwide. First reported back in December 2019 in Wuhan, China, it has spread to the rest of the world causing severe harm, particularly in most parts of Europe and the United States. India had reported it’s first case of COVID-19 on 30th of January, 2020. Since then, the government has taken major steps to contain the spread of SARS-CoV-2 including complete nationwide lockdown, increase in the number of tests, declaring COVID-19 zones for strict containment and so on. Here, we shall look at how India is performing against the rest of the world in order to contain the ongoing pandemic. Note that the data studied here is as latest as 22nd of May, 2020. The datasets used have been taken from Kaggle and are available <a href="https://github.com/gauravalley/COVID-19-In-India">here</a>, along with the code.</p><p><strong>COMPARISON WITH RESPECT TO THE NUMBER OF CONFIRMED CASES</strong></p><p>Here, we see that the number of cases in India is small compared to the other ten countries, but the curve is still increasing in an exponential manner while the curve for most of the other countries — like Germany, France, Italy and Iran; have started to flatten with time. This shows that the impact of COVID-19 has just started to peak in India while in most European countries, it has started to subside or at least has been controlled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K67TvpFqOiRtvueAbpXGlA.png" /></figure><p>This can further be seen when we compare the trend in India’s COVID-19 Confirmation numbers with those of the six countries with highest number of cases, measured across the last five days. We see that, as mentioned earlier, the number of cases in India is seen to be growing exponentially compared to countries like UK, Spain and Italy, signified by the steepness of the curve corresponding to India’s numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-t6t98FufBrDiQoAbRzd6Q.jpeg" /></figure><p>If we compare India’s per day COVID-19 Confirmation numbers with those of the same six countries, measured across the last five days, the same result follows. The number of per day cases in India is much higher compared to the three European Countries, while it is comparatively lower than US, Russia and Brazil.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KggHJF2SeP6LBoHq8exulQ.jpeg" /></figure><p><strong>COMPARISON WITH RESPECT TO THE NUMBER OF DEATHS</strong></p><p>Just like the confirmation numbers, the number of Deaths in India is comparatively low and its corresponding curve, although going upwards, appears much flatter than the others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwlJE11DPH9yT7J1LaeMfQ.png" /></figure><p>On comparing the Death Rate of these countries, we see that India has the lowest among them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T2ZHQnlv5G4vot1BSS6bCQ.png" /></figure><p>Next, we compare the trend in India’s Death numbers with those of the six countries with highest number of Deaths, measured across the last five days. We see that the line signifying India’s numbers appears flatter than the rest, but this trend is getting much closer to those of Italy, France and Spain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5fxzfyOugO673MuF1p80kw.jpeg" /></figure><p>This increasing closeness of India’s trend with the above mentioned three European countries can be understood when we compare India’s per day Death numbers with those belonging the same six countries. Here we see that the per day Deaths in India are beginning to get much closer to the those happening in Italy, France and Spain; having even surpassed them in some occasions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZjIVlwgLiiA_q7liqyxNCQ.jpeg" /></figure><p><strong>INDIA’S COVID-19 STATISTICS</strong></p><p>We see below that the curve representing the number of Confirmed cases is increasing exponentially with time, which is a big concern. Though the same pattern can be seen in the curve for Recovered cases which, coupled with the fact that the curve for Deaths is comparatively flatter, should be of some relief but the failure to contain the spread by flattening the Confirmed cases curve will only make situations worse with time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StmKDfv55mRAbiBubWXlfw.png" /></figure><p>Also, we see that India’s Death Rate is almost half of the Global Death Rate while both the Recovery Rates are almost identical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYkudBStDrPm2Ju1LYmObA.jpeg" /></figure><p><strong>INDIA’S STATE-WISE COVID-19 STATISTICS</strong></p><p>Now, we shall analyse the impact of SARS-CoV-2 in India at the State level. With the help of a barplot, we see that Maharashtra, Gujarat, Tamil Nadu and Delhi have reported the highest number of Confirmed cases. Maharashtra and Gujarat are also among the States with highest number of Deaths, along with Madhya Pradesh and West Bengal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gAMmr1Tsl0bq7H7s1EIiJg.png" /></figure><p>If we consider the ten States with the highest number of Confirmed cases, we see that most of the curves representing the State numbers have started to show exponential growth, which is an alarming sign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zc-0xtLzrkvBT6_opY7w3g.png" /></figure><p>We can also compare the different states with respect to their Death Rates and Recovery Rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9gZtVP6g8mWpY1HGHogMOg.jpeg" /></figure><p><strong>AGE GROUP AND GENDER ANALYSIS</strong></p><p>From the handful of information made available about the patients, we see that of all the Confirmed cases, majority of the people have ages between 20 and 39. People within the age group of 40–49 are next, followed by 50–59, 10–19 and so on. On doing the same thing for people who have been Deceased, we see that almost half of them were of ages ranging between 60–69 and 50–59.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTtXvVo01jAYr2YHiPEomw.jpeg" /></figure><p>Next, we have the gender distribution of the Confirmed cases taken from the available data and the same for people who have been Deceased.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SyAoBNkcC3yVzQgA1Wp9ig.jpeg" /></figure><p>At last, we have a State-wise gender breakdown of the Confirmed COVID-19 cases, again only considering the data made available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JqhlWTHlRX_OQUs4xDnqRg.png" /></figure><p><strong>TESTING NUMBERS IN INDIA</strong></p><p>First, we have the distribution of the outcomes from the COVID-19 tests performed in India. About 4.52% of the tests have come out to be positive. We then check the percentage of India’s population that has been tested so far which, surprisingly, is only about 0.22%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AV1rSwvYf-U0-dVWZjzXQA.jpeg" /></figure><p>On comparing India with other countries, we see that the testing numbers in India rank among the highest in the world. Only five countries have performed more tests than India.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gCNFBmMJy3F-FDXjb0VI0g.png" /></figure><p>We then have the Positive Rate of tests and the number of tests performed per 10,000 persons in each of these countries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0uZ_blcgWL6sWk4jgDsXCA.jpeg" /></figure><p>Although the number of tests in India is among the highest in the world, the huge population creates major issues. This can be seen when we compare the number of tests performed per one million of each of these countries’ population. We see that India has the lowest numbers compared to the other countries. This indicates that although the number of tests being done is comparatively high, this number is certainly not enough when we factor in the huge population.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TGjygc5MbHUU7NHYJ2Ouw.png" /></figure><p>To get a better idea of the impact of India’s huge population, we compare the percentage of the total population that has been tested in these countries. Needless to say that India ranks the lowest among them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7eTrWQiGZg_CQTzIdGXyA.png" /></figure><p><strong>STATE-WISE TESTING NUMBERS</strong></p><p>At first, we check the testing stats for the different States. We see that Tamil Nadu, Maharashtra, Andhra Pradesh, Rajasthan and Uttar Pradesh are among the States with highest number of tests performed in India.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EB9A0gnQgk4ZDdmaeAO-Yw.png" /></figure><p>We then compare the Positive Rate of the tests and the number of tests performed per 10,000 persons across the States.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5bf4QYbixCFL2b1BFa_2A.jpeg" /></figure><p>We’ve seen how the huge population of India proved to be a major factor when the number of tests were compared with the other countries. We shall see the same impact of population in the State level data as well. If we check the number of tests performed per one million of the population of each State, we see that the number of tests performed is very low.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*il2yC-2tVvwUug2I66FdIQ.png" /></figure><p>And if we check the percentage of population of each State that has been tested so far, the result is equally worrying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*--8YofsyyOhPDV12hVzpiQ.png" /></figure><p><strong>INSIGHTS ON THE DIFFERENT ZONES</strong></p><p>In the hopes to contain the spread of SARS-CoV-2, all the districts of India have been classified into one of the three zones- Green, Orange or Red, the classification being done according to several variables such as the number of Confirmed cases reported by these districts, the amount of testing done and the doubling rate of COVID-19 cases. This classification of zones has been declared as a dynamic process which would be studied and revised every week. We shall check the distribution of the three zones in the different States.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DBY4saEMIu0hTeHINZEoUQ.png" /></figure><p>The Red zones are the ones with very high number of Confirmed cases and high doubling rate. As a result, it is considered to be of high priority in terms of surveillance and is strictly contained with many restrictions in addition to the nationwide lockdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LtX9KS-DEVYZo6usfgtRXA.png" /></figure><p>Orange zones have lower number of cases and lower doubling rate than the Red zones. Hence, the additional restrictions are comparatively lower. But an Orange zone might step up to a Red zone or vise versa, relative to the aforementioned variables. The aim would be to contain the spread so that rather than stepping up, it steps a level down to become a Green zone. A zone is declared as Green if it has no new cases for at least 21 straight days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zm5vMzwfTkAuUyrfhPwwNA.png" /></figure><p><strong>MEDICAL FACILITIES IN INDIA</strong></p><p>We shall start by comparing the number of Hospitals and Hospital Beds across the different States. Uttar Pradesh has the most number of Hospitals while Tamil Nadu and Maharashtra have the highest number of Hospital Beds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RpOHg0pAWF5iFai6L30pg.jpeg" /></figure><p>Next, we shall take a look at the average number of Hospital Beds in each Hospital across the States. Except six, all of the other States have less than 30 beds per Hospital, which is not enough for this ongoing pandemic. The figures become more alarming when we try to see the number of Hospital beds per 10,000 persons. Almost all of the States have less than 7 beds for every group of 10,000 persons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zbxh95sjvrtwXJ4SMqBtYw.jpeg" /></figure><p>If we take the population of the States into account, then we have more woeful numbers. Here, we have the measure of the number of people per one Hospital Bed for each State. This is a very frightening statistic, since shows that the high population will only lead the medical department to crumble. The same thing can be observed when we calculate the number of beds per one million of the population of each State.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZIdD8AKkukJ5NxL-Luegfw.jpeg" /></figure><p>Finally, we see how the medical department is currently holding up by comparing the number of Hospital beds with the number of Active cases in each State and then in India as a whole. From the barplot, it looks like the State of Maharashtra might run out of beds soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-gMQkL3o2zQ0LYDpMElRw.jpeg" /></figure><p><strong>TESTING LABS IN INDIA</strong></p><p>On comparing the number of Testing Labs in each State, we see that the States with the highest number of Labs are among those with the highest number of Confirmed cases. This signifies that there has been a major spread of SARS-CoV-2 in the country and the only way to control it is by testing more and isolating the positive patients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmGL8VRzm4MByiBt5vauWg.png" /></figure><p>Then, we see the distribution of the different types of Testing Labs across the States. Finally, we compare the number of tests done per Testing Lab in each State.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tIsM67TDYZzkICcYhTwJtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJUpyIBT-n7zlVhEyWImaA.png" /></figure><p><strong>SIMPLE TIME SERIES FORECASTING</strong></p><p>Here, by using a simple ETS Time Series model, we predict the number of cases might increase in the next 15 days with respect to the data we have at hand. The model predicts that we are heading towards more than 1,75,000 cases in the next 15 days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lf29x_MU7F4beLgI071rUQ.png" /></figure><p><em>Note: The results can be updated for latest results by running the code with updated datasets for the </em><a href="https://www.kaggle.com/sudalairajkumar/novel-corona-virus-2019-dataset"><em>world</em></a><em>, </em><a href="https://www.kaggle.com/sudalairajkumar/covid19-in-india"><em>India</em></a><em>, </em><a href="https://www.kaggle.com/imdevskp/covid19-corona-virus-india-dataset"><em>State-wise</em></a><em> India and the </em><a href="https://github.com/owid/covid-19-data/tree/master/public/data/testing"><em>testing</em></a><em> numbers.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8814f9a3dea9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/covid-19-in-india-a-data-study-8814f9a3dea9">COVID-19 in India: A Data Study</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[Bagging v Boosting : The H2O Package]]></title>
            <link>https://medium.com/analytics-vidhya/bagging-v-boosting-the-h2o-package-e288b09ade7e?source=rss-11f796e1c93b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e288b09ade7e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <dc:creator><![CDATA[Gaurav Thapa]]></dc:creator>
            <pubDate>Mon, 30 Mar 2020 19:21:47 GMT</pubDate>
            <atom:updated>2020-03-31T12:56:24.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bagging v Boosting : Pulsar Star feat. The H2O Package</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*I2djqyl0xWK8WMrnEmb30A.png" /><figcaption>Image Source : Google</figcaption></figure><p>Before we dive deep into the complexities of Bagging and Boosting, we need to question the need of such complicated processes. <a href="https://medium.com/analytics-vidhya/a-comparison-of-some-basic-ml-algorithms-by-using-red-wine-quality-data-8318bd6e19e1">Earlier</a>, we’ve seen how the Decision Tree algorithm works and how easily it can be interpreted. Then why don’t we settle on that? Why do the extra work if the Decision Tree works just fine?</p><p><strong>The Bias-Variance Trade-Off</strong></p><p>While the Decision Tree algorithm is simple, highly intuitive and very easy to interpret; the fact that it is often susceptible to being overfit prevents it from being the ideal algorithm. By an overfit model, we mean a model which perfectly fits or predicts the training set, but fails to do so with any other data set. This property, namely the difference in the fits with varying data sets, is called variance. As a result, a Decision Tree model is unable to predict any other data set apart from the one it was trained on and thus it shows high variance. Also, since it predicts the training set properly, we can say that it has a low bias. By bias, we mean the difference in the predicted model values and the underlying true values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*yI_3sLiQir-Y2K6aBF-V8Q.png" /><figcaption>Image Source : Google</figcaption></figure><p>The main aspect of Machine Learning is to use an algorithm to build a model which balances the right amount of bias and variance, preferably low bias and low variance. Such a model would be able to predict the training set accurately and also perform well with any other data set, giving consistently good predictions. While having a low bias, Decision Tree models often have a high variance. Although there are a number of ways to decrease the variance: limiting the number of leaves, limiting the number of node levels, pruning and so on; combining them with the concepts of Bagging and Boosting are much better ways to get comparatively more accurate results.</p><p><strong>Bagging</strong></p><p>One way to decrease the high variance of Decision Tree models is to take a collection of them, where each Tree is constructed by bootstrapping a data set from the training set. By bootstrapping, we mean creating a new data set by randomly selecting samples from the training set with repetition allowed, until both the data sets are of the same size. A new sample is classified by running it down each of the Trees and giving it the category that got the majority number of votes. This process of averaging the result based on a collection of models created from bootstrapped data sets is called Bagging(B-Bootstrapped, Agg- Aggregate).</p><p>The decrease in variance comes as a direct consequence of the Central Limit Theorem which states that -</p><blockquote>“For a sequence of ‘<strong>n</strong><em>’</em> independent identically distributed random variables with mean ‘<strong>mu</strong>’ and variance ‘<strong>sigma-squared</strong>’, their sum, under certain general conditions, will follow a normal distribution with mean ‘<strong>n*mu</strong>’ and variance ‘<strong>n*sigma-squared</strong>’<em> </em>as ‘<strong>n</strong>’<strong> </strong>tends to ‘<strong>infinity</strong>’<em>.”</em></blockquote><p>This will imply that their average will have mean ‘<em>mu’</em> and variance ‘<em>sigma-squared/n’</em>. Thus by averaging the results from a collection of Decision Trees, we get a significantly lower variance.</p><p>Bootstrapping and aggregating is something that we’ve seen <a href="https://medium.com/analytics-vidhya/a-comparison-of-some-basic-ml-algorithms-by-using-red-wine-quality-data-8318bd6e19e1">earlier</a> in Random Forests. Random Forests are a special case of Bagging where, along with bootstrapping and aggregating, we have the additional condition that at each split, only a random subset of variables is used. Sometimes, it might happen that we have a very strong predictor among the variables. As a result, this variable will almost always end up being the root of every Tree. Thus, the Trees end up becoming highly correlated. By taking a subset of random variables at each split, we ensure that this does not happen and so we get a diverse collection of Decision Trees in the Forest. It should be noted that the Trees in the Forest are left unpruned so that each of them has a low bias. As a result, by using Random Forests, we end up with a model having low bias and low variance.</p><p><strong>Boosting</strong></p><p>Boosting is a method in which we create a sequence of weak learners-generally with high bias and low variance, such that every subsequent learner emphasizes on correcting the errors made by its predecessor, thereby reducing the bias of the model as a whole. Unlike Bagging, where the Trees can be constructed at any random order, Boosting requires the learners to be made sequentially since each learner is made by taking the preceding learner’s errors into account. Gradient Boosting Machine(GBM) is an example of a Boosting algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*04P78hwaLA0pgF1i_0Jlww.png" /><figcaption>Image Source : Google</figcaption></figure><p>It starts off with an initial guess <em>Fo(x)</em><strong> </strong>of the result by using a Loss Function<strong> </strong><em>L(y, F(x));</em> then considering <em>m = </em>1, calculates the pseudo-residuals from the samples in the data set using the gradient of the Loss Function. Then it proceeds to construct a Decision Tree (weak learner) <em>h1(x)</em><strong><em> </em></strong>based on these residuals and the output value ‘<em>gamma-1’</em> of each terminal node is calculated, again by using the Loss Function. It should be noted that, unlike their previous use, here the Trees are built to obtain a value for the residuals. Now, in order to avoid overfitting, the output value of the Tree is usually multiplied by a regularization parameter, called the Learning Rate, to get a scaled outcome. Learning Rate is a factor which shrinks the contribution that each Tree has on the final prediction. The initial guess <em>Fo(x)</em> and the scaled outcome of the Tree are summed up to get new predictions <em>F1(x)</em> for each of the samples. Thereafter, new residuals are again calculated using these new predictions <em>F1(x)</em> and the initial guess <em>Fo(x); </em>then increasing <em>m = 2</em>, a new Tree <em>h2(x)</em> is built on these new residuals to get the output values ‘<em>gamma-2’</em> which are again scaled by the Learning Rate. The initial guess <em>Fo(x)</em>, the scaled outcome of the first Tree and the scaled outcome of the second Tree are all summed up to get new predictions <em>F2(x)</em> for each of the samples. In this way, new Trees are continually added to the sequence until <em>m= a predefined M </em>or<em> </em>when<em> </em>additional Trees fail to improve the result.</p><p>It should be noted that at each step, the residuals become smaller than their previous values. Also, each prediction is better than the previous one. Even if they turn out to be worse than before, the fact that we keep on building subsequent Trees ensures that it will improve later on. This is the main aspect of GBM, <em>viz.</em></p><blockquote>taking lots of small steps in the right direction in order to get better and more accurate results.</blockquote><p><strong>The H2O package</strong></p><p>H2O is an open source platform that uses in-memory compression in order to handle large amounts of data. Along with the functions for GBM and Random Forest, the H2O package in R also has functions for other ML algorithms like Naive Bayes, SVM and so on. Due to its use of parallel processing, calculations are performed rigorously, making it much faster than other packages. Note that H2O requires Java JRE to be updated and properly installed.</p><p>Here, we shall use the <a href="https://www.kaggle.com/pavanraj159/predicting-a-pulsar-star">data set containing Pulsar Star candidates</a> from Kaggle’s data set repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*4qi1sfJ4V0BC3tzrk_I_tg.png" /></figure><p>Data cleaning like outlier treatment is done as <a href="https://medium.com/analytics-vidhya/a-comparison-of-some-basic-ml-algorithms-by-using-red-wine-quality-data-8318bd6e19e1">before</a>. After this, we check the distribution of the target classes via a barplot. We also draw a correlation matrix with the predictor variables and a distribution chart of the predictor variables with respect to the target classes. We then divide the data into train and test in the ratio of 8:2. One last but very important step is to check the distributions of the target classes in both the train and test data sets, to make sure that they are almost the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*fRv1k3P-AQqCz4t6RNVpng.png" /></figure><p>Next, we call the H2O package by using the<em> library()</em> function. We shall initialize H2O with <em>h2o.init(), </em>along with<em> </em>allocating about 50% RAM size for H2O(<em>max_mem_size</em>) and also by setting the suitable number of parallel processes(by setting <em>nthreads = -1, </em>this number will be automatically decided). <em>h20.removeAll() </em>clears the slate in case the H2O cluster was already running. We then assign our train and test data sets as objects to the H2O cluster using <em>as.h2o()</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*iP3Pvg6G5WA6YnDZwnMYYQ.png" /></figure><p><strong><em>Bagging</em></strong>: We start by making a simple Random Forest model using the <em>h2o.randomForest()</em> function. We check the different metrics of the model and the important variables, then do an initial prediction by this model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*1kp1ZoO_37d-HULnn7sOUA.png" /></figure><p>Next, we shall build another model but this time we shall tune the following hyper-parameters -</p><p><strong><em>(a)</em></strong><em>ntrees:</em> the number of Trees in the Forest; <strong><em>(b)</em></strong><em>mtries:</em> the number of random variables to be used at each split; <strong><em>(c)</em></strong><em>stopping_rounds</em>,<em> stopping_metric, stopping_tolerance:</em> stop making new trees if ‘<em>stopping_metric’</em> does not improve by (‘<em>stopping_tolerance’ </em>*100)% for ‘<em>stopping_rounds’ </em>consecutive scoring events; <strong><em>(d)</em></strong><em>balance_classes: True </em>for unbalanced data, as is the case here; <strong><em>(e)</em></strong><em>nfolds: </em>value of<em> k </em>for <em>k-</em>fold cross validation; <strong><em>(f)</em></strong><em>score_each_iteration: True </em>if we want to predict against train and validation for each Tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*QVBZZZLULWNmrEt8UkQM4g.png" /></figure><p>We see that tuning of hyper-parameters has led to better values for Recall and AUC, although Accuracy and Precision have decreased. But, since Recall and AUC are comparatively more significant than the others, the new model indeed does a better job at classifying whether a given star is a Pulsar star or not.</p><p><strong><em>Boosting</em></strong>: Just like before, we start by making a simple GBM model using the <em>h2o.gbm()</em> function. We check the different metrics of the model and the important variables, then do an initial prediction by this model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*qURCj-79bgqVXhzo0F1fjg.png" /></figure><p>Again, we shall build another model but this time we shall tune the following hyper-parameters -</p><p><strong><em>(a)</em></strong><em>ntrees:</em> the number of Trees in the Forest; <strong><em>(b)</em></strong><em>max_depth:</em> the maximum depth of each Tree; <strong><em>(c)</em></strong><em>learn_rate:</em> the learning rate to scale the output value obtained from each Tree<em>; </em><strong><em>(d)</em></strong><em>sample_rate: </em>row sampling rate per Tree<em>;</em><strong><em>(e)</em></strong><em>col_sample_rate: </em>column sampling rate per Tree<em>; </em><strong><em>(f)</em></strong><em>stopping_rounds</em>,<em> stopping_metric, stopping_tolerance:</em> stop making new trees if ‘<em>stopping_metric’</em> does not improve by (‘<em>stopping_tolerance’ </em>*100)% for ‘<em>stopping_rounds’ </em>consecutive scoring events; <strong><em>(g)</em></strong><em>balance_classes: True </em>for unbalanced data, as is the case here; <strong><em>(h)</em></strong><em>nfolds: </em>value of<em> k </em>for <em>k-</em>fold cross validation; <strong><em>(i)</em></strong><em>score_tree_iteration: </em>the model is scored after every <em>‘score_tree_interval’ </em>Trees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*nK2tWSVwiEncdo2U7s2Q4g.png" /></figure><p>Here, we see that the values for Accuracy, Recall and AUC have all increased by tuning the hyper-parameters, although Precision shows a small decrease. Additionally, if we compare the modified Random Forest model with the modified GBM model, we see that the latter has better values for all of the four metrics. Thus, in this case, Boosting does a much better job of predicting if a given star is Pulsar or not.</p><p>It is to be noted that though Bagging and Boosting provide much better results than Decision Trees, they are much harder to interpret. Also, both of these methods contain a ton of hyper-parameters, so the run time required to tune them in order to get the appropriate model can be very high. Thus, Bagging and Boosting are computationally very expensive methods.</p><p>The full code is available <a href="https://github.com/gauravalley/Pulsar-Star-Prediction">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e288b09ade7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/bagging-v-boosting-the-h2o-package-e288b09ade7e">Bagging v Boosting : The H2O Package</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[A Comparison of Some Basic ML Algorithms by Using Red Wine Quality Data.]]></title>
            <link>https://medium.com/analytics-vidhya/a-comparison-of-some-basic-ml-algorithms-by-using-red-wine-quality-data-8318bd6e19e1?source=rss-11f796e1c93b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8318bd6e19e1</guid>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[r-programming]]></category>
            <dc:creator><![CDATA[Gaurav Thapa]]></dc:creator>
            <pubDate>Tue, 03 Mar 2020 18:08:50 GMT</pubDate>
            <atom:updated>2020-03-13T04:20:49.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QvEU-rYfAv1VLcna0WA3Hw.jpeg" /></figure><p>What’s fascinating about Machine Learning algorithms is how they have evolved with time. From the simple concepts of Linear and Logistic Regression, we have come a long way to using such complicated methods like XGBoost. Somewhere in the middle of these two extremes, we had other important techniques which kept on evolving steadily to eventually lead us to the complex ones we have today. Most notable among them are the <em>k</em>-Nearest Neighbors, Decision Tree and Random Forest. Here, we shall see how each of these three algorithms work as we try to categorize a collection of red wine as having ‘Good’ or ‘Bad’ quality from a dataset containing a number of attributes.</p><p><strong>Getting the Red Wine Data Ready</strong></p><p>We start by importing the <a href="https://www.kaggle.com/uciml/red-wine-quality-cortez-et-al-2009">red wine quality data</a> obtained from Kaggle’s dataset repository. Looking at the data, we see that the red wine quality has been described by numbers ranging from 3 to 8. So, we re-label the data by assigning the red wines with <em>quality </em>&gt; 6 as having ‘Good’ quality and those with <em>quality </em>≤ 6 as having ‘Bad’ quality. Then, since it is the target variable, we set the <em>quality </em>variable as a factor variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*_sLbMz9Q4ZtjI8XTNf3qDg.png" /></figure><p>We now construct a simple user-defined function and us this UDF, along with boxplots, to check for outliers. We identify all the values outside the range of <em>(mean-(3 * SD), mean+(3*SD))</em> as outliers and cap them by with these limits. We also create a matrix to see the correlation between the different attributes of the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*zm73IIIG0DQS3qvGudGCjQ.png" /></figure><p>Now we simply compare the Good and Bad quality red wines in terms of the different attributes with the help of density plots and see how much the mean values of these two categories differ in each case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*E7pXbs_kb9vA8dcayy0shg.png" /></figure><p>Finally, we separate our dataset into training and testing sets in the ratio of 8:2. We then go on to build our models on the training set and see how good these models are by checking how correctly they work with our testing set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*7a0J92Inhxl-kzn3ws9NQQ.png" /></figure><p><strong><em>k</em>-Nearest Neighbors</strong></p><p><em>k</em>-Nearest Neighbors or simply <em>k</em>NN, is a simple, supervised ML algorithm. It is the data equivalent of the ‘<em>herd mentality</em>’ since each new point is classified based on its nearest <em>k </em>neighbors. The training set is first clustered and when a new point is added, then based on the Euclidean distance, the nearest <em>k </em>points are considered. The new point is then categorized into a particular cluster according to the categorization of these nearest <em>k </em>points. If the new point lies between two or more clusters, then it is categorized to the cluster that gets the most number of votes.</p><p>The only tricky aspect of <em>k</em>NN algorithm is getting the appropriate value for <em>k</em>. As the value of <em>k </em>increases, the boundary becomes smooth but there’s also a chance that a cluster with only a few points is always outvoted by other clusters and thus result in an underfit model. On the other hand, low values of <em>k </em>can lead to overfitting since it becomes sensitive to outliers.</p><p>In order to get the best value for <em>k</em>, we consider a small part of the training set as ‘unknown’ and running it through the <em>k</em>NN algorithm to see how accurate it is. We then go a few values higher and lower, before settling for an appropriate one.</p><p>Now, with the training set we have obtained, we first make a simple <em>k</em>NN model by using the <em>train()</em> function in the <em>caret</em> package(can also be made using the <em>class </em>package). Note that <em>k</em>NN requires the data to be normalised before constructing the model. We do this by adding the <em>preProcess </em>as <em>center </em>and <em>scale</em>. Next we plot the model to get an initial value for <em>k</em>. Then we predict the outcome of the testing set using this model and check its confusion matrix to get a measure of its Accuracy and Recall. We also construct an ROC graph in order to get its AUC value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*pt38lEVosu3C_NKp6w3TZQ.png" /></figure><p>Now, we shall create a modified <em>k</em>NN model by tuning the parameters. First, we tell the <em>train()</em> function to create the new model using 10-fold cross-validation by using an additional <em>trainControl()</em> function. We also introduce a grid so that an appropriate value for <em>k</em> can be taken from it. By doing so, we expect for a better value of <em>k</em>, thus improving the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*_c95ReoHeMaSrY97eAH71w.png" /></figure><p>We observe that the new modified <em>k</em>NN model has a comparatively high Accuracy and AUC value than the initial <em>k</em>NN model, although the Recall remains the same for both models. Additionally, we can see that the modified <em>k</em>NN model is more precise(61.91%) than the initial one(48.15%). Thus, overall, tuning of parameters led to better results.</p><p><strong>Decision Tree</strong></p><p>Decision Tree is an intuitive algorithm which performs classification based on the preceding conditions being True or False. Just like their physical counterparts, Decision Trees have a root: the topmost condition with only outgoing arrows; internal nodes or simply nodes: the conditions with arrows on both sides; and terminal nodes or leaves: the conditions with no outgoing arrows. Thus, Decision Trees are analogous to physical trees flipped vertically.</p><p>We start building the Decision Tree by selecting the most appropriate attribute as the root. For this, we first make small Decision Trees comprising only of a root and two leaves, also known as stumps, for each attribute. Then we measure the impurity of each of these stumps using Gini index and the attribute corresponding to the stump with the lowest Gini index is chosen as the root. The nodes are then separated in the same way with the remaining attributes, provided the Gini index after separation is lower than what it was initially, failing which, the node is declared as a leaf.</p><p>While being super intuitive and very easy to interpret, Decision Trees generally suffer with the problem of high variance i.e. overfitting. This can be dealt by many techniques: maintaining a threshold for the minimum amount of observations before allowing splitting of a node, limiting the number of levels for the Decision Trees, limiting the number of leaves in a Decision Tree and so on.</p><p>There is also the concept of pruning the Decision Trees. Pruning is done in order to make the Decision Trees much simpler and more easy to interpret by getting rid of some of its leaves using the Complexity Penalty and Tree Score. Thus, in the long run, it serves as a method to make the Decision Trees less overfit.</p><p>With our training data, we first create a simple Decision Tree model using the <em>rpart()</em> function from the package of the same name(can also be made using the <em>C50 </em>and <em>party</em> packages) and plot the Decision Tree that we created. We then make a quick prediction using this model on the testing set and check the confusion matrix and ROC curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*gknyLmOzdGfZHrSQhsebsA.png" /></figure><p>We observe that this Decision Tree is already doing a better job at classification than the modified <em>k</em>NN model. Now we build a modified tree by tuning the parameters : introducing 10-fold cross-validation, setting the least number of observations before splitting a node along with the number of observations in each leaf node and limiting the maximum number of node levels of the tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*VL3BpXttz0SYw566-Db5Cg.png" /></figure><p>Here, we see that this modified Decision Tree is much more complex than the initial one. In order to make this tree simpler, we prune it by using the Complexity Parameter which gives the least value for <em>xerror </em>and make our predictions using this pruned tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*-QzqPzUKbCRtaYwm4VBhbg.png" /></figure><p>Just like with the <em>k</em>NN model, we see that tuning of parameters has led to better results. Also, the modified Decision Tree model does a much better job at classifying the testing set than the modified <em>k</em>NN model, proving that Decision Trees are better classifiers than <em>k</em>NN models.</p><p><strong>Random Forest</strong></p><p>As the name suggests, Random Forests consist of a collection of Decision Trees. However, the process of creating the Decision Trees is quite different. First a bootstrapped dataset of the same size as the initial dataset is created by randomly selecting samples, with repetition allowed. Then a Decision Tree is built from this bootstrapped dataset, with an added condition that at each step only a limited number of randomly selected attributes is used. The whole process is again repeated multiple times: a new bootstrapped dataset is created along with its corresponding Decision Tree using only a random subset of attributes at each step. In this way, we create multiple Decision Trees from multiple corresponding bootstrapped datasets, thus making a Random Forest.</p><p>Classification of any new data is done by running it down all of the Decision Trees in the Random Forest and giving it the category that gets the majority number of votes. There is also something known as an Out-of-Bag Error, which gives us an idea of how good the Random Forest is. It is the proportion of Out-of-Bag samples i.e. samples from the initial dataset left out during bootstrapping, that were incorrectly classified by the Random Forest. It is calculated by running each Out-of-Bag sample down those Decision Trees whose corresponding bootstrapped datasets did not contain that particular Out-of-Bag sample and checking if it is correctly classified.</p><p>It should be noted that the accuracy of a Random Forest increases with the increase in the number of Decision Trees but after sometime, it becomes constant. Although Random Forests solve the problem of overfitting by creating a variety of Decision Trees, they are comparatively less intuitive than Decision Trees. Also, they take a long time to be created and are much harder to interpret.</p><p>We take our training dataset and make a simple Random Forest model using the same <em>train()</em> function that we had used for <em>k</em>NN modelling(can also be made using the <em>randomForest </em>and <em>H2O </em>packages). We tell the <em>train()</em> function to perform a 10-fold cross-validation and set the metric as Accuracy since the target variables has two levels. The resultant confusion matrix and ROC curve give us the initial values for Accuracy, Recall and AUC. We also list down the variables on the basis of their importance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*danCgC-Dw0ItNZ9UA3AzJw.png" /></figure><p>Next, we construct another Random Forest model by tuning the parameters. We start by finding out the best value for <em>mtry</em> i.e. the most appropriate number of randomly selected attributes to be used at each step for splitting. We do this by making a grid of all the possible <em>mtry</em> values and making a model which uses this grid to get the best <em>mtry</em> value. We then use this <em>mtry </em>value and proceed to get the best <em>ntree </em>value i.e. the most appropriate number of Decision Trees in our model. For this, we create a loop to get multiple Random Forest models based on multiple values of <em>ntree </em>and select the <em>ntree </em>value whose corresponding model gives the maximum accuracy along with a good Kappa value. Finally, we create our modified Random Forest model with these tuned parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*tXqWkrD6FohljNEmbOBepA.png" /></figure><p>We see that, just like before, the modified Random Forest model did better job at classification than the initial one. Additionally, the results were significantly better than what we got with the <em>k</em>NN and Decision Tree models, showing that classification by Random Forest algorithm is more accurate than with the other two algorithms.</p><p>The full code used is available <a href="https://github.com/gauravalley/Red-Wine-Quality">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8318bd6e19e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/a-comparison-of-some-basic-ml-algorithms-by-using-red-wine-quality-data-8318bd6e19e1">A Comparison of Some Basic ML Algorithms by Using Red Wine Quality Data.</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>