<?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 Vardaan Bajaj on Medium]]></title>
        <description><![CDATA[Stories by Vardaan Bajaj on Medium]]></description>
        <link>https://medium.com/@vardaanbajaj?source=rss-168771086803------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dqlnNbi6iZd9fMFWEIkYPw.jpeg</url>
            <title>Stories by Vardaan Bajaj on Medium</title>
            <link>https://medium.com/@vardaanbajaj?source=rss-168771086803------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 14:34:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vardaanbajaj/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[Unsupervised Learning For Anomaly Detection]]></title>
            <link>https://medium.com/data-science/unsupervised-learning-for-anomaly-detection-44c55a96b8c1?source=rss-168771086803------2</link>
            <guid isPermaLink="false">https://medium.com/p/44c55a96b8c1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[kaggle]]></category>
            <dc:creator><![CDATA[Vardaan Bajaj]]></dc:creator>
            <pubDate>Sat, 08 Aug 2020 16:00:08 GMT</pubDate>
            <atom:updated>2020-08-09T17:52:28.191Z</atom:updated>
            <content:encoded><![CDATA[<h3>Contents</h3><p>In this post, we’ll be going through:</p><ol><li>The Need for Anomaly Detection</li><li>Baseline Algorithm for Anomaly Detection with underlying Mathematics</li><li>Evaluating an Anomaly Detection Algorithm</li><li>Extending Baseline Algorithm for a Multivariate Gaussian Distribution and the use of Mahalanobis Distance</li><li>Detection of Fraudulent Transactions on a Credit Card Dataset available on Kaggle</li></ol><p>In the <a href="https://towardsdatascience.com/deep-dive-into-principal-component-analysis-fc64347c4d20">previous</a> post, we had an in-depth look at Principal Component Analysis (PCA) and the problem it tries to solve. To consolidate our concepts, we also visualized the results of PCA on the MNIST digit dataset on Kaggle. In each post so far, we discussed either a supervised learning algorithm or an unsupervised learning algorithm but in this post, we’ll be discussing Anomaly Detection algorithms, which can be solved using both, supervised and unsupervised learning methods. Here though, we’ll discuss how unsupervised learning is used to solve this problem and also understand why anomaly detection using unsupervised learning is beneficial in most cases.</p><h3>Anomaly Detection</h3><p>Anomaly is a synonym for the word ‘outlier’. Anomaly detection (or outlier detection) is the identification of rare items, events or observations which raise suspicions by differing significantly from the majority of the data. Anomalous activities can be linked to some kind of problems or rare events such as bank fraud, medical problems, structural defects, malfunctioning equipment etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*X1DCyUYWFHIEMlyTgvgRaQ.png" /><figcaption>Example of an Anomalous Activity</figcaption></figure><h3>The Need for Anomaly Detection</h3><p>According to a research by <a href="https://www.domo.com/">Domo</a> published in June 2018, over 2.5 quintillion bytes of data were created every single day, and it was estimated that by 2020, close to 1.7MB of data would be created every second for every person on earth. And in times of CoViD-19, when the world economy has been stabilized by online businesses and online education systems, the number of users using the internet have increased with increased online activity and consequently, it’s safe to assume that data generated per person has increased manifold. In simple words, the digital footprint for a person as well as for an organization has sky-rocketed. The servers are flooded with user activity and this poses a huge challenge for all businesses. Fraudulent activities in banking systems, fake ids and spammers on social media and DDoS attacks on small businesses have the potential to collapse the respective organizations and this can only be prevented if there are ways to detect such malicious (anomalous) activity. Since there are tonnes of ways to induce a particular cyber-attack, it is very difficult to have information about all these attacks beforehand in a dataset. But, since the majority of the user activity online is normal, we can capture almost all the ways which indicate normal behaviour. And from the inclusion-exclusion principle, if an activity under scrutiny does not give indications of normal activity, we can predict with high confidence that the given activity is anomalous.</p><p>Let us understand the above with an analogy. In the world of human diseases, normal activity can be compared with diseases such as malaria, dengue, swine-flu, etc. for which we have a cure. SarS-CoV-2 (CoViD-19), on the other hand, is an anomaly that has crept into our world of diseases, which has characteristics of a normal disease with the exception of delayed symptoms. Had the SarS-CoV-2 <strong>anomaly</strong> been <strong>detected</strong> in its very early stage, its spread could have been contained significantly and we wouldn’t have been facing a pandemic today. Since SarS-CoV-2 is an entirely new anomaly that has never been seen before, even a supervised learning procedure to detect this as an anomaly would have failed since a supervised learning model just learns patterns from the features and labels in the given dataset whereas by providing normal data of pre-existing diseases to an unsupervised learning algorithm, we could have detected this virus as an anomaly with high probability since it would not have fallen into the category (cluster) of normal diseases. I hope this gives enough intuition to realize the importance of Anomaly Detection and why unsupervised learning methods are preferred over supervised learning methods in most cases for such tasks.</p><h3>Anomaly Detection Algorithm</h3><p>There are different types of anomaly detection algorithms but the one we’ll be discussing today will start from feature-by-feature probability distribution and how it leads us to using <strong>Mahalanobis Distance </strong>for the anomaly detection algorithm.</p><p>One of the most important assumptions for an unsupervised anomaly detection algorithm is that the dataset used for the learning purpose is assumed to have all non-anomalous training examples (or very very small fraction of anomalous examples). This might seem a very bold assumption but we just discussed in the previous section how less probable (but highly dangerous) an anomalous activity is. Also, the goal of the anomaly detection algorithm through the data fed to it is to learn the patterns of a normal activity so that when an anomalous activity occurs, we can flag it through the inclusion-exclusion principle. With this thing in mind, let’s discuss the anomaly detection algorithm in detail.</p><p>Data points in a dataset usually have a certain type of distribution like the <a href="https://en.wikipedia.org/wiki/Normal_distribution">Gaussian (Normal) Distribution</a>. Not all datasets follow a normal distribution but we can always apply certain transformation to features (which we’ll discuss in a later section) that convert the data’s distribution into a Normal Distribution, without any kind of loss in feature variance. Set of data points with Gaussian Distribution look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*NN4cisdtxK2VyrmYq0RF9A.png" /><figcaption>Normally Distributed Data (<a href="https://www.healthknowledge.org.uk/public-health-textbook/research-methods/1b-statistical-methods/statistical-distributions">Source</a>)</figcaption></figure><p>From the histogram above, we see that data points follow a Gaussian Probability Distribution and most of the data points are spread around a central (mean) location. When the frequency values on y-axis are mentioned as probabilities, the area under the bell curve is always equal to 1. Before we continue our discussion, have a look at the following normal distributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*8d7CYvW9CfprFilv1aavNw.png" /><figcaption>(<a href="https://en.wikipedia.org/wiki/Normal_distribution">Source</a>)</figcaption></figure><p>What do we observe? All the line graphs above represent Normal Probability Distributions and still, they are different. This is because each distribution above has 2 parameters that make each plot unique: the <strong>mean (μ)</strong> and <strong>variance (σ²)</strong> of data. The red, blue and yellow distributions are all centered at 0 mean, but they are all different because they have different spreads about their mean values. On the other hand, the green distribution does not have 0 mean but still represents a Normal Distribution. From this, it’s clear that to describe a Normal Distribution, the 2 parameters, <strong>μ </strong>and <strong>σ²</strong> control how the distribution will look like. As a matter of fact, 68% of data lies around the first standard deviation (<strong>σ</strong>) from the mean (34% on each side), 26.2 % data lies between the first and second standard deviation (<strong>σ</strong>) (13.1% on each side) and so on. This means that roughly 95% of the data in a Gaussian distribution lies within 2 standard deviations from the mean. We can use this to verify whether real world datasets have a (near perfect) Gaussian Distribution or not.</p><p>Real world data has a lot of features. If each feature has its data distributed in a Normal fashion, then we can proceed further, otherwise, it is recommended to convert the given distribution into a normal one. The following figure shows what transformations we can apply to a given probability distribution to convert it to a Normal Distribution. The resultant transformation may not result in a perfect probability distribution, but it results in a good enough approximation that makes the algorithm work well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*gORT47nFAXpyIB8Oz0Yu7Q.png" /><figcaption>Transforming Probability Distributions for Normality (<a href="https://www.statisticssolutions.com/transforming-data-for-normality/">Source</a>)</figcaption></figure><p>Remember the assumption we made that all the data used for training is assumed to be non-anomalous (or should have a very very small fraction of anomalies). We’ll put that to use here. We saw earlier that almost 95% of data in a normal distribution lies within two standard-deviations from the mean. Since the likelihood of anomalies in general is very low, we can say with high confidence that data points spread near the mean are non-anomalous. And since the probability distribution values between mean and two standard-deviations are large enough, we can set a value in this range as a threshold (a parameter that can be tuned), where feature values with probability larger than this threshold indicate that the given feature’s values are non-anomalous, otherwise it’s anomalous. Consider that there are a total of <strong>n </strong>features in the data. For a feature <strong>x(i)</strong> with a threshold value of <strong>ε(i)</strong>, all data points’ probability that are above this threshold are non-anomalous data points i.e. non-anomalous data points w.r.t. a particular feature are represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*XuSOUkKj3enJYreKe0JSZw.png" /></figure><p>Where <strong>P(X(i):</strong> <strong>μ(i), σ(i)) </strong>represents the probability of a given training example for feature <strong>X(i)</strong> which is characterized by the mean of <strong>μ(i) </strong>and variance of <strong>σ(i)</strong>.</p><p>The above case flags a data point as anomalous/non-anomalous on the basis of a particular feature. In reality, we cannot flag a data point as an anomaly based on a single feature. Only when a combination of all the probability values for all features for a given data point is calculated can we say with high confidence whether a data point is an anomaly or not. This scenario can be extended from the previous scenario and can be represented by the following equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*32OtBmiKsIv1H0et6YOK4w.png" /></figure><p>A data point is deemed non-anomalous when</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*PGu3ozcktjBjDOrOdvtJ7A.png" /></figure><p>Now that we know how to flag an anomaly using all n-features of the data, let us quickly see how we can calculate <strong>P(X(i)) </strong>for a given normal probability distribution. For that, we also need to calculate <strong>μ(i) </strong>and <strong>σ2(i)</strong>, which is done as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*TmJTc9Gwz5lwsWKg1N_dxQ.png" /></figure><p>where <strong>m</strong> is the number of training examples and <strong>n </strong>is the number of features.</p><p>We now have everything we need to know to calculate the probabilities of data points in a normal distribution. Let’s go through an example and see how this process works. Consider data consisting of 2 features x1 and x2 with Normal Probability Distribution as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*61KFqtgc1_qs2RODMEX5Yg.png" /></figure><p>If we consider a data point in the training set, then we’ll have to calculate it’s probability values wrt x1 and x2 separately and then multiply them in order to get the final result, which then we’ll compare with the threshold value to decide whether it’s an anomaly or not. To better visualize things, let us plot x1 and x2 in a 2-D graph as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*GXBfp8c1jo8DKVCO0DeaEw.png" /></figure><p>The combined probability distribution for both the features will be represented in 3-D as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*2Ivm5CEt69JRQaI32xPmpQ.png" /></figure><p>The resultant probability distribution is a Gaussian Distribution. Now, if we consider a training example around the central value, we can see that it will have a higher probability value rather than data points far away since it lies pretty high on the probability distribution curve. We saw earlier that approximately 95% of the training data lies within 2 standard deviations from the mean which led us to choose the value of <strong>ε </strong>around the border probability value of second standard deviation, which however, can be tuned depending from task to task. This indicates that data points lying outside the 2nd standard deviation from mean have a higher probability of being anomalous, which is evident from the purple shaded part of the probability distribution in the above figure.</p><h3>Evaluating an Anomaly Detection Algorithm</h3><p>Any anomaly detection algorithm, whether supervised or unsupervised needs to be evaluated in order to see how effective the algorithm is. Since the number of occurrence of anomalies is relatively very small as compared to normal data points, we can’t use accuracy as an evaluation metric because for a model that predicts everything as non-anomalous, the accuracy will be greater than 99.9% and we wouldn’t have captured any anomaly. This is completely undesirable. Our requirement is to evaluate how many anomalies did we detect and how many did we miss. Predicting a non-anomalous example as anomalous will do almost no harm to any system but predicting an anomalous example as non-anomalous can cause significant damage. One metric that helps us in such an evaluation criteria is by computing the <strong>confusion matrix</strong> of the predicted values. A confusion matrix is a summary of prediction results on a classification problem. The number of correct and incorrect predictions are summarized with count values and broken down by each class. This is the key to the confusion matrix. The confusion matrix shows the ways in which your classification model is confused when it makes predictions. It gives us insight not only into the errors being made by a classifier but more importantly the types of errors that are being made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*eA9aKPbLKY9U6w2UKWiXrA.png" /></figure><p>A <strong>true positive</strong> is an outcome where the model correctly predicts the positive class (non-anomalous data as non-anomalous). Similarly, a <strong>true negative</strong> is an outcome where the model correctly predicts the negative class (anomalous data as anomalous). A <strong>false positive</strong> is an outcome where the model incorrectly predicts the positive class (non-anomalous data as anomalous) and a <strong>false negative</strong> is an outcome where the model incorrectly predicts the negative class (anomalous data as non-anomalous). In the case of our anomaly detection algorithm, our goal is to reduce as many false negatives as we can. Lower the number of false negatives, better is the performance of the anomaly detection algorithm.</p><p>We have missed a very important detail here. The anomaly detection algorithm we discussed above is an unsupervised learning algorithm, then how do we evaluate its performance? While collecting data, we definitely know which data is anomalous and which is not. The reason for not using supervised learning was that it cannot capture all the anomalies from such a limited number of anomalies. That is why we use unsupervised learning with inclusion-exclusion principle. Suppose we have 10,040 training examples, 10,000 of which are non-anomalous and 40 are anomalous. This data will be divided into training, cross-validation and test set as follows:</p><p>Training set: 8,000 non-anomalous examples</p><p>Cross-Validation set: 1,000 non-anomalous and 20 anomalous examples</p><p>Test set: 1,000 non-anomalous and 20 anomalous examples</p><p>This distribution will enable us to capture as many patterns that occur in non-anomalous data points and then we can compare and contrast them with 20 anomalies, each in cross-validation and test set. The point of creating a cross validation set here is to tune the value of the threshold point <strong>ε.</strong></p><h3>Drawback of This Anomaly Detection Algorithm</h3><p>We need to know how the anomaly detection algorithm analyses the patterns for non-anomalous data points in order to know whether there is a further scope of improvement. Let’s consider a data distribution in which the plotted points do not assume a circular shape, like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*yzJmKl8EKA6bzVZrUtsAVg.png" /></figure><p>All the red points in the image above are non-anomalous examples. If we consider the point marked in green, using our intelligence we will flag this point as an anomaly. But, the way we the anomaly detection algorithm we discussed works, this point will lie in the region where it can be detected as a normal data point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*CQH7fyVaA6h7bixQi1XEcg.png" /></figure><p>The anomaly detection algorithm discussed so far works in circles. The inner circle is representative of the probability values of the normal distribution close to the mean. The second circle, where the green point lies is representative of the probability values that are close the first standard deviation from the mean and so on. This is undesirable because every time we won’t have data whose scatter plot results in a circular distribution in 2-dimensions, spherical distribution in 3-dimensions and so on. We need an anomaly detection algorithm that adapts according to the distribution of the data points and gives good results. Turns out that for this problem, we can use the <strong>Mahalanobis Distance (MD)</strong> property of a Multi-variate Gaussian Distribution (we’ve been dealing with multivariate gaussian distributions so far).</p><h3>Mahalanobis Distance for Anomaly Detection of a Multi-variate Gaussian Distribution</h3><p>The Mahalanobis distance (MD) is the distance between two points in multivariate space. In a regular Euclidean space, variables (e.g. x, y, z) are represented by axes drawn at right angles to each other. The distance between any two points can be measured with a ruler. For uncorrelated variables, the Euclidean distance equals the MD. However, if two or more variables are correlated, the axes are no longer at right angles, and the measurements become impossible with a ruler. In addition, if you have more than three variables, you can’t plot them in regular 3D space at all. The MD solves this measurement problem, as it measures distances between points, even correlated points for multiple variables.</p><p><strong>The</strong> <strong>Mahalanobis distance measures distance relative to the centroid — a base or central point which can be thought of as an overall mean for multivariate data</strong>. The centroid is a point in multivariate space where all means from all variables intersect. The larger the MD, the further away from the centroid the data point is.</p><p>To use Mahalanobis Distance for anomaly detection, we don’t need to compute the individual probability values for each feature. Instead, we can directly calculate the final probability of each data point that considers all the features of the data and above all, due to the non-zero off-diagonal values of Covariance Matrix <strong>Σ </strong>while calculating Mahalanobis Distance, the resultant anomaly detection curve is no more circular, rather, it fits the shape of the data distribution.</p><p>Mahalanobis Distance is calculated using the formula given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*PvK01Atgx9Mlelggv2uq8g.png" /></figure><p>Once the Mahalanobis Distance is calculated, we can calculate <strong>P(X)</strong>, the probability of the occurrence of a training example, given all <strong>n</strong> features as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*xcgmUBej_mxHMuBFWlQ91w.png" /></figure><p>Where <strong>|Σ| </strong>represents the determinant of the covariance matrix <strong>Σ</strong>.</p><p>The values <strong>μ </strong>and <strong>Σ</strong> are calculated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*7ja759Vb6IM9Cnj1zE_1ig.png" /></figure><p>Finally, we can set a threshold value <strong>ε</strong>, where all values of <strong>P(X) &lt;</strong> <strong>ε</strong> flag an anomaly in the data. However, this value is a parameter and can be tuned using the cross-validation set with the same data distribution we discussed for the previous anomaly detection algorithm.</p><p>Before concluding the theoretical section of this post, it must be noted that although using Mahalanobis Distance for anomaly detection is a more generalized approach for anomaly detection, this very reason makes it computationally more expensive than the baseline algorithm. Also, we must have the number training examples <strong>m</strong> greater than the number of features <strong>n </strong>(<strong>m </strong>&gt;<strong> n</strong>), otherwise the covariance matrix <strong>Σ </strong>will be non-invertible (i.e. <strong>Σ^-1 </strong>would become undefined).</p><p>Finally we’ve reached the concluding part of the theoretical section of the post. We understood the need of anomaly detection algorithm before we dove deep into the mathematics involved behind the anomaly detection algorithm. I recommend reading the theoretical part more than once if things are a bit cluttered in your head at this point, which is completely <em>normal</em> though. Now, let’s take a look back at the fraudulent credit card transaction dataset from Kaggle, which we solved using Support Vector Machines in <a href="https://towardsdatascience.com/machine-learning-iv-support-vector-machines-kaggle-dataset-with-svms-57d7c885652a">this</a> post and solve it using the anomaly detection algorithm.</p><h3>Problem Statement</h3><p>In this section, we’ll be using Anomaly Detection algorithm to determine fraudulent credit card transactions. Dataset for this problem can be found <a href="https://www.kaggle.com/mlg-ulb/creditcardfraud">here</a>. One thing to note here is that the features of this dataset are already computed as a result of PCA. This helps us in 2 ways:</p><p>(i) The confidentiality of the user data is maintained.</p><p>(ii) The features in the dataset are independent of each other due to PCA transformation.</p><p>Let’s start by loading the data in memory in a pandas data frame.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt</pre><pre>from sklearn import preprocessing<br>from sklearn.neighbors import LocalOutlierFactor<br>from sklearn.metrics import confusion_matrix, classification_report,accuracy_score</pre><pre>import os<br>for dirname, _, filenames <strong>in</strong> os.walk(‘/kaggle/input’):<br>  for filename <strong>in</strong> filenames<br>    print(os.path.join(dirname, filename))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*guX8OgPz2o-ce6ajY9Wr0g.png" /></figure><pre>df = pd.read_csv(&quot;/kaggle/input/creditcardfraud/creditcard.csv&quot;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*FrDUYsiXozYr_9zWBckvoA.png" /></figure><p>We proceed with the data pre-processing step. Let’s have a look at how the values are distributed across various features of the dataset.</p><pre>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Ong-zoNS9E4rflWPMwEluA.png" /></figure><p>The original dataset has over 284k+ data points, out of which only 492 are anomalies. Training the model on the entire dataset led to timeout on Kaggle, so I used 20% of the data ( &gt; 56k data points ).</p><pre>print(df.shape)<br>data= df.sample(frac = 0.2,random_state=1)<br>print(data.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*1FHW4YAzfcSbDhhYwyHz6g.png" /></figure><p>The data has no null values, which can be checked by the following piece of code.</p><pre>df.isnull().values.any()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/75/1*YAZBaiIQT2ro81iGHpkoiw.png" /></figure><p>Let us plot normal transaction v/s anomalous transactions on a bar graph in order to realize the fraction of fraudulent transactions in the dataset. Additionally, also let us separate normal and fraudulent transactions in datasets of their own.</p><pre>num_classes = pd.value_counts(df[&#39;Class&#39;], sort = True)<br>num_classes.plot(kind = &#39;bar&#39;)</pre><pre>plt.title(&quot;Transaction Class Distribution&quot;)<br>plt.xticks(range(2), [&quot;Normal&quot;, &quot;Fraud&quot;])<br>plt.xlabel(&quot;Class&quot;)<br>plt.ylabel(&quot;Frequency&quot;)</pre><pre>fraud = df[df[&#39;Class&#39;] == 1]<br>normal = df[df[&#39;Class&#39;] == 0]</pre><pre>print(fraud.shape, normal.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*bVx85-AqACw8XYVLBuJ-cA.png" /></figure><p>In the dataset, we can only interpret the ‘Time’ and ‘Amount’ values against the output ‘Class’. Let us see, if we can find something observations that enable us to visibly differentiate between normal and fraudulent transactions.</p><pre>f, (ax1, ax2) = plt.subplots(2, 1, sharex=True)<br>f.suptitle(&#39;Time of transaction v/s Amount by Class type&#39;)</pre><pre>ax1.scatter(fraud.Time, fraud.Amount)<br>ax1.set_title(&#39;Fraud&#39;)<br>ax2.scatter(normal.Time, normal.Amount)<br>ax2.set_title(&#39;Normal&#39;)</pre><pre>plt.xlabel(&#39;Time (in secs)&#39;)<br>plt.ylabel(&#39;Amount&#39;)<br>plt.xlim((0, 20000))</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*Vxk_326am6GCUGAmb8TWpA.png" /></figure><pre>f, (ax1, ax2) = plt.subplots(2, 1, sharex=True)<br>f.suptitle(&#39;Amount per transaction by class&#39;)</pre><pre>bins = 10<br>ax1.hist(fraud.Amount, bins = bins)<br>ax1.set_title(&#39;Fraud&#39;)<br>ax2.hist(normal.Amount, bins = bins)<br>ax2.set_title(&#39;Normal&#39;)</pre><pre>plt.xlabel(&#39;Amount ($)&#39;)<br>plt.ylabel(&#39;Number of Transactions&#39;)<br>plt.xlim((0, 20000))<br>plt.yscale(&#39;log&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*7hwSv8spwt1qAc-mAq4msA.png" /></figure><p>From the first plot, we can observe that fraudulent transactions occur at the same time as normal transaction, making time an irrelevant factor. From the second plot, we can see that most of the fraudulent transactions are small amount transactions. This is however not a huge differentiating feature since majority of normal transactions are also small amount transactions.</p><p>Before proceeding further, let us have a look at how many fraudulent and non-fraudulent transactions do we have in the reduced dataset (20% of the features) that we’ll use for training the machine learning model to identify anomalies.</p><pre>fraud = data[data[&#39;Class&#39;]==1]<br>normal = data[data[&#39;Class&#39;]==0]</pre><pre>anomaly_fraction = len(fraud)/float(len(normal))<br>print(anomaly_fraction)</pre><pre>print(&quot;Fraud Cases: &quot; + str(len(fraud)))<br>print(&quot;Normal Cases: &quot; + str(len(normal)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*hxIWIO3THhaL5rdZmWL33w.png" /></figure><p>We have just 0.1% fraudulent transactions in the dataset. This means that a random guess by the model should yield 0.1% accuracy for fraudulent transactions. We’ll, however, construct a model that will have much better accuracy than this one. You might be thinking why I’ve mentioned this here. I’ll refer these lines while evaluating the final model’s performance.</p><p>Recall that we learnt that each feature should be <em>normally distributed</em> in order to apply the unsupervised anomaly detection algorithm. Let us plot histograms for each feature and see which features don’t represent Gaussian distribution at all.</p><pre>data.hist(figsize=(15,15), bins = 64)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*mny5WmR433jffpplX5i6NA.png" /></figure><p>From the above histograms, we can see that ‘Time’, ‘V1’ and ‘V24’ are the ones that don’t even approximate a Gaussian distribution. Let’s drop these features from the model training process. We were going to omit the ‘Time’ feature anyways.</p><pre>columns = data.columns.tolist()</pre><pre>target=columns[-1]<br>columns = columns[:-1]</pre><pre>X_train = data.iloc[:45000, :-1]<br>y_train = data.iloc[:45000, -1]</pre><pre>X_test = data.iloc[45000:, :-1]<br>y_test = data.iloc[45000:, -1]</pre><pre>print(X_train.shape, X_test.shape)<br>print(y_train.shape, y_test.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*8dG0-40J2bkAu7DP7B7h6A.png" /></figure><p>Let us use the <em>LocalOutlierFactor</em> function from the scikit-learn library in order to use unsupervised learning method discussed above to train the model.</p><pre>model = LocalOutlierFactor(contamination=anomaly_fraction)</pre><pre>y_train_pred = model.fit_predict(X_train)<br>y_train_pred[y_train_pred == 1] = 0</pre><pre>y_train_pred[y_train_pred == -1] = 1<br>y_test_pred = model.fit_predict(X_test)</pre><pre>y_test_pred[y_test_pred == 1] = 0<br>y_test_pred[y_test_pred == -1] = 1</pre><p>Now that we have trained the model, let us evaluate the model’s performance by having a look at the confusion matrix for the same as we discussed earlier that accuracy is not a good metric to evaluate any anomaly detection algorithm, especially the one which has such a skewed input data as this one.</p><pre>import itertools</pre><pre>classes = np.array([&#39;0&#39;,&#39;1&#39;])</pre><pre>def plot_confusion_matrix(cm, classes,title=&#39;Confusion matrix&#39;, cmap=plt.cm.Blues):</pre><pre>plt.imshow(cm, interpolation=&#39;nearest&#39;, cmap=cmap)<br>plt.title(title)<br>plt.colorbar()</pre><pre>tick_marks = np.arange(len(classes))<br>plt.xticks(tick_marks, classes, rotation=45)<br>plt.yticks(tick_marks, classes)</pre><pre>fmt = &#39;d&#39;<br>thresh = cm.max() / 2.</pre><pre>for i, j <strong>in</strong> itertools.product(range(cm.shape[0]), range(cm.shape[1])):<br>plt.text(j, i, format(cm[i, j], fmt),<br>horizontalalignment=&quot;center&quot;,<br>color=&quot;white&quot; if cm[i, j] &gt; thresh else &quot;black&quot;)</pre><pre>plt.tight_layout()<br>plt.ylabel(&#39;True label&#39;)<br>plt.xlabel(&#39;Predicted label&#39;)</pre><p>The above function is a helper function that enables us to construct a confusion matrix. We’ll plot confusion matrices to evaluate both training and test set performances.</p><pre>cm_train = confusion_matrix(y_train, y_train_pred)<br>plot_confusion_matrix(cm_train,[&quot;Normal&quot;, &quot;Fraud&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*rfo5q28Dwq8ISuCZQKFVpQ.png" /></figure><pre>cm_test = confusion_matrix(y_test_pred, y_test)<br>plot_confusion_matrix(cm_test,[&quot;Normal&quot;, &quot;Fraud&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*b773g6PMFEWnshXj4mSe-A.png" /></figure><p>We see that on the training set, the model detects 44,870 normal transactions correctly and only 55 normal transactions are labelled as fraud. This is quite good, but this is not something we are concerned about. We can see that out of the 75 fraudulent transactions in the training set, only 14 have been captured correctly whereas 61 are misclassified, which is a problem. When we compare this performance to the random guess probability of 0.1%, it is a significant improvement form that but not convincing enough. Even in the test set, we see that 11,936/11,942 normal transactions are correctly predicted, but only 6/19 fraudulent transactions are correctly captured.</p><h3>Analysing the Performance</h3><p>When I was solving this dataset, even I was surprised for a moment, but then I analysed the dataset critically and came to the conclusion that for this problem, this is the best unsupervised learning can do. One reason why unsupervised learning did not perform well enough is because most of the fraudulent transactions did not have much unusual characteristics regarding them which can be well separated from normal transactions. This is supported by the ‘Time’ and ‘Amount’ graphs that we plotted against the ‘Class’ feature. And I feel that this is the main reason that labels are provided with the dataset which flag transactions as fraudulent and non-fraudulent, since there aren’t any visibly distinguishing features for fraudulent transactions. The accuracy of detecting anomalies on the test set is 25%, which is way better than a random guess (the fraction of anomalies in the dataset is &lt; 0.1%) despite having the accuracy of 99.84% accuracy on the test set.</p><pre>print(&#39;Total fraudulent transactions detected in training set: &#39; + str(cm_train[1][1]) + &#39; / &#39; + str(cm_train[1][1]+cm_train[1][0]))</pre><pre>print(&#39;Total non-fraudulent transactions detected in training set: &#39; + str(cm_train[0][0]) + &#39; / &#39; + str(cm_train[0][1]+cm_train[0][0]))</pre><pre>print(&#39;Probability to detect a fraudulent transaction in the training set: &#39; + str(cm_train[1][1]/(cm_train[1][1]+cm_train[1][0])))</pre><pre>print(&#39;Probability to detect a non-fraudulent transaction in the training set: &#39; + str(cm_train[0][0]/(cm_train[0][1]+cm_train[0][0])))</pre><pre>print(&quot;Accuracy of unsupervised anomaly detection model on the training set: &quot;+str(100*(cm_train[0][0]+cm_train[1][1]) / (sum(cm_train[0]) + sum(cm_train[1]))) + &quot;%&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*0LqlNrQtTpDfVlNHZfNQhg.png" /></figure><pre>print(&#39;Total fraudulent transactions detected in test set: &#39; + str(cm_test[1][1]) + &#39; / &#39; + str(cm_test[1][1]+cm_test[1][0]))</pre><pre>print(&#39;Total non-fraudulent transactions detected in test set: &#39; + str(cm_test[0][0]) + &#39; / &#39; + str(cm_test[0][1]+cm_test[0][0]))</pre><pre>print(&#39;Probability to detect a fraudulent transaction in the test set: &#39; + str(cm_test[1][1]/(cm_test[1][1]+cm_test[1][0])))</pre><pre>print(&#39;Probability to detect a non-fraudulent transaction in the test set: &#39; + str(cm_test[0][0]/(cm_test[0][1]+cm_test[0][0])))</pre><pre>print(&quot;Accuracy of unsupervised anomaly detection model on the test set: &quot;+str(100*(cm_test[0][0]+cm_test[1][1]) / (sum(cm_test[0]) + sum(cm_test[1]))) + &quot;%&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*bVPogKBW-bmC_2l7lPIMnQ.png" /></figure><p>The entire code for this post can be found <a href="https://www.kaggle.com/vardaanbajaj/unsupervised-anomaly-detection-for-fraud-detection">here</a>.</p><p>That’s it for this post. This post also marks the end of a series of posts on Machine Learning. It was a pleasure writing these posts and I learnt a lot too in this process. I believe that we understand things only as good as we teach them and in these posts, I tried my best to simplify things as much as I could. Mathematics got a bit complicated in the last few posts, but that’s how these topics were. Thanks for reading these posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44c55a96b8c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/unsupervised-learning-for-anomaly-detection-44c55a96b8c1">Unsupervised Learning For Anomaly Detection</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dimensionality Reduction and Deep Dive Into Principal Component Analysis]]></title>
            <link>https://medium.com/data-science/deep-dive-into-principal-component-analysis-fc64347c4d20?source=rss-168771086803------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc64347c4d20</guid>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kaggle]]></category>
            <dc:creator><![CDATA[Vardaan Bajaj]]></dc:creator>
            <pubDate>Wed, 29 Jul 2020 15:01:02 GMT</pubDate>
            <atom:updated>2020-08-09T18:37:41.778Z</atom:updated>
            <content:encoded><![CDATA[<h4>Along with a solved Kaggle Dataset</h4><h3>Contents</h3><p>In this post, we’ll be going through:</p><ol><li>The Need of Dimensionality Reduction</li><li>Methods of Dimensionality Reduction</li><li>PCA Algorithm through Singular Value Decomposition</li><li>Intuition for Eigenvectors and Eigenvalues</li><li>Tips to keep in mind while using PCA</li><li>Illustration of PCA on Kaggle’s MNIST digit dataset</li></ol><p>In this series of machine learning posts so far, we had an in-depth look at the first unsupervised learning algorithm (K-means) in the <a href="https://towardsdatascience.com/machine-learning-vi-unsupervised-learning-k-means-kaggle-dataset-with-k-means-1adf5c30281b">previous</a> post. In this post, we are going to have an in-depth look at another popular unsupervised learning algorithm called Principal Component Analysis (PCA). Unlike K-means, PCA is not a clustering algorithm, but an algorithm used for dimensionality reduction while trying to replicate the characteristics of the original dataset, which it does to a great extent. Throughout this post, I’ll try to provide intuition for each and every concept involved in PCA before diving deep into its technicalities and mathematics involved. So, before understanding what PCA does, let us first understand what Dimensionality Reduction is.</p><h3>Dimensionality Reduction</h3><p>The dimension of a dataset is equivalent to the number of features present in that dataset. The more the number of features in a dataset, the higher is its dimensionality. The terms ‘features’ and ‘dimensions’ are quite often used interchangeably. Dimensionality reduction is the transformation of data from a high-dimensional space into a low-dimensional space so that the low-dimensional representation tries to replicate all the features in the original dataset, albeit in a condensed form.</p><h3>The Need for Dimensionality Reduction</h3><p>A well performing machine learning model’s performance can significantly decay when the number of features (dimensions) in the dataset are increased. When a model is trained on such a large dimensional dataset, it is unable to generalize the patterns from the training dataset to real world datasets, resulting in <strong>overfitting and hence a poor performance</strong>.</p><p>Another disadvantage of having a dataset with a lot of features (dimensions) is that it consumes a significant amount of main memory while loading into a dataframe. While training a machine learning model with such a large amount of memory occupied, <strong>the training process becomes slow </strong>since the model has to process a large amount of data. Here, you can argue that we can use mini-batches of the data to train the model (<a href="https://machinelearningmastery.com/gentle-introduction-mini-batch-gradient-descent-configure-batch-size/">mini-batch gradient descent</a>) in order to reduce the memory occupied by the data. But here’s the catch. Suppose we load data in batches of <strong>k</strong>. If the original data has <strong>n</strong> features, then the memory occupied by the model at each mini-batch will be proportional to <strong>k</strong> x <strong>n</strong>. If through dimensionality reduction we can reduce the number of features from <strong>n</strong> to <strong>n’</strong>, then each mini-batch will occupy memory proportional to <strong>k</strong> x <strong>n’</strong>, which is way less than the memory occupied than the first case. Now, we might compensate for the large memory occupied in the first case by reducing the batch size <strong>k</strong>. But supplying less data with a large number of features won’t capture patterns in the data as the lower the number of data points, the probability that data points are sparsely distributed is higher.</p><p>In real world datasets, there are<strong> a lot of features that are correlated to each other </strong>i.e. not all features are independent of each other. For a robust machine learning model, we want the input data’s features to be independent of each other, since a large number of dependent features make the model partial towards these features.</p><p>All the above cases highlight the fact that for datasets with a large number of features (dimensions), we need to reduce the number of features before training any regressor/classifier to perform predictive tasks. The above drawbacks of high-dimensional data is commonly referred to as the <a href="https://en.wikipedia.org/wiki/Curse_of_dimensionality"><strong>Curse of Dimensionality</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*pa9R3VHesG6AWXQD6aoRcg.png" /><figcaption>Reducing <strong>D</strong> dimensions to <strong>d</strong> dimensions (<a href="https://www.assignmentpoint.com/business/business-statistics/dimensionality-reduction.html">Source</a>)</figcaption></figure><h3>Methods of Dimensionality Reduction</h3><p>The problem of Dimensionality Reduction can be divided into 2 parts:</p><p>(i) Feature Selection</p><p>(ii) Feature Extraction</p><p>Feature Selection is a technique in which we have a dataset with a large number of features and we select a subset of these features for the training process. This subset can be determined either by intuition or by some statistical techniques like Recursive Feature Elimination (RFE) which we used to solve the Titanic dataset from Kaggle in <a href="https://medium.com/analytics-vidhya/machine-learning-ii-logistic-regression-explained-data-pre-processing-hands-on-kaggle-728e6a9d4bbf">this</a> post. This method is however, not <em>much</em> effective since with loss of some features, we might lose important information from the data.</p><p>In Feature Extraction, we build new features (less than the actual number of features) from the existing dataset. We should <strong>only opt for feature extraction only if we can do with the loss of identity of features from the original dataset</strong>. Feature extraction is an excellent technique to replicate the variety (variance) of the dataset’s features by creating a small number of features (dimensions), but it comes at the cost of loss of individual feature identity i.e. the extracted features are not interpretable by humans since they comprise of numbers instead of other values. The algorithms that help in feature extraction are:</p><p>(i) Principal Component Analysis (PCA)</p><p>(ii) t-distributed Stochastic Neighbour Embedding (t-SNE)</p><p>In the following sections, we’ll have a detailed look at Principal Component Analysis (PCA).</p><p><strong>NOTE:</strong> Feature Extraction is usually preferred over feature selection but while building a machine learning model, we should always use the original set of features to train the initial model, since in some cases, dimensionality reduction does not yield significant improvement over the base model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*ZcdVpB3DT3jMQpmjw2WPTQ.png" /><figcaption>(<a href="https://www.groundai.com/project/a-scalable-saliency-based-feature-selection-method-with-instance-level-information/1">Source</a>)</figcaption></figure><h3>Principal Component Analysis (PCA)</h3><p>PCA is an <strong>unsupervised learning algorithm</strong> and one of the most widely used algorithms for dimensionality reduction. In one line, PCA is nothing but the transformation of axes of an <strong>n</strong>-dimensional feature space to a <strong>k</strong>-dimensional feature space which has little to almost no effect on the variance of the dataset. Variance of data is a property that defines how spread out the data points are in the original feature space and is important to retain while performing PCA in order to get maximum variety of data points from the given features, the absence of which can cause the resultant machine learning model to perform poorly, since the model won’t be able to generalize the patterns. Each of the <strong>k</strong>-dimensions, where <strong>k</strong> is the input to the PCA algorithm is referred to as a principal component. Each of these principal components is sorted in descending order based on the variance captured by them. For example, while reducing a 100-dimensional feature space to a 10-dimensional feature space, the first principal component (dimension) captures the most variance, the second principal components captures slightly less variance and so on.</p><p>Now that we have an idea of what PCA does, let’s first run through an example of PCA before diving deep into the PCA algorithm. For illustration purposes, we’ll be going through an example of how PCA converts a 2-dimensional feature space into a 1-dimensional feature space by retaining the variance of the data.</p><p>Consider the scatter plot below. This scatter plot has some data points (blue dots), where each data point is represented by values on the x-axis and the y-axis. As I mentioned earlier, PCA is nothing but transformation of axes in the direction of data such that <strong>k </strong>out of the <strong>n </strong>transformed axes (k &lt; n) point towards the direction of the data. Here k = 1 and n = 2. Applying PCA to the given data transforms the axes of the 2-dimensional feature space to the axes represented by the dotted axes shown below. We can clearly see that only 1 of these 2 axes seems to be able to very well approximate all the data points, so, we can successfully say that the given data can only be represented in 1-dimension instead of 2-dimensions and hence, PCA has done its magic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*zF7Drm8h86qVRK7oXnhOaw.png" /><figcaption>(<a href="https://glowingpython.blogspot.com/2011/07/principal-component-analysis-with-numpy.html">Source</a>)</figcaption></figure><p>But how does PCA know to transform axes in this particular direction? Well, PCA starts with some random transformation of axes and then measures the total squared distances (projection error) when all the data points are projected <strong>perpendicularly</strong> on each axis. This can be thought of as the cost function for PCA and the objective of the algorithm is to minimize this cost function. The minimization process yields the above dotted transformation of axes as a result. When the scatter plot for the data points is plotted, from the image below we can see how well the horizontal axis alone has the capability to represent all the data points while retaining the majority of the variance along that axis. The vertical axis has very less variance of data as compared to the horizontal axis and if the horizontal axis has captured the minimum threshold variance (say &gt; 90%) we wanted it to, then we can say that PCA has successfully done its job of converting 2-dimensional feature space into 1-dimensional feature space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*C9nuXfgI-ONL_Tg69GuUTw.png" /><figcaption>(<a href="https://glowingpython.blogspot.com/2011/07/principal-component-analysis-with-numpy.html">Source</a>)</figcaption></figure><p><strong>NOTE:</strong> For converting 2-dimesnional feature space into 1-dimensional feature space, the above process resembles a lot with linear regression. But keep in mind that the objective here is not to construct a straight line that generalizes all the data points, rather, the objective is to transform the axes in the direction of the data, which for a 2-dimensional problem might resemble Linear Regression, but for PCA’s application in high feature spaces, the end result is very much different.</p><p>Having seen an example of how PCA works, let’s dive deep into the PCA algorithm.</p><h3>PCA Algorithm</h3><p>Before going deep into the algorithm, I would recommend (not mandatory) reading <a href="https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues">this</a> answer on Stack Exchange. You don’t need to read the full answer, follow it till the point you start finding things complicated and then resume this post from here. Rest assured, you’ll have a good hold over the PCA algorithm by the end of this post.</p><p>PCA is one of the more difficult algorithms in machine learning since it involves the use of complex Linear Algebra. The entire algorithm of PCA can be divided into 2 steps:</p><p>(i) Standardizing the data</p><p>(ii) Eigen decomposition of the input correlation matrix</p><p>Standardizing the data is a data pre-processing step and an important part of PCA algorithm since it brings down all the data values across different features of data down to the same scale. This is achieved in two steps: <strong>mean normalization</strong> and <strong>feature scaling</strong>. In mean normalization, the mean of each feature is subtracted from all the values of that feature. Due to this, the new mean of each feature is zero. Once mean normalization has been performed, the data values, even after having a mean of zero still can be quite spread apart. Each feature has values in a different range and for PCA, we want that the values lie in a particular range. For this, we can divide the normalized mean values of each feature with the standard deviation of each feature. The overall effect of this process is that we have data values of all the features in a particular range which are centralized in that range (due to zero mean). The formula for the above process looks like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*0KLZrF3igfMaCSRgmzgrFw.png" /></figure><p>where <strong>x̅</strong> is the mean of all the values of a feature, <strong><em>σ</em></strong><em> is the standard deviation and </em><strong><em>x’</em></strong><em> is the final standardized value.</em></p><p>Let’s separate the input training features from the output labels before discussing eigen-decomposition since PCA is an unsupervised learning algorithm. If the input dataset has <strong>n </strong>training features and <strong>m </strong>training examples, then the matrix that represents the data is of the size <strong>m </strong>x<strong> n </strong>i.e. the training examples are represented as rows and the features are represented as columns. Since this matrix represents the input data, let’s call it <strong>X</strong>. We know that when we’ll perform PCA on this data, the number of features <strong>n</strong> would reduce to <strong>k</strong>. Let’s call the input matrix of shape <strong>k</strong> x <strong>m</strong> that we’ll obtain after PCA as <strong>Z</strong>.</p><p>Let’s go through eigen-decomposition step-by-step.</p><ol><li>The first step of eigen-decomposition involves the construction of a correlation matrix for the input data. This is calculated by the matrix multiplication of the transpose of the input matrix and the original input matrix and is represented as <strong>XᵀX</strong>. The correlation matrix is an <strong>n</strong> x <strong>n</strong> matrix and as the name suggests, it calculates the how much the features of the dataset are related to each other. All the values in the correlation matrix are between -1 and 1, where the positive values show that the 2 values are strongly correlated and the negative value indicates that the 2 values are not correlated. Correlation matrix is a symmetric matrix since the <strong>correlation(a, b) = correlation(b, a)</strong>. The image below is a heatmap of a correlation matrix of a dataset on which PCA has already been applied. We can see that all the diagonal values are close to 1, indicating that each feature has a strong correlation with itself but all the other values are negative, suggesting every feature has almost no correlation with the other features. This is what the final correlation matrix should like after PCA has been applied. However, the correlation matrix <strong>XᵀX </strong>needs to be converted into a matrix like this and for this the eigenvectors and eigenvalues of the correlation <strong>XᵀX </strong>come into play. Before moving further, you should watch <a href="https://www.youtube.com/watch?v=PFDu9oVAE-g&amp;vl=en">this</a> video in order to visualize what eigenvectors and eigenvalues of a matrix represent. However, I’ve briefed this in a section below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*e00OzA_BSLnrAqK1WLZhvQ.png" /></figure><p><strong>2.</strong> Once the correlation matrix is computed, we can use <strong>Singular Value Decomposition (SVD)</strong> to (eigen)decompose the original input matrix <strong>X</strong>. Through SVD, we can decompose the matrix <strong>X</strong> into 3 matrices as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/93/1*xBKXMpxCnEbMo0VIFey_RA.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*0rDhJYIcEf1wZIrIlxkVzQ.png" /><figcaption>SVD for 2-dimensional data</figcaption></figure><p>NS represents the Null spaces of the matrix and <strong>λ(n) </strong>represents the eigenvalue corresponding to the eigenvector v(n).</p><p>How we came up with the idea of SVD to use for PCA is a work of genius by many statisticians and mathematicians, but to further understand how the decomposed matrices through SVD are used, I recommend watching <a href="https://www.youtube.com/watch?v=Ls2TgGFfZnU">this</a> video to satisfy yourself that the eigen-decomposition of a matrix into 3 matrices like this is correct.</p><p><strong>Understanding Eigenvectors and Eigenvalues</strong></p><p>The term ‘eigen’ is a German word that means ‘characteristic’. Eigenvectors and eigenvalues are the characteristic features of a matrix. A matrix can be considered as a combination of a number of vectors and an eigenvector is one such special vector that points in the direction of the maximum variance of the data and the length of the eigenvector is its eigenvalue. Once a transformation (like PCA) is applied to the matrix, the direction of the eigenvector doesn’t change (for all other ordinary vectors, it changes) but the eigenvalue corresponding to that eigenvector can change. Here, we do not need to care about the process of calculating eigenvectors and eigenvalues, since this is a very complex step and is a part of linear algebra libraries in python, where there are optimized implementations inbuilt for this calculation.</p><p><strong>3.</strong> Once we have the eigenvectors and eigenvalues separated out, we can sort the values in the matrix <strong>U</strong> in decreasing order by measuring their corresponding eigenvalue in the vector <strong>Vᵀ</strong>. Once we have eigenvectors in the decreasing order of their eigenvalues, the first eigenvector captures maximum variance of the original data, the second eigenvector captures somewhat less variance than the first one and so on. Each eigenvector here is referred to as a <strong>principal component</strong>. In the next section, we’ll see how to select the number of principal components.</p><p><strong>4.</strong> For now suppose that we have selected the first <strong>K </strong>principal components, then we get the final reduced feature matrix from the matrix multiplication in the formula mentioned below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*QfRC-p4ZDEBF0fXhBhiR5w.png" /></figure><p>Here, U[:k] is the slice of the first k eigenvectors of the U matrix of shape (n, k) and X is the input feature matrix of shape (m , n). The result is stored in the matrix Z. We can also get back the original input matrix back from Z, but the data values in it will be an approximation of the original values, but we get the original features back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*5He6EMBbKCNZdkYnKricrg.png" /></figure><p>X_approx is an (m, n) shaped matrix.</p><p>Now, when we construct the correlation matrix for Z, it should look similar to the heatmap shown previously. This indicates that PCA has been applied successfully on the input data and hence we have successfully eliminated all the features which were either related to each other or were redundant.</p><h3>Choosing the Number of Principal Components</h3><p>Earlier we assumed that we select <strong>K</strong> principal components after applying PCA. But, how to choose <strong>K</strong>? We want that through these K principal components, we capture the maximum amount of variance of the original data. However, the amount of variance required is subject to the machine learning task at hand. However, it is recommended that we retain variance from anywhere between 90% — 99% of the original variance with as minimum principal components as possible. To ensure this, we first begin with the first principal component and measure the variance captured by it. Then we consider the first 2 principal components and measure how much variance is captured by this combination. This process is repeated until we get K principal components that yield the desired variance. The total number of principal components that leads us to this desired variance is the final number of dimensions (principal components) that are used for further training of a machine learning model (regressor / classifier / neural network). The formula to check if given the principal components retain 99% variance is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*OOCVaFn8xExcbAlZlGWSKg.png" /></figure><h3>Key Points To Remember While Applying PCA</h3><p>1) PCA should only be applied on the training dataset. For the cross-validation and test dataset, only the <strong>X -&gt; Z</strong> mapping that is created by PCA should be applied.</p><p>2) It might occur that since PCA helps in reducing the number of input features, it might as well prevent overfitting of a model. While this is true to an extent, in practice, always try to address overfitting through regularization method since applying PCA doesn’t make much of a difference in this regard.</p><p>3) It might be tempting to use PCA for dimensionality reduction for every machine learning problem having a large number of features but we should always try to train our first model with the original feature set. If this doesn’t yield desirable results, only then we should consider applying PCA on the input features.</p><p>That’s it for the PCA algorithm. We’ve learnt how PCA helps in dimensionality reduction and the mathematics involved behind it. In order to consolidate these concepts I created <a href="https://www.kaggle.com/vardaanbajaj/illustration-of-pca-through-mnist-dataset/comments?scriptVersionId=39720618">this</a> notebook (follow the next section for details) on Kaggle which illustrates how PCA works with visualization of a few principal components as well.</p><h3>Problem Statement</h3><p>We use the MNIST digit dataset which contains 784 feature values, where each feature represents a pixel value. The task of the problem is to make a digit recognizer. I haven’t created a model for recognizing digits, since it will use a neural network and I haven’t discussed neural networks yet, but 784 is a lot of features and by applying PCA on the input data, you’ll see that around 300 features are enough to capture 95% variance of the data, which is a pretty good reduction of features. You can try training a neural network to recognize the digits from the reduced features yourself after following the steps for PCA here if you have some knowledge about them. The dataset for the problem can be found <a href="https://www.kaggle.com/c/digit-recognizer/data">here</a>.</p><p>Let’s start by importing the required libraries and measuring the shape of the input data.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.image as mpimg<br>import matplotlib.pyplot as plt<br>import matplotlib<br>%matplotlib inline</pre><pre>from sklearn.decomposition import PCA<br>import os</pre><pre>for dirname, _, filenames <strong>in</strong> os.walk(‘/kaggle/input’):<br>  for filename <strong>in</strong> filenames:<br>    print(os.path.join(dirname, filename))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*YsQKMSClRzVuTKaz9cqhAg.png" /></figure><pre>df = pd.read_csv(&quot;/kaggle/input/digit-recognizer/train.csv&quot;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*WYL-vfqh5TRfmUkmqYg4lA.png" /></figure><pre>df.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*fmqF_UcwJnjUAW8qs3oAEw.png" /></figure><p>The given dataset has 42000 training examples, 784 features and 1 output label. Let’s separate the input features from the output label.</p><pre>test_df = df[&#39;label&#39;]<br>train_df = df.drop(&#39;label&#39;, axis = 1)</pre><p>Now, we need to standardize the data before applying eigen-decomposition.</p><pre><em># Standardize the data<br></em>from sklearn.preprocessing import StandardScaler<br>X = train_df.values<br>X_std = StandardScaler().fit_transform(X)</pre><p>In the steps below, we first construct the correlation matrix for the input data and then calculate the eigenvectors and the corresponding eigenvalues. Once we have these eigenvectors, we sort them in decreasing order based on the eigenvalues and calculate the percentage of variance represented by each of these eigenvectors.</p><pre><em># Calculating Eigenvectors and eigenvalues of Cov matirx<br></em>mean_vec = np.mean(X_std, axis=0)<br>cov_mat = np.cov(X_std.T)<br>eig_vals, eig_vecs = np.linalg.eig(cov_mat)</pre><pre><em># Create a list of (eigenvalue, eigenvector) tuples<br></em>eig_pairs = [ (np.abs(eig_vals[i]),eig_vecs[:,i]) for i <strong>in</strong> range(len(eig_vals))]</pre><pre><em># Sort the eigenvalue, eigenvector pair from high to low<br></em>eig_pairs.sort(key = lambda x: x[0], reverse= True)</pre><pre><em># Calculation of Explained Variance from the eigenvalues<br></em>tot = sum(eig_vals)<br>var_exp = [(i/tot)*100 for i <strong>in</strong> sorted(eig_vals, reverse=True)] <em># Individual explained variance<br></em>cum_var_exp = np.cumsum(var_exp) <em># Cumulative explained variance</em></pre><p>By printing the variables <em>var_exp</em> and <em>cum_var_exp</em>, you can observe each eigenvector’s contribution towards the variance and as expected, the individual variance decreases as we go through the eigenvectors but the cumulative variance adds up to 100% eventually. Let’s plot variances against each eigenvector to verify our observations.</p><pre>plt.plot(list(range(784)), cum_var_exp, label = &#39;Cumulative Variances&#39;)</pre><pre>plt.xlabel(&#39;Feature No.&#39;)<br>plt.ylabel(&#39;Variance %&#39;)<br>plt.title(&#39;Cumulative Variance % v/s Features&#39;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*cYkjWTe8ijeI2lcCVGwnmQ.png" /></figure><pre>plt.plot(list(range(784)), var_exp, label = &#39;Individual Variances&#39;)</pre><pre>plt.xlabel(&#39;Feature No.&#39;)<br>plt.ylabel(&#39;Variance %&#39;)<br>plt.title(&#39;Individual Variance % v/s Features&#39;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*Itpj0nXBZIM3V-rTPdoQwQ.png" /></figure><p>From the above 2 plots, it is clear that the majority of variance is captured between 200–300 features and individual variances after 300 features are close to zero. So, using anywhere between 200–300 features would be a very good choice since close to 95% variance has been captured. So, let’s perform PCA with top 300 features and visualize the type of features captured by top 25 eigenvector-eigenvalue pairs.</p><pre>n_components = 300<br>pca = PCA(n_components= n_components).fit(train_df.values)<br>eigenvalues = pca.components_</pre><pre>n_row = 5<br>n_col = 5</pre><pre><em># Visualizing first 25 eigenvectors through their eigenvalues<br></em>plt.figure(figsize=(13,12))<br>for i <strong>in</strong> list(range(n_row * n_col)):<br>  offset =0<br>  plt.subplot(n_row, n_col, i + 1)<br>  plt.imshow(eigenvalues[i].reshape(28,28), cmap=&#39;jet&#39;)<br>  title_text = &#39;Eigenvalue &#39; + str(i + 1)<br>  plt.title(title_text, size=6.5)<br>  plt.xticks(())<br>  plt.yticks(())<br>  plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*-XUIdLvjSHyQ_3iOMB_Yog.png" /></figure><p>The subplots above portray the top 25 optimal directions or principal component axes that the PCA method has decided to generate for the digit dataset. When we compare the first component “Eigenvalue 1” to the 25th component “Eigenvalue 25”, it is evident that more complicated directions or components are being generated by each passing eigenvector in search to maximise variance in the new feature subspace, which supports the theory studied earlier.</p><p>While plotting, I used the ‘jet’ colour map but you can try out many values from <a href="https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html">here</a> and see which one gives the best visuals.</p><p>So far, we’ve just seen the data as separate pixels. Let us plot these pixels as 28 x 28 pixel images to have a peek into the images of digits rather than just looking at 1s and 0s.</p><pre><em># plotting some numbers from the dataset<br></em>plt.figure(figsize=(14,12))</pre><pre>for digit_num <strong>in</strong> range(0,50):<br>  plt.subplot(7,10,digit_num+1)<br>  grid_data = train_df.iloc[digit_num].to_numpy().reshape(28,28)<br>  plt.imshow(grid_data, interpolation = &quot;none&quot;, cmap = &quot;gist_gray&quot;)<br>  plt.xticks([])<br>  plt.yticks([])</pre><pre>plt.tight_layout()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*vWBqhMmOuhb0R9eG15EBvQ.png" /></figure><p>From the 50 digit images above, we can see that the top, bottom, left and right columns are black for all the images. This means that the pixel values corresponding to these columns are redundant and hence, useless. Among many types of redundant features that PCA will remove, this is probably the most prominent of them.</p><p>To cap it off, we’ll use 10000 data points and 30 principal components and will try to see if variances captured by every principal component is greater than the subsequent principal components. If that’s the case, this means that PCA has been successful in its task.</p><pre>X = train_df[:10000].values</pre><pre><em># Standardizing the values<br></em>X_std = StandardScaler().fit_transform(X)</pre><pre><em># Call the PCA method with 30 components.<br></em>pca = PCA(n_components = 30)<br>pca.fit(X_std)<br>X_30d = pca.transform(X_std)<br>y = test_df[:10000].values</pre><pre><br>plt.scatter(X_30d[:,0], X_30d[:,1])<br>plt.xlabel(&#39;First Principal Component&#39;)<br>plt.ylabel(&#39;Second Principal Component&#39;)<br>plt.show()</pre><pre>plt.scatter(X_30d[:,0], X_30d[:,9])<br>plt.xlabel(&#39;First Principal Component&#39;)<br>plt.ylabel(&#39;Tenth Principal Component&#39;)<br>plt.show()</pre><pre>plt.scatter(X_30d[:,0], X_30d[:,19])<br>plt.xlabel(&#39;First Principal Component&#39;)<br>plt.ylabel(&#39;Twentieth Principal Component&#39;)<br>plt.show()</pre><pre>plt.scatter(X_30d[:,0], X_30d[:,29])<br>plt.xlabel(&#39;First Principal Component&#39;)<br>plt.ylabel(&#39;Thirtyth Principal Component&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*LNjXedrXlsZteB298v2IlA.png" /></figure><p>The horizontal axis in each plot above represents the first principal component and the vertical axis has the 2nd, 10th, 20th and 30th principal component. We can clearly see that in each plot, the spread of data along the horizontal axis is greater and in the subsequent plots, the spread along the vertical axis reduces significantly which means the initial principal components capture more variance than others. This proves the correctness of PCA implementation.</p><p>That’s it for this post. We had an in-depth look at Principal Component Analysis in this post and this indeed was one of the most difficult topics we’ve covered so far. In the <a href="https://towardsdatascience.com/unsupervised-learning-for-anomaly-detection-44c55a96b8c1">next</a> post, we’ll have a detailed look at Anomaly Detection algorithms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc64347c4d20" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deep-dive-into-principal-component-analysis-fc64347c4d20">Dimensionality Reduction and Deep Dive Into Principal Component Analysis</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unsupervised Learning and Deep Dive Into K-Means]]></title>
            <link>https://medium.com/data-science/machine-learning-vi-unsupervised-learning-k-means-kaggle-dataset-with-k-means-1adf5c30281b?source=rss-168771086803------2</link>
            <guid isPermaLink="false">https://medium.com/p/1adf5c30281b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[Vardaan Bajaj]]></dc:creator>
            <pubDate>Tue, 21 Jul 2020 11:28:41 GMT</pubDate>
            <atom:updated>2020-07-30T11:40:07.085Z</atom:updated>
            <content:encoded><![CDATA[<h4>Along with a solved Kaggle Dataset with K-Means</h4><h3>Contents</h3><p>In this post, we’ll be going through:</p><ol><li>Unsupervised Learning</li><li>Working example of K-Means</li><li>Cost Function for K-Means</li><li>Initialization methods for clusters</li><li>Elbow Method (hit-and-trial method)</li><li>Kaggle’s Credit Card Dataset to map user spending activity</li></ol><p>So far in the series of posts on Machine Learning, we have had a look at the most popular supervised algorithms up to this point. In the <a href="https://medium.com/analytics-vidhya/machine-learning-v-decision-trees-random-forest-kaggle-dataset-with-random-forest-3ebfe6d584be">previous</a> post, we discussed Decision Trees and Random Forest in great detail. This post and the next few posts will focus on Unsupervised Learning Algorithms, the intuition and mathematics behind them, with a solved Kaggle dataset at the end.</p><h3>Unsupervised Learning</h3><p>Learning tasks done without supervision is unsupervised learning. Unlike supervised machine learning algorithms, there are no labels present in the training data for unsupervised learning which supervise the machine learning model’s performance. But, like supervised learning algorithms, unsupervised learning is used for both, discrete and continuous data values. Formally, unsupervised learning is a type of machine learning algorithm used to draw inferences from datasets consisting of input data without labelled responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*kB59UKVBSatqNxLfdiJFcA.png" /><figcaption>(<a href="https://www.kdnuggets.com/2018/04/supervised-vs-unsupervised-learning.html">Source</a>)</figcaption></figure><p>There are two types of Unsupervised Learning: <strong>discriminative models</strong> and <strong>generative models</strong>. Discriminative models are only capable of telling you, if you give it X then the consequence is Y whereas the generative model can tell you the total probability that you’re going to see X and Y at the same time.</p><p>So the difference is as follows: the <strong>discriminative model assigns labels to inputs, and has no predictive capability</strong>. If you gave it a different X that it has never seen before it can’t tell what the Y is going to be because it simply hasn’t learnt it yet. With a <strong>generative model</strong>, once you set it up and find the baseline you can give it any input and ask for a prediction. Thus, it <strong>has a predictive ability</strong>.</p><p>Two common use cases of unsupervised learning are:</p><p>(i) Cluster Analysis a.k.a. Exploratory Analysis</p><p>(ii) Principal Component Analysis</p><p>Cluster analysis or clustering is the task of grouping data points in such a way that data points in a cluster are alike and are different from data points in the other clusters. Clustering has various applications such as in market segmentation, pattern recognition, word vectors, detecting cyber-attacks and many such areas.</p><p>Principal Component Analysis is used to reduce the dimensionality (the number of features) of a dataset. In addition to reducing the dimensionality, Principal Component Analysis also converts data into a numeric form which is difficult to interpret by humans. Through Principal Component Analysis, the training time of the model can be reduced to a great extent with just a very slight decline in accuracy.</p><p>Some common examples of unsupervised learning are K-means, Principal Component Analysis (PCA), Autoencoders, etc. In this post, we’ll have a detailed look at K-means algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*NTJbb77Wzv8Ux7m_u_jHLA.png" /><figcaption>Unsupervised Learning Example (<a href="https://www.kdnuggets.com/2018/04/supervised-vs-unsupervised-learning.html">Source</a>)</figcaption></figure><h3>K-Means</h3><p>Let’s first get the hang of the term ‘K-Means’. In statistics, ‘mean’ refers to the average of a given set of data points. This means that the algorithm deals with ‘K’ averages. But, what does ‘K’ averages signify? We usually have just a single average representing the entire data. Having ‘K’ averages signifies that we have performed the ‘mean’ operation on ‘K’ data segments, each of which can be treated as a separate independent unit. So, having ‘K’ averages for the given data is possible only when it is divided into ‘K’ parts/groups/clusters. The term K-means in itself is sufficient to describe that it’s a clustering algorithm and hence we should avoid using the term ‘clustering’ with K-means. Later we’ll see that this is exactly how the mathematics behind K-means works.</p><p>Formally, K-Means is an unsupervised learning algorithm that takes an unlabelled dataset with ‘m’ records and groups it into ‘K’ subsets/clusters, where each cluster has records having similar attributes and K &lt; m. The algorithm however is not intelligent enough to determine the number of clusters in the data automatically and hence requires a predefined number of clusters (K) to divide the data into ‘K’ coherent groups. That being said, K-means is still one of the most widely used clustering algorithms due to its simplicity and fast computation time.</p><p>K-means algorithm works in 2 steps.</p><p>(i) Cluster assignment</p><p>(ii) Move centroid</p><p>Both of these steps are repeated until the algorithm converges.</p><h3>K-Means Working Example</h3><p>To better understand the 2 steps of K-means, let’s look at how K-means works through an example and the optimization objective (cost function) involved. In order to visualize things, we’ll assume that the data we’re using just has 2 features i.e. 2-dimensional data. Let us divide the data into 2 clusters, so K = 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*9O6121npN0kv1zWsyLatbA.png" /><figcaption>K-Means Working (<a href="https://stanford.edu/~cpiech/cs221/handouts/kmeans.html">Source</a>)</figcaption></figure><p>Given the scatter plot for raw data in fig. (a), first of all 2 random points (cluster centroids) are selected on the graph (fig. b). Once these points have been selected, the proximity of all the data points to the chosen cluster points is calculated. There are many ways to calculate proximity and one of the easiest ways is to use Euclidean distance. Once all the Euclidean distances are calculated, the data points are assigned to those cluster centroids which are nearest to them. In fig. c, data points are assigned to red/blue cluster centroids based on their proximity to the cluster centroid. This is the <strong>cluster assignment step </strong>where each data point is assigned to a cluster. But these cluster assignments are not optimal since the initial values of cluster centroids were randomly chosen. To overcome this, the centre value of all the data points belonging to a cluster is calculated and the cluster centroid is moved to this new position as represented in fig. d. This is the <strong>move centroid step</strong>. So far, we have performed one iteration of the cluster assignment and the move centroid step and haven’t got a good division of data points into clusters. We need to perform multiple iterations of these 2 steps in order for the K-means algorithm to converge. Fig. e performs the ‘cluster assignment step’ for the new cluster centroids obtained in fig. d and then fig. f performs the ‘move centroid step’ to give new and optimal cluster centroids. At this point, after 2 iterations of these steps, we seem to have reached an optimal cluster grouping for the given data points. In reality, it takes a large number of iterations to reach an optimal cluster grouping.</p><p>The entire process of K-means clustering described above can be summarized through the following pseudo-code.</p><pre>Initialize cluster centroids µ(1), µ(2), µ(3), ……, µ(k) <strong>∈ R</strong>n randomly, where <strong>R</strong>n represents a feature vector of n-dimensions.</pre><pre>Repeat until convergence:<br>{<br>  for i = 1 to m<br>    c(i) = cluster centroid closest to training example x(i)<br>  for k = 1 to K<br>    µ(k) = average (mean) of points assigned to cluster k<br>}</pre><h3>Cost Function</h3><p>Now that we know how the steps involved in K-means lead to clustering, let us try to obtain the optimization objective (cost function) involved through the intuition behind these steps. In one line, K-means algorithm determines the cluster centroid for each data point, then shifts the cluster centroid to a central position of that cluster and both of these steps are repeated until the algorithm converges. Hence, the cost function should minimize the overall distance of every cluster centroid with its corresponding data points; subject to the conditions that occur in ‘cluster assignment step’ and ‘move centroid step’.</p><p>Before formally defining the cost function for K-means, let’s have a look at the notation used to define the cost function.</p><p>· c(i) = cluster number (between 1 and K) to which training example x(i) is currently assigned</p><p>· µ(k) = representation of a cluster centroid (µ(k) <strong>∈ R</strong>n)</p><p>· µ(c(i)) = representation of cluster centroid of the cluster to which training example x(i) has been assigned.</p><p>The parameters for the cost function are c(i) and µ(k) (also µ(c(i))), since by varying these parameters, we can get different clusters and the target is to get the most optimal clusters which can be obtained by minimizing the cost function. The minimization objective for K-means is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Leqo1IGCReKHoEr-naMxWQ.png" /></figure><p>and the values of c(i) and µ(k) for which the cost function yields minimum value are the optimal values of these parameters. During the ‘cluster assignment step’, the cost function is minimized wrt the parameters c(i) keeping µ(k) fixed (i.e. the partial derivative of the cost function is taken wrt the c(i) variables) and during the ‘move centroid’ step, the cost function is minimized wrt the parameters µ(k) keeping c(i) fixed (i.e. the partial derivative of the cost function is taken wrt the µ(k) variables).</p><p>The gradient descent algorithm then updates the cost function after computing the aggregate of these 2 partial derivatives and enables us to reach the global minima/a good local minima.</p><h3>Initializing Clusters</h3><p>In the pseudo-code for k-means, we saw how the cluster assignment step and the move centroid step work in tandem to generate k clusters, but we still haven’t discussed how to initialize the cluster centroids randomly, which was the first line of the pseudo-code. Just like we randomly initialized the parameters ‘W’ and ‘b’ in linear and logistic regression, here, there are different ways of initializing the parameters c(i) and µ(k) randomly. Let’s discuss them one by one.</p><p><strong>(i)</strong> <strong>Forgy Initialization</strong>: Forgy initialization is one good and fast way of initializing parameters. For K clusters, Forgy method randomly chooses K observations from the training dataset and uses them as the initial means (cluster centroids). Forgy initialization is quite an intuitive technique for initializing cluster centroids since the cluster centroids will lie somewhere near to the training data points, however in practice it tends to spread the initial means out i.e. the algorithm takes more steps to converge.</p><p><strong>(ii)</strong> <strong>Random Partition</strong>: In this method, each data point is randomly assigned to one of the K clusters, data points with same group are combined together to form groups and their mean value is taken to determine the initial cluster centroids. Random Partition method is generally preferred for fuzzy k-means but for the standard k-means, forgy initialization works well.</p><p><strong>(iii) K-means++</strong>: The intuition behind this approach is that spreading out the K initial cluster centroids is a good thing. The first cluster centroid is chosen uniformly at random from the data points that are being clustered, after which each subsequent cluster centroid is chosen from the remaining data points with probability proportional to its squared distance from the point’s closest existing cluster center. This method outperforms both, Forgy Initialization and Random Partition methods and is a preferred choice. More about K-means++ can be found <a href="https://en.wikipedia.org/wiki/K-means%2B%2B">here</a>.</p><h3>The Problem of Local Optima</h3><p>Although the above mentioned random initializations work well for K-means, they can result in K-means converging to a bad local optimum (some local optima are close to global optima and some are not) of the cost function, resulting in poor cluster formation. In fact, in all the algorithms that have random initialization steps, they are at this risk of getting stuck on local optima, even linear and logistic regression algorithms. Look at the image below to see an example of clusters formed by K-means when the algorithm gets stuck in a bad local optimum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*R3hoOs2NDA4v8t8TUf_Xnw.png" /></figure><p>These bad local optima are detrimental for the model’s performance. We need to avoid such a scenario. The solution is simple though. For values of K between 2–10, we can overcome this problem by running 10 to 1000 iterations of K-means, each time with different initial random initializations and pick that one model for which the set of parameters (c(i) and µ(k)) obtained leads to the smallest value for the cost function. However, this method does not work for large values of K since the more clusters we want, greater is the chance of the algorithm converging to a local optima. Hence, in such cases, we don’t need to apply K-means a large number of times since each time there will be high chances of converging to a local minima. A single iteration of K-means gives satisfactory results for large values of K.</p><h3>Choosing K</h3><p>Since we have no way to evaluate the K-means model’s performance due to unlabelled data, the choice of the variable K becomes challenging. The most sensible thing to do in such cases is to use a hit-and-trial method. In the hit-and-trial method used for K-means, we choose a range of values of K (let’s say 1 to 10) and compute the overall cost by running K-means with every possible value of K in the range selected. The value of K up to which the cost function decreases steeply and after which the cost function decreases quite slow can be considered an optimum value of K. This method is called the <strong>Elbow Method</strong> but I simply like calling it the hit-and-trial method. However, it is not a compulsion to choose this elbow point as the optimum value of K. The value of cost function decreases with increasing values of K and reaches 0 when K = m (total number of training data points) which happens when each data point is a part of its own unique cluster. Although we don’t want K = m, but we can go beyond the elbow point depending on the computation power, the amount of data and the complexity of data we have at hand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*WMYZon_Yq0vEsiLpa_RISg.png" /><figcaption>Elbow Method example (<a href="https://www.researchgate.net/figure/Result-of-the-elbow-method-to-determine-optimum-number-of-clusters_fig8_320986519">Source</a>)</figcaption></figure><h4>Additional Notes</h4><p>So far we’ve discussed about K-means in great detail and I’d like to draw your attention to the point when we just started discussing K-means. I mentioned that one of the limitations of K-means is that it doesn’t capture all the clusters automatically and needs an explicit value for the number of clusters. This however, can also be put to an advantage. Consider a dataset where we need to find clusters for a task such as market segmentation but the data points are uniformly scattered. An algorithm that captures clusters automatically has a higher chance of failing in such a scenario. But through the explicit number of clusters supplied to K-means, we can expect the algorithm to come up with good groupings which even humans can’t find. This is the beauty of K-means.</p><p>Another important thing to note about K-means is that K-means results in linear separation of clusters. This may come as a surprise but there is nothing to worry about. The clusters (the squiggly shapes drawn by hand around a set of data points to represent clusters) are still very much the same as we’ve portrayed them so far. The image below will make things clearer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*B95zxiYtSJKTF8kEpbD7dw.png" /><figcaption>Linear separation of clusters (<a href="https://aws.amazon.com/blogs/machine-learning/k-means-clustering-with-amazon-sagemaker/">Source</a>)</figcaption></figure><p>With this, we have come to an end on our discussion of K-means. Now, let’s use an unlabelled Credit Card Dataset from Kaggle and use it to determine the usage pattern of credit cards for different credit card holders.</p><h3>Problem Statement</h3><p>We’ll be using Credit Card Dataset on Kaggle to determine map spending activity. The dataset can be found <a href="https://www.kaggle.com/arjunbhasin2013/ccdata">here</a>. As is the norm, we need to pre-process the data in order to feed it to the K-means algorithm. First of all, let’s read the data into a pandas dataframe.</p><pre>import numpy as np<br>import pandas as pd</pre><pre>import matplotlib.pyplot as plt<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.cluster import KMeans<br>from sklearn.decomposition import PCA<br>import os</pre><pre>for dirname, _, filenames in os.walk(&#39;/kaggle/input&#39;):<br>  for filename in filenames:<br>    print(os.path.join(dirname, filename))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*IlkhtwF-R5zcCgRH80AG0A.png" /></figure><pre>df = pd.read_csv(‘/kaggle/input/ccdata/CC GENERAL.csv’)<br>print(df.shape)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*nHhCpemPJBAUd4JCH70JqQ.png" /></figure><pre>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*SjmCjRRGAWtGflanKYg2ZQ.png" /></figure><p>There are 18 features in the dataset which are difficult to fit inside a single image. But, from the output of df.describe(), we can see that for all the columns/features, the standard deviation is quite high and the min and max values are too far apart with the distribution being skewed towards lower values as can be seen from the 75% mark, mean and max. This means that the given dataset consists of outliers and these outliers need to be dealt with. Simply ignoring the outliers will result in quite a lot of data loss.</p><p>Before we deal with outliers, let’s check for missing values in the data and impute them.</p><pre>df.isna().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*_Lp-dF7MBvoXj0coNeWwng.png" /></figure><p>Only 2 columns have null values. The missing values are small fraction of the entire dataset (1/8950) and (313/8950) and hence can be easily imputed. We’ll impute CREDIT_LIMIT with mean value and since MINIMUM_PAYMENTS is a continuous variable skewed towards the lower side, we can impute it with either the mean or median. It shouldn’t make much of a difference since this the fraction of missing values is quite small. We’ll go with imputing with mean values.</p><pre>df[‘MINIMUM_PAYMENTS’].fillna(df[‘MINIMUM_PAYMENTS’].mean(skipna=True), inplace=True)</pre><pre>df[‘CREDIT_LIMIT’].fillna(df[‘CREDIT_LIMIT’].mean(skipna=True), inplace=True)</pre><p>Now that we’ve taken care of missing values, let’s focus our attention back towards the outliers. Let’s convert the entire dataset’s values to categorical values. As we are interested in finding similarities through clusters, it is a good idea to group values in a particular range and assigning them a category. Later we’ll normalize these category values as well to make sure that no large value in any column dominates/skews the clustering result.</p><pre>columns = [&#39;BALANCE&#39;, &#39;PURCHASES&#39;, &#39;ONEOFF_PURCHASES&#39;, &#39;INSTALLMENTS_PURCHASES&#39;, &#39;CASH_ADVANCE&#39;, &#39;CREDIT_LIMIT&#39;,&#39;PAYMENTS&#39;, &#39;MINIMUM_PAYMENTS&#39;] # All features with outlandish values</pre><pre>for c in columns:<br>  Range = c+&#39;_RANGE&#39;<br>  df[Range]=0<br>  df.loc[((df[c]&gt;0)&amp;(df[c]&lt;=500)),Range]=1<br>  df.loc[((df[c]&gt;500)&amp;(df[c]&lt;=1000)),Range]=2<br>  df.loc[((df[c]&gt;1000)&amp;(df[c]&lt;=3000)),Range]=3<br>  df.loc[((df[c]&gt;3000)&amp;(df[c]&lt;=5000)),Range]=4<br>  df.loc[((df[c]&gt;5000)&amp;(df[c]&lt;=10000)),Range]=5<br>  df.loc[((df[c]&gt;10000)),Range]=6</pre><pre>columns=[&#39;BALANCE_FREQUENCY&#39;, &#39;PURCHASES_FREQUENCY&#39;, &#39;ONEOFF_PURCHASES_FREQUENCY&#39;, &#39;PURCHASES_INSTALLMENTS_FREQUENCY&#39;, &#39;CASH_ADVANCE_FREQUENCY&#39;, &#39;PRC_FULL_PAYMENT&#39;]</pre><pre>for c in columns:<br>  Range=c+&#39;_RANGE&#39;<br>  df[Range]=0<br>  df.loc[((df[c]&gt;0)&amp;(df[c]&lt;=0.1)),Range]=1<br>  df.loc[((df[c]&gt;0.1)&amp;(df[c]&lt;=0.2)),Range]=2<br>  df.loc[((df[c]&gt;0.2)&amp;(df[c]&lt;=0.3)),Range]=3<br>  df.loc[((df[c]&gt;0.3)&amp;(df[c]&lt;=0.4)),Range]=4<br>  df.loc[((df[c]&gt;0.4)&amp;(df[c]&lt;=0.5)),Range]=5<br>  df.loc[((df[c]&gt;0.5)&amp;(df[c]&lt;=0.6)),Range]=6<br>  df.loc[((df[c]&gt;0.6)&amp;(df[c]&lt;=0.7)),Range]=7\<br>  df.loc[((df[c]&gt;0.7)&amp;(df[c]&lt;=0.8)),Range]=8<br>  df.loc[((df[c]&gt;0.8)&amp;(df[c]&lt;=0.9)),Range]=9<br>  df.loc[((df[c]&gt;0.9)&amp;(df[c]&lt;=1.0)),Range]=10</pre><pre>columns=[&#39;PURCHASES_TRX&#39;, &#39;CASH_ADVANCE_TRX&#39;]</pre><pre>for c in columns:<br>  Range=c+&#39;_RANGE&#39;<br>  df[Range]=0<br>  df.loc[((df[c]&gt;0)&amp;(df[c]&lt;=5)),Range]=1<br>  df.loc[((df[c]&gt;5)&amp;(df[c]&lt;=10)),Range]=2<br>  df.loc[((df[c]&gt;10)&amp;(df[c]&lt;=15)),Range]=3<br>  df.loc[((df[c]&gt;15)&amp;(df[c]&lt;=20)),Range]=4<br>  df.loc[((df[c]&gt;20)&amp;(df[c]&lt;=30)),Range]=5<br>  df.loc[((df[c]&gt;30)&amp;(df[c]&lt;=50)),Range]=6<br>  df.loc[((df[c]&gt;50)&amp;(df[c]&lt;=100)),Range]=7<br>  df.loc[((df[c]&gt;100)),Range]=8</pre><p>Since we have modified all the exisitng feature names, we can delete the existing feature names.</p><pre>df.drop([&#39;CUST_ID&#39;, &#39;BALANCE&#39;, &#39;BALANCE_FREQUENCY&#39;, &#39;PURCHASES&#39;, &#39;ONEOFF_PURCHASES&#39;, &#39;INSTALLMENTS_PURCHASES&#39;, &#39;CASH_ADVANCE&#39;, &#39;PURCHASES_FREQUENCY&#39;,  &#39;ONEOFF_PURCHASES_FREQUENCY&#39;, &#39;PURCHASES_INSTALLMENTS_FREQUENCY&#39;, &#39;CASH_ADVANCE_FREQUENCY&#39;, &#39;CASH_ADVANCE_TRX&#39;, &#39;PURCHASES_TRX&#39;, &#39;CREDIT_LIMIT&#39;, &#39;PAYMENTS&#39;, &#39;MINIMUM_PAYMENTS&#39;, &#39;PRC_FULL_PAYMENT&#39; ], axis=1, inplace=True)</pre><pre>X= np.asarray(df)</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*bkXxNnRjhgno64ZFo-Da2Q.png" /></figure><p>We can plot the frequency distribution for all the features. You can check them out in the notebook <a href="https://www.kaggle.com/vardaanbajaj/k-means-to-recognize-credit-card-usage-patterns?scriptVersionId=39202855">here</a>.The above graphs show that the frequencies for lower values are high since most values in the data are small. This is evident from the <strong>minimum, 1st quartile, median 3rd quartile and maximum values</strong> from the data distribution we obtained by <em>df.describe()</em>. This process however took a certain number of trials but didn’t consume much time. Now we normalize all the values to adjust them in the range of 0–1.</p><pre>scaler = StandardScaler()<br>X = scaler.fit_transform(X)</pre><p>Now that we have converted data from continuous to discrete values and brought it down to a particular range, we’ve made sure that we give equal importance to all the features. Now, we can go ahead and apply K-means. Let’s use <strong>Elbow Method</strong> to choose an optimal value of K.</p><pre>clusters = 25<br>cost = []</pre><pre>for i in range(1,clusters):<br>  kmeans = KMeans(i)<br>  kmeans.fit(X)<br>  cost.append(kmeans.inertia_)</pre><pre>plt.plot(cost, ‘ro-’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*xFzwBnGcvCiwwrDtn9xdZQ.png" /></figure><p>We seem to reach an inflection point when K = 6. After this value of K, the cost decreases very slowly.</p><pre>kmeans = KMeans(6)<br>kmeans.fit(X)</pre><pre>labels = kmeans.labels_</pre><p>The output of this step is a ‘cluster’ variable, which contains the cluster number for each record/row of the dataset. Let us add this variable at the end of the dataframe.</p><pre>clusters = pd.concat([df, pd.DataFrame({‘cluster’:labels})], axis=1)</pre><p>In order to visualize the clusters created and see if they’re well-defined, we need to reduce the dimensionality of the data since it’s difficult to visualize n-dimensional data in 2 dimensional space. However, while reducing the dimensionality of the data, we want to make sure that we capture as many features of the original dataset as possible. For this, we use Principal Component Analysis (PCA), which helps us to achieve the objective mentioned above. Follow the next post for an in-depth understanding of PCA.</p><pre>pca = PCA(2)<br>principalComponents = pca.fit_transform(X)<br>x, y = principalComponents[:, 0], principalComponents[:, 1]<br>print(principalComponents.shape)</pre><pre>colors = {0: ‘red’, 1: ‘blue’, 2: ‘green’, 3: ‘yellow’, 4: ‘orange’, 5:’purple’}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*4KU8NxpS8wrUNYWwZ7CGhA.png" /></figure><pre>final_df = pd.DataFrame({‘x’: x, ‘y’:y, ‘label’:labels})<br>groups = final_df.groupby(labels)</pre><p>Finally, we plot all the clusters as various subplots inside a single plot.</p><pre>fig, ax = plt.subplots(figsize=(15, 10))</pre><pre>for name, group <strong>in</strong> groups:<br>  ax.plot(group.x, group.y, marker=&#39;o&#39;, linestyle=&#39;&#39;, ms=5, color=colors[name], mec=&#39;none&#39;)<br>  ax.set_aspect(&#39;auto&#39;)<br>ax.tick_params(axis=&#39;x&#39;,which=&#39;both&#39;,bottom=&#39;off&#39;,top=&#39;off&#39;,labelbottom=&#39;off&#39;)<br>  ax.tick_params(axis= &#39;y&#39;,which=&#39;both&#39;,left=&#39;off&#39;,top=&#39;off&#39;,labelleft=&#39;off&#39;)</pre><pre>ax.set_title(“Customers Segmentation based on their Credit Card usage bhaviour.”)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*El2lniz8hGdzM0YaOHhR-g.png" /></figure><p>The results are decent. We have 6 separate clusters which are well distinguished. We see that the clusters in green can be a part of either yellow and purple clusters if we chose the number of clusters to be 5. Additionally, we can also determine what each cluster means by plotting frequency distributions for each feature in a cluster and then comparing and contrasting these plots. The entire code for this post can be found <a href="https://www.kaggle.com/vardaanbajaj/k-means-to-recognize-credit-card-usage-patterns?scriptVersionId=39202855">here</a>.</p><p>That’s it for this post. We had a detailed look at K-means algorithm in this post. In the <a href="https://towardsdatascience.com/deep-dive-into-principal-component-analysis-fc64347c4d20">next</a> post, we’ll have an in-depth look at Principal Component Analysis, which is one of the most popular and extensively used unsupervised learning algorithms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1adf5c30281b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/machine-learning-vi-unsupervised-learning-k-means-kaggle-dataset-with-k-means-1adf5c30281b">Unsupervised Learning and Deep Dive Into K-Means</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive Into Decision Trees and Random Forest]]></title>
            <link>https://medium.com/data-science/machine-learning-v-decision-trees-random-forest-kaggle-dataset-with-random-forest-3ebfe6d584be?source=rss-168771086803------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ebfe6d584be</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[Vardaan Bajaj]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 21:45:19 GMT</pubDate>
            <atom:updated>2020-07-22T15:36:58.001Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Dive Into Desision Trees and Random Forest</h3><h4>Along with a solved Kaggle Dataset with Random Forest</h4><h3>Contents</h3><p>In this post, we’ll go through:</p><ol><li>Terminology of Decision Trees</li><li>Ways of Measuring Impurity</li><li>CART Algorithm</li><li>Construction of a Decision Tree by hand using CART</li><li>Why choose Random Forest over Decision Trees</li><li>Diversification of Decision Trees in Random Forest</li><li>Improving Titanic Dataset classifier using Random Forest</li></ol><p>In the <a href="https://medium.com/analytics-vidhya/machine-learning-iv-support-vector-machines-kaggle-dataset-with-svms-57d7c885652a">previous</a> post, we went through Support Vector Machines in great detail and also solved fraudulent credit card transaction dataset from Kaggle. In this post, we’ll be looking at 2 more supervised learning algorithms: Decision Trees and Random Forest. After completing this post, we would have pretty much covered all the widely used supervised machine learning algorithms in the industry.</p><h3>Decision Trees</h3><p>The term decision tree is pretty much self-explanatory and its working is similar to a human’s decision making power. How do humans make decisions? First of all, humans define the objective. In machine learning, the objective of a particular task is determined by the dataset. Once humans have a defined objective, they answer various questions/perform various tasks in order to achieve that objective. The first task that is performed to achieve the objective is analogous to the <strong>root node </strong>of the decision tree. It is representative of the objective of the decision tree. The root node branches out to a certain set of options and each of these options have their own set of options. This process perpetuates until we arrive at the final decision. Now, each of these options is analogous to a <strong>decision node</strong> and the final decision is represented by a <strong>leaf node</strong>. In almost all the cases, the root node also acts as a decision node. For huge decision trees, the output of a decision node is a number of decision nodes, except at the deepest level of the tree, where it is the leaf node.</p><p>Decision Tree modelling is a supervised learning algorithm which can be used for both, continuous and discrete valued datasets, both in regression and classification problems. Most commonly, a decision tree is used as a classifier that recursively partitions data into categories. Decision tree is a directed tree i.e. once we reach particular node in the tree, we cannot backtrack to the previous node i.e. <strong>parent nodes</strong> are not accessible from <strong>child nodes</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*HKSgutAzfWu932WzDFMCbA.png" /><figcaption>Decision Tree Example (<a href="https://www.researchgate.net/figure/An-example-of-a-simple-decision-tree_fig2_311614501">Source</a>)</figcaption></figure><p>After seeing the above example of a decision tree, we can see that the algorithm decides that the best question to ask first is the color of the car. All other questions follow some order as well. The order of asking questions is extremely important otherwise the decision tree can become very complex for a simple scenario like the one shown above. How does the decision tree determine the order of questions it needs to ask? The order of questions being asked depends on which question leads to a good split of the data at that level. The split of data at each node happens in a way similar to binary search. At the root node, we have the entire dataset. The root node should split the data into fed to it into 2 or more groups, where the data in each group has similar attributes. Suppose the root node splits data into 3 groups, then these 3 groups will be the 3 children of the root node and each of these 3 nodes will perform this operation of splitting the data, creating more children and this process is carried on for each node until that node has no more splits to make (leaf node), which is the point where predictions are made.</p><p>How does a decision tree decide which question leads to a good split and which question doesn’t? This is quantified by measuring impurity.</p><h3>Impurity</h3><p>The problem of learning an optimal decision tree is NP-Complete, so in order to better mimic the optimal solution, the concept of impurity came into existence. Impurity is a measure of homogeneity of data. Data is said to be pure or homogenous if it only contains a single class. The more the classes in the data, the more impure it is. Each node in the decision tree, except the leaf nodes, contains data which has a potential of splitting into further groups i.e. each node has some sort of impurity related to data. Less impure nodes require less information to describe them and more impure nodes require more information to describe them. Hence, sub-nodes of a node have more purity than their parent nodes.</p><h3>Measuring Impurity</h3><p>There are various methods to measure impurity, but the most commonly used are Information Gain and Gini Index. Let’s look at them one by one.</p><h4>Information Gain</h4><p>Information Gain is used to determine which feature/attribute gives us the maximum information about a class. It is based on the concept of entropy. Entropy in statistics is analogous to entropy in thermodynamics where it signifies disorder. Higher the entropy, more the randomness (i.e. less purity) and it becomes difficult to draw conclusions from the given information. For totally pure data sample i.e. when only one class exists, the entropy is the least (0) and if data is distributed between all the classes equally, then the entropy is the highest (1).</p><p>The binary cross-entropy loss function that we defined for Logistic Regression is quite similar to entropy. For a dataset with ‘c’ different classes, entropy is measured as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*WSakSBfc295qa09KV6i_qQ.png" /><figcaption>Calculating Entropy (<a href="https://www.saedsayad.com/decision_tree.htm">Source</a>)</figcaption></figure><p>where pi represents the fraction of examples in a given class i. In the example in the image above, there are 2 classes so c=2. p(yes) = 9/14 (0.64) and p(no) = 5/14 (0.36). Once entropy for a node is computed, then the information gain of a specific output given a particular feature is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*owNxHYeJdIab2Ng2LNuqog.png" /></figure><p>where S is the output class, A is a particular feature of the dataset and P has the same meaning defined above (for pi). Due to the high computational time of the log function, Gini Index is preferred over information gain for practical purposes.</p><h4>Gini Index</h4><p>Formally, Gini Index measures the probability of a particular variable being wrongly classified when it is randomly chosen. The probability value of 0 means that the variable couldn’t be wrongly classified and it’s possible only when we have only one output class i.e. the data is 100% pure. As the Gini Index value increases, the chances of misclassification of a particular variable increases since the impurity increases. The information conveyed by these values resonate with the entropy values. For a dataset with ‘c’ classes, Gini Index is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*DIEJGcZ3f2XD_MmZu4dKjg.png" /></figure><p>where pi represents the fraction of examples in a given class i, which is similar to the entropy definition.</p><p>There are many more measures of impurity like chi-square, classification error, etc. but the main idea here was to familiarize the readers with impurity measurement methods. One important thing to note here is that these impurity measurement functions play a role analogous to the <strong>cost function</strong>.</p><h3>Constructing Decision Trees</h3><p>Constructing a decision tree is actually partitioning of the input data features, which leads to 2 or more sub-nodes and this process is carried on recursively for each sub-node. Once this tree is created, features have been partitioned throughout the nodes.</p><p>Various decision tree algorithms for classification are compared along the following lines:</p><p>(i) The splitting criteria</p><p>(ii) Techniques to eliminate/reduce overfitting</p><p>(iii) Handling incomplete data</p><p>Some of the various algorithms for decision tree construction are CART, ID3, C4.5, C5.0, CHAID, MARS, etc. In this post, we’ll be discussing CART in great detail. CART is one of the most widely used and a highly effective decision tree algorithm.</p><h3>CART (Classification And Regression Trees)</h3><p>As the name suggests, CART algorithm is used to generate both, classification and regression decision trees. We’ll be focussing on the classification part here. It is used to solve multi-class classification problem (for binary classification, it generates a binary tree) and uses Gini index as a metric to evaluate the split of a feature node in the decision tree.</p><p>In CART algorithm, the <strong>objective is to minimize the cost function (Gini Index)</strong> at each node. The selection of the input variables/features that decides the specific split for each node is selected in a greedy way to minimize the cost function. In this greedy way, a number of split points with different set of variables/features are considered and that split is chosen which results in the minimum value for the Gini Index (i.e. more homogenous splits) at that node. This process is carried out recursively for all sub-nodes in the tree.</p><p>This process can continue on forever and can lead to the formation of many unnecessary sub-nodes, so it needs to be stopped. For this, we count the total number of training examples that pass through each node of the tree. This number is a hyperparameter and is tuned according to the dataset and the optimal choice of this number leads to formation of robust decision trees. To give some intuition, if a node of the tree only has one training example that passes through it, this means that the generated decision tree is suffering from overfitting since it has given so much importance to just one example that it called for its separate node. Such a decision tree needs to reduce its complexity which is achieved using pruning.</p><p><strong>Decision tree pruning</strong> is a technique to reduce the size of a decision tree by removing sections of the tree that provide little power to the classification objective. 2 popular pruning methods are:</p><p>(i) Reduced Error Pruning (bottom-up)</p><p>(ii) Cost complexity pruning (top-down)</p><p>More about these pruning methods can be found <a href="https://en.wikipedia.org/wiki/Decision_tree_pruning">here</a>. Now that we know the underlying logic behind the CART algorithm, let’s see through an example of binary classification, how a decision tree is constructed using CART. Let’s use 10 records of UCI machine learning Zoo Animal Classification dataset to build a decision tree by hand. Given the features “toothed”, “hair”, “breathes”, “legs”, the decision tree should output the species of the animal (mammal/reptile).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*82X22M-nSYiIxeA6lPrIvw.png" /></figure><p>Let’s start with each feature one by one. We observe in the data that all the input features are represented by Boolean values.</p><p>(i) <strong>toothed</strong>: Let’s summarize the output (species) wrt the ‘toothed’ feature values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*6IR4xLAqh2jp4uO9TL0j8Q.png" /></figure><p>Gini Index (toothed = true) = 1 — {(5/8)² + (3/8)²} = 1–0.39–0.14 = 0.47</p><p>Gini Index (toothed = false) = 1 — {(1/2)² + (1/2)²} = 1–0.25 -0.25 = 0.5</p><p>To obtain the final Gini index of ‘species’ wrt ‘toothed’, we use the weighted sum of the above calculated values as:</p><p>Gini Index(toothed) = (8/10) * 0.47 + (2/10) * 0.5 = 0.38 + 0.1 = <strong>0.48</strong></p><p>(ii) <strong>hair</strong>: Let’s summarize the output (species) wrt the ‘hair’ feature values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*yo83AmZv-7-c60Xt4IlT6A.png" /></figure><p>Gini Index(hair = true) = 1 — {(5/5)² + (0/5)²} = 1–1–0 = 0</p><p>Gini Index(hair = false) = 1 — {(1/5)² + (4/5)²} = 1–0.04–0.64 = 0.32</p><p>To obtain the final Gini index of ‘species’ wrt ‘hair’, we use the weighted sum of the above calculated values as:</p><p>Gini Index(hair) = (5/10) * 0 + (5/10) * 0.32 = <strong>0.16</strong></p><p>(iii) <strong>breathes</strong>: Let’s summarize the output (species) wrt the ‘breathes’ feature values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*CCIzGCq2rxfkcIUnyD7mlw.png" /></figure><p>Gini Index (breathes = true) = 1 — {(6/9)² + (3/9)²} = 1–0.45–0.11 = 0.44</p><p>Gini Index (breathes = false) = 1 — {(0/1)² + (1/1)²} = 1–0–1 = 0</p><p>To obtain the final Gini index of ‘species’ wrt ‘breathes’, we use the weighted sum of the above calculated values as:</p><p>Gini Index(breathes) = (9/10) * 0.44 + (1/10) * 0 = <strong>0.40</strong></p><p>(iv) <strong>legs</strong>: Let’s summarize the output (species) wrt the ‘legs’ feature values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*wotFOA78Rp3NmWzgnhR2_A.png" /></figure><p>Gini Index (legs = true) = 1 — {(6/7)² + (1/7)²} = 1–0.73–0.02 = 0.25</p><p>Gini Index (breathes = false) = 1 — {(0/3)² + (3/3)²} = 1–0–1 = 0</p><p>To obtain the final Gini index of ‘species’ wrt ‘legs’, we use the weighted sum of the above calculated values as:</p><p>Gini Index(breathes) = (7/10) * 0.25 + (3/10) * 0 = <strong>0.18</strong></p><p>Now that we have calculated Gini Index for the output variable against all 4 input features, we need to choose the root node. The root node is chosen such that it has minimum Gini Index. The lower the Gini Index, the higher the chances of predicting the answer early (due to more purity of the node). So here, we choose <strong>hair</strong> as the root node. The decision tree at this point looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*MRVOZIazbU5LZ2pVh3rdnw.png" /></figure><p>Let’s first consider the case when ‘hair’ takes the values of TRUE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*u6-M5xa1RbAH-j16if7CNQ.png" /></figure><p>Let’s calculate Gini Index for the output against the input features excluding the <strong>hair</strong> feature, when hair takes the value of TRUE.</p><p>(i) <strong>toothed</strong>: Let’s summarize the output (species) wrt the ‘toothed’ feature values when hair = TRUE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*MCyIeBRQ57Jg4lIna34ZdA.png" /></figure><p>Gini Index (hair = true &amp; toothed = true) = 1 — {(4/4)² + (0/4)²} = 1–1–0 = 0</p><p>Gini Index (hair = true &amp; toothed = false) = 1 — {(1/1)² + (0/1)²} = 1–1–0 = 0</p><p>To obtain the final Gini index of ‘species’ wrt ‘toothed’ for ‘hair=true’, we use the weighted sum of the above calculated values as:</p><p>Gini Index (toothed &amp; hair = true) = (4/5) * 0 + (1/5) * 0 = 0 + 0 = <strong>0</strong></p><p>(ii) <strong>breathes</strong>: Let’s summarize the output (species) wrt the ‘breathes’ feature values when hair = TRUE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*g6XEZHF8mIInbwra-0k34g.png" /></figure><p>Gini Index (hair = true &amp; breathes = true) = 0</p><p>Gini Index (hair = true &amp; breathes = false) = 0</p><p>To obtain the final Gini index of ‘species’ wrt ‘breathes’ for ‘hair=true’, we use the weighted sum of the above.</p><p>Gini Index (breathes &amp; hair = true) = <strong>0</strong></p><p>(iii) <strong>legs</strong>: Let’s summarize the output (species) wrt the ‘legs feature values when hair = TRUE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*hR5zILKQmAHH_Wrh15i8Ug.png" /></figure><p>Gini Index (hair = true &amp; legs = true) = 0</p><p>Gini Index (hair = true &amp; legs = false) = 0</p><p>To obtain the final Gini index of ‘species’ wrt ‘legs’ for ‘hair=true’, we use the weighted sum of the above.</p><p>Gini Index (legs &amp; hair = true) = <strong>0</strong></p><p>In all the above cases, the Gini Index is equal to 0. This means that if we predict that the species has hair, it can be classified as a ‘mammal’ based on the given dataset with high confidence. At this point, the decision tree looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*rBlWnnoL87H3z6nbfqR5aA.png" /></figure><p>Now, let’s consider the case when ‘hair’ takes the values of FALSE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*UpczqIfuPgdJFW55c9Epug.png" /></figure><p>Let’s calculate Gini Index for the output against the input features excluding the <strong>hair</strong> feature, when hair takes the value of FALSE.</p><p>(i) <strong>toothed</strong>: Let’s summarize the output (species) wrt the ‘toothed’ feature values when hair = FALSE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*wCimLf-5ALYAeSxShGn0PA.png" /></figure><p>Gini Index (hair = false &amp; toothed = true) = 1 — {(1/4)² + (3/4)²} = 1–0.06–0.56 = 0.38</p><p>Gini Index (hair = false &amp; toothed = false) = 1 — {(0/1)² + (1/1)²} = 1–0–1 = 0</p><p>To obtain the final Gini index of ‘species’ wrt ‘toothed’ for ‘hair=false’, we use the weighted sum of the above calculated values as:</p><p>Gini Index (toothed &amp; hair = false) = (4/5) * 0.38 + (1/5) * 0 = 0.3 + 0 = <strong>0.3</strong></p><p>(ii) <strong>breathes</strong>: Let’s summarize the output (species) wrt the ‘breathes’ feature values when hair = FALSE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*3AmgMPu4Ju9zP4vAVWhFOg.png" /></figure><p>Gini Index (hair = false &amp; breathes = true) = 1 — {(1/4)² + (3/4)²} = 1–0.06–0.56 = 0.38</p><p>Gini Index (hair = false &amp; breathes = false) = 1 — {(0/1)² + (1/1)²} = 1–0–1 = 0</p><p>To obtain the final Gini index of ‘species’ wrt ‘breathes’ for ‘hair=false’, we use the weighted sum of the above calculated values as:</p><p>Gini Index (breathes &amp; hair = false) = (4/5) * 0.38 + (1/5) * 0 = 0.3 + 0 = <strong>0.3</strong></p><p>(iii) <strong>legs</strong>: Let’s summarize the output (species) wrt the ‘legs’ feature values when hair = FALSE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*pLu_lw52LRmlq2kgTahAkA.png" /></figure><p>Gini Index (hair = false &amp; legs = true) = 1 — {(1/2)² + (1/2)²} = 1–0.25–0.25 = 0.5</p><p>Gini Index (hair = false &amp; legs = false) = 1 — {(0/3)² + (3/3)²} = 1–0–1 = 0</p><p>To obtain the final Gini index of ‘species’ wrt ‘legs’ for ‘hair=false’, we use the weighted sum of the above calculated values as:</p><p>Gini Index (toothed &amp; hair = false) = (2/5) * 0.5 + (3/5) * 0 = 0.2 + 0 = <strong>0.2</strong></p><p>In the above 3 cases, we see that the Gini Index is minimum for the ‘legs’ feature given the condition ‘hair=FALSE’. So, ‘legs’ is chosen as the child node when ‘hair=FALSE’. At this point, the decision tree looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*Z_6lvbrLp7HCiGc9QSx1Fw.png" /></figure><p>To proceed further, let us consider the cases when legs = TRUE (hair = FALSE is implied now).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*cFISlIHv4zSSCbRAN4zA6A.png" /></figure><p>Let’s calculate Gini Index for the output against the input features excluding the <strong>hair </strong>and <strong>legs</strong> feature, when hair takes the value of FALSE and legs takes the value of TRUE.</p><p>(i) <strong>toothed</strong>: Let’s summarize the output (species) wrt the ‘toothed’ feature values when hair = FALSE and legs = TRUE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*hAiFz4fCnAKX5D_MjYWZsA.png" /></figure><p>Gini Index (hair = false &amp; legs = true &amp; toothed=true) = 0</p><p>Gini Index (hair = false &amp; legs = true &amp; toothed=false) = 0</p><p>To obtain the final Gini index of ‘species’ wrt ‘toothed’ for ‘hair=false’ and legs=’true’, we use the weighted sum of the above.</p><p>Gini Index (toothed &amp; hair = false &amp; legs = true) = <strong>0</strong></p><p>(ii) <strong>breathes</strong>: Let’s summarize the output (species) wrt the ‘breathes’ feature values when hair = FALSE and legs = TRUE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*72N1cg52LHPscJAc9LofAw.png" /></figure><p>Gini Index (hair = false &amp; legs = true &amp; breathes=true) = 1 — {(1/2)² + (1/2)²} = 1–0.25–0.25 = 0.5</p><p>Gini Index (hair = false &amp; legs = true &amp; breathes=false) = 0</p><p>To obtain the final Gini index of ‘species’ wrt ‘toothed’ for ‘hair=false’ and legs=’true’, we use the weighted sum of the above.</p><p>Gini Index (toothed &amp; hair = false &amp; legs = true) = (2/2) * 0.5 + (0/2) * 0 = <strong>0.5</strong></p><p>In the above 2 cases, we see that ‘toothed’ has lower Gini Index, so it is selected as a child node when ‘legs = TRUE’. The decision tree now looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*AabsJYkfu7S1zxqcFb5aSw.png" /></figure><p>Now, let’s consider the case when ‘legs’ takes the value of FALSE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*nHYcV_nCgxGeZ1fqr-JFFg.png" /></figure><p>From the above scenario, we can clearly see that when ‘hair = TRUE’ and ‘legs = FALSE’, the output ‘species’ is ‘Reptile’ in all the cases. Hence, we without calculating the Gini Index, we can safely conclude that the child node produced for the decision tree will be a leaf node with the value ‘Reptile’. (Remember that when we just considered ‘hair = TRUE’ case, we saw that all the output ‘species’ values were ‘Mammals’ and by calculating Gini Index, we directly produced a leaf node with the value ‘Mammal’)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*70RdyN-98VGIzxFNgGQVSA.png" /></figure><p>Proceeding further, let’s consider the case when ‘toothed = TRUE’. Here, the cases ‘hair = FALSE’ and ‘legs = TRUE’ are implied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*bgp_T2mi1W2t5_0oxZ2B3g.png" /></figure><p>Here, we only have one record which is classified as mammal. Hence, this combination of features results in the output ‘species’ being a ‘Mammal’.</p><p>Considering the case ‘toothed = FALSE’, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*a0po871nS80fCLDWka_JhQ.png" /></figure><p>In a similar way, we can conclude that the output ‘species’ for this set of features is a ‘Reptile’. Now, we have finally constructed the decision tree on which we can throw some test data to make predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*7MiRauQH1A-QGMmhtL5TjQ.png" /></figure><p>If you’ve followed carefully so far, you may have observed that all the variables in this dataset were categorical variables (i.e. the features had a finite set of distinct values (2) like TRUE and FALSE). In the datasets that you encounter in <strong>real life have a mixture of categorical and continuous variables</strong>. In order to construct decision trees from a dataset having continuous values, these continuous values are converted to categorical values by defining a certain threshold. Using this, decision trees can be constructed for any type of data.</p><h3>Why Not to Use Decision Trees</h3><p>Although decision trees are quite intuitive and simple to create, they suffer from the following drawbacks.</p><p>1. They are unstable, meaning that a small change in the data can lead to a large change in the structure of the optimal decision tree.</p><p>2. Calculations can get very complex, particularly if many values are uncertain and/or if many outcomes are linked.</p><p>3. Decision Trees tend to overfit to the training data very quickly and can become very inaccurate.</p><h3>Random Forest</h3><p>Due to the aforementioned disadvantages of Decision Trees, Random Forest algorithm is used instead of Decision Trees. Random Forest algorithm employs the use of a large number of decision trees that operate as an <a href="https://en.wikipedia.org/wiki/Ensemble_learning">ensemble</a>. A machine learning ensemble consists of only a concrete finite set of alternative models, but typically allows for much more flexible structure to exist among those alternatives.</p><p>Random Forest algorithm is based on the concept of <strong>The Wisdom of Crowds</strong>. Wisdom of Crowds is a very effective technique employed in various tasks of computer science. The fact that Wikipedia (fully crowdsourced, editable by everyone) and Britannica (fully written by experts) have been found to have similar levels of quality standards is a testament to the power of the wisdom of crowds. Every individual in the crowd makes their prediction with a certain error. Since all the individuals act independently, their errors are also independent to each other’s. In other words, these errors are <strong>uncorrelated </strong>i.e. when considered in a bunch, these errors cancel each other out and what we’re left with is a good, accurate prediction. This is the way how Random Forest algorithm operates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*Lsg3CDtqE4Y-faLM1ytwpA.png" /><figcaption>Random Forest Simplified (<a href="https://en.wikipedia.org/wiki/Random_forest">Source</a>)</figcaption></figure><h3>Working of Random Forest Algorithm</h3><p>Random Forest algorithm uses a large number of decision trees (creating a <strong>forest</strong>), which are independent of/uncorrelated to each other, from a given dataset, which collectively outperform any of its constituent trees. This little to no correlation between the constituent trees in the forest imparts the element of <strong>random</strong>ness to this ensemble method, which produces a wonderful effect of protecting trees from each other for their individual errors. But we need to make sure that the outputs of the various decision trees that we make randomly for random forest to work should not be completely random. In order to ensure this, we need to make sure that:</p><p>(i) The output should be dependent on all the training features and not only some of them in order to make random decision trees effective.</p><p>(ii) The predictions made by each decision tree should have low correlations with each other in order to make the wisdom of crowds concept to work.</p><p>The first point is the feature of the dataset that we collect. So, as a data scientist, how do we make sure that the constituent decision trees are as diversified as possible? For this, random forest uses the following 2 techniques:</p><p>(i) Bagging</p><p>(ii) Feature Randomness</p><h4>Bagging</h4><p>One of the major drawbacks of Decision Trees was that they were not robust to even small changes in the data which made them prone to overfitting. Let’s understand how bagging solves this problem. Consider a training dataset with <strong>M</strong> ( &gt;&gt; 50) training examples and for simplicity let’s consider these are M numbers in the range of 1 to 50. If we want to use <strong>B</strong> decision trees for Random Forest, then through bagging, each of the B decision trees is made up of M training examples, but instead of using all the M training examples, a random subset of these training examples (here numbers in the range from 1 to 50) is used and numbers from this subset are randomly repeated until a total of M training examples are created.</p><p>How does bagging help? By creating a large number of decision trees with a large number of training examples distributed randomly across decision trees, the aggregate result is a random forest model which is robust to even small changes in the data, thereby eliminating one of the major disadvantages of decision trees (by using decision trees).</p><h4>Feature Randomness</h4><p>The idea of using random training examples can also be applied to the features of the training data. Recall that while constructing decision trees, when deciding the split at each node, we take all the features into account. If the training dataset has <strong>N</strong> features, then in feature randomness, while creating each of the B decision trees, the decision of splitting a node is made by using a random subset of these N features instead of using all N features.</p><p>When both bagging and feature randomness are used to make a forest of decision trees for random forest, <strong>each of the decision trees constitutes of a random subset of training examples as well as a random subset of features</strong>. This randomness adds a lot of robustness and stability to a Random Forest classifier by ensuring the formation of uncorrelated decision trees that protect each other from their errors. Once all these constituent decision trees make a prediction, majority voting takes place in order to get the final prediction of the classifier.</p><p>We’ve looked at a lot of concepts so far. From the mathematics behind decision trees to creating a decision tree by hand and then seeing how decision trees are used in random forest, we’ve come a long way. Now is the time that we get hands on practice for a Random Forest classifier and for this post, we won’t be dealing with a new dataset, instead we’ll be improving upon our Logistic Regression model which we trained over the Titanic dataset in this post. This is the way actual machine learning tasks are carried out. Various machine learning models are tried and the one that works the best and justifies the results obtained is used in practice. Remember, persistence is the key. So let’s get started.</p><h3>Problem Statement</h3><p>The dataset for the Titanic problem can be found <a href="https://www.kaggle.com/c/titanic/data">here</a>. We have to predict whether a passenger on the Titanic will survive or not given the data corresponding to them. We have already applied data pre-processing and logistic regression in <a href="https://medium.com/analytics-vidhya/machine-learning-ii-logistic-regression-explained-data-pre-processing-hands-on-kaggle-728e6a9d4bbf">this</a> post. Now, we will use the same pre-processed data from the previous post, but will apply Random Forest classification this time. Dataset after pre-processing looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*G8pgG7vnb0yyzevPd6o2Kg.png" /></figure><p>After applying <strong>recursive feature elimination(RFE)</strong>, we obtain the top 8 most important features that will help in training the Random Forest Classifier. More on RFE can be found <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFE.html">here</a>.</p><pre>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.feature_selection import RFE</pre><pre>cols = [“Age”, “SibSp”, “Parch”, “Fare”, “Pclass_1”, “Pclass_2”, “Pclass_3”, “Embarked_C”, “Embarked_Q”, “Embarked_S”, “Sex_male”]</pre><pre>X = final_train[cols]<br>y = final_train[‘Survived’]</pre><pre>model = RandomForestClassifier()</pre><pre><em># selecting top 8 features<br></em>rfe = RFE(model, n_features_to_select = 8)<br>rfe = rfe.fit(X, y)</pre><pre>print(‘Top 8 most important features: ‘ + str(list(X.columns[rfe.support_])))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*mU8YcmSpGuJtUUMqvK24Ig.png" /></figure><p>Now that we have the list of features we should use for training the classifier, let us apply Random Forest classifier on the dataset. Unlike Logistic Regression, Random Forest has a large number of parameters that need to be fed into the model. The most important parameters are:</p><p>1. n_estimators = number of trees in the foreset</p><p>2. max_features = max number of features considered for splitting a node</p><p>3. max_depth = max number of levels in each decision tree</p><p>4. min_samples_split = min number of data points placed in a node before the node is split</p><p>5. min_samples_leaf = min number of data points allowed in a leaf node</p><p>6. bootstrap (like bagging) = method for sampling data points (with or without replacement)</p><p>These are a lot of parameters and it is difficult to obtain their optimal value together manually. So, we make use of the computation power by passing the model a set of values for each parameter, the parameter applies these values to the dataset and chooses the best ones. For this dataset, this took me about 5 minutes to get optimal values using Random Hyperparameter Grid technique.</p><pre><em># Number of trees in random forest<br></em>n_estimators = [int(x) for x <strong>in</strong> np.linspace(start = 200, stop = 2000, num = 10)]</pre><pre><em># Number of features to consider at every split<br></em>max_features = [&#39;auto&#39;, &#39;sqrt&#39;]</pre><pre><em># Maximum number of levels in tree<br></em>max_depth = [int(x) for x <strong>in</strong> np.linspace(10, 110, num = 11)]<br>max_depth.append(None)</pre><pre><em># Minimum number of samples required to split a node<br></em>min_samples_split = [2, 5, 10]</pre><pre><em># Minimum number of samples required at each leaf node<br></em>min_samples_leaf = [1, 2, 4]</pre><pre><em># Method of selecting samples for training each tree (bagging)<br></em>bootstrap = [True, False]</pre><pre><em># Creating random grid<br></em>random_grid = {&#39;n_estimators&#39;: n_estimators, &#39;max_features&#39;: max_features, &#39;max_depth&#39;: max_depth, &#39;min_samples_split&#39;: min_samples_split, &#39;min_samples_leaf&#39;: min_samples_leaf, &#39;bootstrap&#39;: bootstrap}</pre><p>On each iteration, the algorithm will choose a difference combination of the features. Altogether, there are 2 * 12 * 2 * 3 * 3 * 10 = 4320 settings! However, the benefit of a random search is that we are not trying every combination, but selecting at random to sample a wide range of values.</p><pre><em># First create the base model to tune<br></em>rf = RandomForestClassifier()</pre><pre><em># Random search of parameters, using 3 fold cross validation,<br># search across 100 different combinations, and use all available cores</em></pre><pre>rf_random = RandomizedSearchCV(estimator = rf, param_distributions = random_grid, n_iter = 100, cv = 3, verbose=2, random_state=42, n_jobs = -1)</pre><pre><em># Fit the random search model<br></em>rf_random.fit(final_train[selected_features], final_train[&#39;Survived&#39;])<br>rf_random.best_params_</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*SOwGtL0eaC9BafJO68rgRw.png" /></figure><p>Now that we have an optimal set of parameters from the given range supplied to the algorithm, let’s train the random forest classifier, both with default values that sci-kit learn provides and with the values we obtained.</p><pre>X = final_train[selected_features]<br>y = final_train[&#39;Survived&#39;]</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=2)</pre><pre><em># fitting both base random forest model and RandomizedSearchCV random forest model<br></em>base_model = RandomForestClassifier()<br>base_model.fit(X_train, y_train)</pre><pre>best_random = RandomForestClassifier(n_estimators = 2000, min_samples_split= 5, min_samples_leaf = 1, max_features = &#39;sqrt&#39;, max_depth = 100, bootstrap = True)</pre><pre>best_random.fit(X_train, y_train)</pre><p>Now that we have trained these models, let’s evaluate them using the evaluation function defined below.</p><pre>def evaluate(model, test_features, test_labels):<br>  predictions = model.predict(test_features)<br>  errors = abs(predictions - test_labels)<br>  accuracy = accuracy_score(test_labels, predictions) * 100<br>  print(&#39;Model Performance&#39;)<br>  print(&#39;Average Error: <strong>{:0.4f}</strong> degrees.&#39;.format(np.mean(errors)))<br>  print(&#39;Accuracy = <strong>{:0.2f}</strong>%.&#39;.format(accuracy))</pre><pre>  return accuracy</pre><pre>base_accuracy = evaluate(base_model, X_test, y_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*FkRUj8XRTlNCGFBiO91Axg.png" /></figure><pre>random_accuracy = evaluate(best_random, X_test, y_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*d4HkoWcHFB33oivWeSdqVQ.png" /></figure><p>We observe that the base model had a test accuracy of 84.33% whereas the model in which we fed the parameters obtained RandomizedSearchCV yielded test accuracy of 81.34%, which should have been higher than the base model’s accuracy. This can be due to the fact that the training dataset was not big enough or the values we supplied for random search to choose from might have included the range of optimal values. We can definitely toy around with it to improve our accuracy though.</p><p>Similarly, I also applied GridSearchCV to check for the accuracy of the classifier which was again around 81%. The relatively low accuracy might be due to the reasons posited above.</p><p>But, the key takeaway from this exercise is that we improved our model’s accuracy on the test set from 77.6% using Logistic Regression to around 84% using Random Forest algorithm, which indeed justified our discussion of Random Forest algorithm above. When I submitted the results of this model on Kaggle, I received a public score of 0.7751, which is better than the score we received for Logistic Regression classifier (0.7703), although not by much, but good enough to take a step forward to improve an already existing robust classifier.</p><p>The entire code for this post can be found <a href="https://www.kaggle.com/vardaanbajaj/titanic-random-forest">here</a>.</p><p>That’s it for this post. In all the posts so far, we have explored the most frequently used supervised machine learning algorithms in great detail. From the <a href="https://towardsdatascience.com/machine-learning-vi-unsupervised-learning-k-means-kaggle-dataset-with-k-means-1adf5c30281b">next</a> post onwards, we’ll dive deep into the basics of Unsupervised Learning and also learn about various unsupervised learning algorithms, starting with K-means clustering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ebfe6d584be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/machine-learning-v-decision-trees-random-forest-kaggle-dataset-with-random-forest-3ebfe6d584be">Deep Dive Into Decision Trees and Random Forest</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive Into Support Vector Machines]]></title>
            <link>https://medium.com/data-science/machine-learning-iv-support-vector-machines-kaggle-dataset-with-svms-57d7c885652a?source=rss-168771086803------2</link>
            <guid isPermaLink="false">https://medium.com/p/57d7c885652a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[kaggle]]></category>
            <dc:creator><![CDATA[Vardaan Bajaj]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 10:07:34 GMT</pubDate>
            <atom:updated>2020-07-23T20:58:44.732Z</atom:updated>
            <content:encoded><![CDATA[<h4>Along with a solved Kaggle Dataset with SVMs</h4><h3>Contents</h3><p>In this post, we’ll go through:</p><p>(i) Role of Support Vectors in SVMs</p><p>(ii) Cost Function for SVMs</p><p>(iii) SVMs as a Large Margin Classifier</p><p>(iv) Non-Linear Decision Boundaries through SVMs with the help of Kernels</p><p>(v) Fraudulent Credit Card Transaction Kaggle Dataset Detection using SVMs</p><p>In the <a href="https://medium.com/analytics-vidhya/contents-9b2e49f49fe9">previous</a> post, we had a good look at high bias and variance problems in machine learning and discussed how regularization plays a big role in solving these issues along with some other techniques. In this post, we’ll be having a detailed look at another supervised learning algorithm called the Support Vector Machine. Later in the post, we’ll be solving a Kaggle dataset to detect Fraudulent Credit Card Transactions using the SVM.</p><h3>Support Vector Machines (SVM)</h3><p>SVM is a supervised machine learning method which solves both, regression and classification problems. However, it is mostly used in classification problems where it constructs hyperplanes in the n-feature dimensions. An n-dimension feature space has a hyperplane of n-1 dimensions. Eg. In the dataset with 2 features (2-dimeansional feature space), the hyperplane constructed by the SVM is a curve(line, circle, etc.) If we are solving a classification problem on 2 classes, then the job of the SVM classifier is to find the hyperplane that maximizes the margin between the 2 classes. Before we look at how SVMs work, let’s understand where the name Support Vector Machine came from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b8pYGw735O3wMpox.png" /><figcaption>SVM in action (<a href="https://en.wikipedia.org/wiki/Support_vector_machine#/media/File:SVM_margin.png">Source</a>)</figcaption></figure><h3>What is a Support Vector?</h3><p>We know that an SVM classifier constructs hyperplanes for classification. But how does the SVM classifier construct a hyperplane? Let’s develop intuition by considering just 2 classes. We know that a hyperplane has to pass from somewhere in the middle of the 2 classes. A good separation between these classes is achieved by the hyperplane that has the largest distance to the nearest training data points from both the classes. In the figure alongside, the 2 dotted lines that mark the extremes of each class constitute the support vectors for each class. These support vectors help in finding the hyperplane that maximizes the distance (margin) of the hyperplane from each of the 2 classes with the help of their support vectors.</p><h3>Working of SVMs</h3><p>Support Vector Machines can fit both linear and non-linear decision boundaries as a classifier and one of the main advantages SVMs have over Logistic Regression is that they compute the training parameters fast due to a much simplified cost function.</p><p>Cost Function</p><p>Let’s recall the binary crossentropy cost function used for binary classification in logistic regression. Here, for the sake of simplification, we’ll ignore the bias term, so the final prediction that we make for the ith training example out of a total of ‘m’ training examples through logistic regression will be represented as h(x(i)) = sigmoid(W * x(i))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*NZXE7Wg4hRTrGQ_e2SPSPw.png" /></figure><p>This cost function can be divided into 2 parts: when y(i) = 1 the term (1 — y(i))*log(1 — h(x(i))) becomes 0 and when y(i) = 0, the term y(i)*log(h(x(i))) becomes 0. The corresponding graphs for these equations (Cost vs W * x) (excluding the regularization term, since it is common to both) are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*6wvjFQYaiBULyMwwQWVhag.png" /></figure><p>SVM uses a slight modification of this cost function which provides it computational advantages over logistic regression. For the case y = 1, we see that the cost function has all its values closer to 0 when W * x &gt;= 1 and when W * x &lt; 1, the -log(h(x)) function values are approximated by a straight line by calculating the derivative of the cost function when W * x = 0. Similarly for the case y = 0, we see that the cost function has all its values closer to 0 when W * x &lt;= -1 and when W * x &gt; 1, the -log(1 — h(x)) values are approximated by a straight line by calculating the derivative of the cost function when W * x = 0.</p><p>Now since we are no longer using logarithmic cost function, let’s rename the log part in the logistic regression cost function. Let’s replace <strong>-log(h(x)) with cost1(h(x)) </strong>and <strong>-log(1 — h(x)) with cost0(h(x))</strong>. We’re ignoring the constant (1/m) here as it doesn’t affect our minimization objective and helps us to simplify our calculations. So, the final cost function for support vector machine looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*7GOR000vxql-oL09pR-KjA.png" /></figure><p>This leads to the following mathematical equation for the cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*LuYXtM0VC2Qz8RGrMdTdjw.png" /></figure><p>Unlike logistic regression which outputs probability values, SVMs output 0/1. When h(x) &gt;=1, the SVM outputs 1 and when h(x) &lt;= -1, the SVM outputs 0. In logistic regression, we saw that when h(x) &gt; 0, the output was a probability &gt; 0.5, which was rounded-off to 1 and when h(x) &lt; 0, the output was a probability &lt; 0.5 which was rounded-off to 0. The range of (-1, 1) is an <em>extra safety margin factor </em>which allows SVMs to make more confident predictions than logistic regression.</p><p>Let us now re-parameterize the cost function a bit. Currently our cost function is of the form A + λ*B, where A is the cost function and B is the regularization term. Let’s convert it to C*A + B form, where C plays a role similar to 1/λ.</p><h3>SVM as a Large Margin Classifier</h3><p>Earlier, we read about the role of support vectors in finding a hyperplane that acts as a classifier which is at a maximum distance from each of the 2 classes. Such a classifier is known as a <strong>Large Margin Classifier</strong>. A large margin classifier is the one which predicts the classes for given data points with greater confidence. This was not the case with logistic regression. Let’s see why this happens with SVM.</p><p>We re-parameterized the SVM cost function to <strong>C*A + B</strong>, where <strong>A </strong>is the loss associated with the SVM output (the cost component), <strong>B </strong>is the regularization term (regularization component) and <strong>C </strong>plays a role similar to 1/λ. When we choose <strong>C</strong> to be very large, then our model will be prone to overfitting. To counter this, we would want that <strong>A </strong>should be close zero otherwise there would be a huge cost which is undesirable. Since the value of <strong>A </strong>is directly proportional to the parameter W (represented by ‘theta’ in figures), this means that the parameters themselves will have very small values. So, in case of large C, the optimization objective is simply to find the minimum value of the training parameters present in <strong>B</strong>. Formally defining, the minimization objective in this case is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*QVs8yB9nUk-hfUf8ff4QBQ.png" /></figure><p>In the implementation of SVMs, vectorization is used and the dot product of vector W (‘theta in figure’) and the vector of features (X) is computed. From the knowledge of multiplication of matrices, we know that when dot product of 2 vectors (let’s say <strong>u</strong> and <strong>v</strong>) is computed, we get the projection of vector <strong>u </strong>on the vector <strong>v</strong>. In the same way, when dot product of W and X is computed, we get the <strong>projection of the vector X on W</strong> and the length of projection (<strong>P</strong>) is equal to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/91/1*gsR3B02dFx2O_c_5F8ZY5w.png" /></figure><p>where ||thetha|| is the L2 norm of theta. This equation can be represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/1*Yu3HW5e-CwMo3Ec_xwA_0w.png" /></figure><p>So, the minimization objective can be rephrased as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*NVuXgyGxvNGZloeQ-Hp9vw.png" /></figure><p>Now let’s take an example to see how this minimization objective leads to a large margin classifier in SVM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*glK4d8zfxiCJfq1DH5tM0A.png" /></figure><p>Consider the following binary classification problem where ‘X’ represents the feature x1 and the ‘O’ represents the feature x2. From our current optimization objective we know that the SVM minimizes the cost function only when p.||theta|| &lt;= -1 for y = 0 (x1) and p.||theta|| &gt;= 1 for y = 1 (x2) i.e. the angle between the projection of a training example and the vector of parameters is either between 900–1800 and 2700–3600 respectively.</p><p>In the image below, consider the decision boundary in the left image (green). The vector of parameters (theta vector) is perpendicular to it since the region to the right of the vector of parameters has angles from 900–1800 and the region to the left of the decision boundary has angles between 2700–3600. For this decision boundary, we see that the length of projections of training examples (represented by red and pink) is quite small. To satisfy the conditions of p.||theta|| &lt;= -1 for y = 0 (x1) and p.||theta|| &gt;= 1 (x2) in this case, theta needs to have a large value. Due to this, the value of the cost function is not minimized and hence the decision boundary represented in green in the left image won’t be selected by the SVM.</p><p>Now, consider the decision boundary (green) for the image below at right. For the same training examples, we see that their projection on the vector of parameters is greater as compared to the previous decision boundary. Now to satisfy the conditions of p.||theta|| &lt;= -1 for y = 0 (x1) and p.||theta|| &gt;= 1 (x2), we already have a large value of the projection vector ‘p’. This means that a small value of theta will suffice, which in turn minimizes the cost function as well. Hence the decision boundary represented in the image on the right will most likely be selected by the SVM for the binary classification task and by comparing both the decision boundaries, we can clearly see that the classifier selected by the SVM is indeed a large margin classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*M9cq38M6NwQDsCrYVuImyg.png" /></figure><p>Let’s keep in mind that the conclusion that we have drawn above is proven when the parameter <strong>C </strong>in the SVM equation <strong>C*A + B </strong>was very large. We can get similar results when the value of <strong>C</strong> is small and hence we generalize this claim. I encourage the reader to think about it. This will help clarifying the mathematics behind the SVM even more.</p><h3>SVM for Non-Linear Decision Boundaries</h3><p>So far we have seen the scenario where SVM is used as a classifier with linear decision boundaries. SVM uses kernel methods for this task. Before we get onto kernel methods, let us understand why complex polynomial features won’t work well for non-linear SVM classification. Let’s have an intuition about it with the help of linear regression.</p><p>In linear regression, for training data with ’n’ input features, we represent the output as follows:</p><p>y = W1x1 + W2x2 + W3x3 + ………. + Wnxn.</p><p>The output we get for ‘m’ training examples is a straight line. So how can we teak this to get a non-linear decision boundary? Well, we know that polynomials of degree &gt; 1 produce non-linear outputs. But using these polynomials as input features has the following problems:</p><p>(i) For the number of features as small as 5, there are tonnes of possibilities for the choosing features. A sample representation of the output can be y = W1x1² + W2x2³x3² + W3x1²x4²x5 + W4x2x4³ + ……… (there can be tonnes of possibilities). Remember that a polynomial of degree 5 does not need to have all features of 5-degree.</p><p>(ii) With such complex feature representation, the decision boundary can’t be intuitively determined which makes it difficult to tune the features to get better results.</p><p>(iii) Additionally, computing these complex features is computationally very expensive and hence undesirable.</p><h4>Kernel Methods</h4><p>Due to all the drawbacks of polynomial feature vectors for non-linear classifiers mentioned above, SVMs provide a very smart and efficient way to generate non-linear decision boundaries by incorporating the use of <a href="https://en.wikipedia.org/wiki/Kernel_method">kernel methods</a>. The magic of the kernel is to find a function that avoids all the trouble implied by the high-dimensional computation. In machine learning, kernel methods are a class of algorithms for pattern analysis, whose best known member is the Support Vector Machine. Kernel methods require a user-specified kernel, i.e., a <strong>similarity function</strong> over pairs of data points in raw representation. Kernel methods are preferred over feature vectors since they reduce the computational time drastically while computing complex non-linear decision boundaries. The output of a kernel method is a scalar.</p><p>Here, although we are limiting the use of kernels to SVMs, one important thing to note is that every machine learning algorithm that can be expressed using dot-products can be replaced by kernels. Then we can use any of these machine learning algorithms with kernels, which give both, quick and better results. Although there are <a href="https://data-flair.training/blogs/svm-kernel-functions/">different types of kernel methods</a>, I’ll be using Gaussian Kernel for further illustration.</p><h4>Generating Non-Linear Decision Boundaries</h4><p>If kernels don’t do such complex calculations, then how do they generate such good non-linear decision boundaries? Some <strong>landmarks </strong>are defined for the training examples and the similarity of each of the examples is computed with every defined landmark using the similarity function (kernel). The <strong>Gaussian kernel</strong> or Gaussian similarity function for the training example <em>xi</em> and the landmark <em>lj</em> is represented as <strong>exp(-||xi — lj||2 / 2σ2)</strong>. From this, we can see that for a training example <em>xi</em> close to the landmark, its feature value <em>fi </em>is close to 1 and for a training example <em>xi</em> quite far away from the landmark, its feature value is close to 0, which seems a good measure for similarity.</p><p>The calculated similarity values using the Gaussian kernel are considered as the new features values of the respective training examples which can then be attached with their weight parameters (W/theta) to compute the final output class. Earlier in the post we saw that the minimisation objective was subject to the conditions when the dot product of the weight vector and the input feature vector was either &gt;=1 or &lt;= -1. After computing the new feature values using kernels, the conditions of the optimization objective change a bit. Although the inequality values remain the same, the dot product is now computed between the weight vector and the new feature vector computed using Gaussian kernel. Just to clarify, although the output of the kernel method is a scalar value, that scalar value is computed against a single landmark. Against L landmarks, L values are computed which then form a feature vector for a given training example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*dtwvV71kgNlGXVDouq4o6Q.png" /><figcaption>Minimization objective when C &gt;&gt; 1 and kernel methods are used</figcaption></figure><p>Consider a training dataset (with 2 features only for demonstration purposes) with 2 output classes that don’t have a linear decision boundary. Let’s see how defining a few landmarks (let’s say 3) on the training set helps in solving non-linear decision boundaries. In the figure below, we see that for the training example X in pink, it’s quite close to the landmark L1 as compared to the landmarks L2 and L3. Computing the similarity using the Gaussian Kernel for this example, we get feature value f1 corresponding to L1 as close to 1 and the ones corresponding to L2 and L3 (f2 and f3) as close to 0. According to the above equation, we predict one when theta * f &gt;= 1. Now, if the theta values corresponding to these features are 2, 0.5, and 1, then 2*1 + 0.5*0 +1*0 = 2 i.e. &gt;= 1. Performing the same step for multiple training examples gives us a proper non-linear decision boundary with a high accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*6sl0iA5z7fJrXEviiRS1Mw.png" /></figure><h4>Choosing Landmarks</h4><p>We saw how landmarks combined with kernel methods help in defining complex non-linear decision boundaries in SVMs. Now the obvious question of the selection of landmarks arises. One way to choose the landmarks is to convert all the training examples as landmarks and then the feature vector for each training example is calculated by computing similarity between the training example and each landmark using the Gaussian Kernel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*DTkQYfb4d1IjAcsorALe7g.png" /><figcaption>Training examples to landmark mapping</figcaption></figure><p>Once these landmarks are chosen and these new feature vectors are calculated, the final optimization objective is modified to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*3ace0_QI3GDxQqJzt6mbxA.png" /></figure><p>where f(i) represents the new feature vectors calculated using the Gaussian kernel. One thing to note here is that the number of feature vectors (n) will be equal to the number of training examples (m) since each training example is a landmark.</p><h4>Computing Weight Parameters</h4><p>We saw in linear and logistic regression how we computed weights using Gradient Descent. We can’t use gradient descent in its raw form to compute the optimal weight parameters for SVMs because the cost function in the SVM is not differentiable at all points. So, in order to compute weight parameters for SVM, some variants of gradient descent like sub-gradient descent or even various complex algorithms are used. The weight update in sub-gradient descent looks like:</p><p>W = W — alpha * subgradient_wrt_W(J), where ‘alpha’ is the learning rate.</p><p>Solving for sub-derivatives is not as simple as partial derivatives and requires us to understand limits and inequalities well. The first 2 pages of <a href="https://web.stanford.edu/class/ee392o/subgrad_method.pdf">this</a> pdf from Stanford is a good resource that will give you an intuition of how the sub-derivatives are calculated.</p><p>Once the optimal weight parameters for a classification task are calculated, we can run the SVM classifier and calculate the train and test accuracy to evaluate the model’s performance.</p><p>At times in this post, I’ve used various examples by Andrew NG sir while teaching SVMs on coursera along with my ability to provide intuition for the same. I recommend checking the <a href="https://www.coursera.org/learn/machine-learning">machine learning course</a> offered by him if you can spare yourself time for that.</p><p>So far, we’ve learned quite a bit about SVMs. We started from the role of support vectors, then understood how the cost function of SVM implicitly favours large margin classifier in depth followed by the use of kernel trick to calculate non-linear decision boundaries with ease of computation through various illustrations to make things easy to understand. In the end we learnt how vanilla (plain) gradient descent does not work for calculating weight parameters, so the need to use sub-gradient descent was realized. After having learnt this much, it’s now time for us to shift our focus to the Credit Card Transactions Kaggle dataset in order to consolidate our concepts and see the SVM in action.</p><h3>Problem Statement</h3><p>In this section, we’ll be using an SVM to determine fraudulent credit card transactions. Dataset for this problem can be found <a href="https://www.kaggle.com/mlg-ulb/creditcardfraud">here</a>. One thing to note here is that the features of this dataset are already computed as a result of PCA (Principal Component Analysis, which we’ll see in a later post) transformation. It helps in 2 ways:</p><p>(i) The confidentiality of the user data is maintained.</p><p>(ii) The features in the dataset are independent of each other due to PCA transformation.</p><p>Let’s get started by loading the dataset in memory as a dataframe.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt</pre><pre>from sklearn import preprocessing, svm<br>from sklearn.metrics import confusion_matrix</pre><pre>import os<br>for dirname, _, filenames in os.walk(‘/kaggle/input’):<br>  for filename in filenames:<br>    print(os.path.join(dirname, filename))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*BymgGWEOeiwCMQ8ZZAM01w.png" /></figure><pre>df = pd.read_csv(“/kaggle/input/creditcardfraud/creditcard.csv”)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*KPd4NVd7CIQlc_UAW10edA.png" /></figure><p>The dataset has 31 columns/features out of which 28 have been computed through PCA transformation and other features are numerical features only. Let’s now see how the fraudulent and non-fraudulent transactions are distributed in the dataset.</p><pre>print(df[‘Class’].value_counts())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*C97AdR3dTbhsA_n5CMFItw.png" /></figure><p>There are 492 fraudulent (1) transactions as compared to 284315 non-fraudulent (0) ones, which is highly skewed. Clearly we need to resample our data else we can achieve high accuracy by simply predicting every transaction as 0 (non-fraudulent).</p><pre>print(“Accuracy by predicting all transactions as non-fraudulent: “ + str((284315 / (284315 + 492)) * 100) + “%”)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*cE1bwJWRfDYusvo3m4VQvA.png" /></figure><p>There is no use of such a system since all the fraudulent transactions are ignored. We need an equal amount of fraudulent and non-fraudulent transactions for training in order to better capture the features of both kinds of transactions. First of all, let’s analyse the fraudulent transactions data wrt ‘Time’ and ‘Amount’.</p><pre>df_fraud = df[df[‘Class’] == 1]<br>plt.figure(figsize=(15, 12))<br>plt.scatter(df_fraud[‘Time’], df_fraud[‘Amount’])<br>plt.title(“Fraudulent transactions”)<br>plt.xlabel(“Time”)<br>plt.ylabel(“Amount”)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*yiH9HadTpFs2vckT7Jjgug.png" /></figure><p>At all times we have some number of fraudulent transactions making time an irrelevant factor while predicting them. Additionally, most of the fraudulent transactions are very small amount values as seen from the plot above.</p><pre>df_huge_fraud_amounts = df_fraud[df_fraud[‘Amount’] &gt; 1000]</pre><pre>print(“Number of fraudulent transactions over the amount of 1000 are: “ + str((df_huge_fraud_amounts.shape[0])))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*NEQWkvajPX75IqR1vkkUxg.png" /></figure><p>The given dataset says that the features have been calculated using PCA transformation, hence they should be independent of each other. Let us check if this is the case by calculating the correlation between the features.</p><pre>import seaborn as sns</pre><pre>plt.figure(figsize = (15, 12))<br>df_correlation = df.corr()<br>sns.heatmap(df_correlation)<br>plt.title(“Heatmap representing correlations”)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*-XHlchRf1g6jsncRwWAO8g.png" /></figure><p>The diagonal across the heatmap represents the highest correlation (close to 1.0), which is the correlation of a feature with itself. The correlation between other pairs of features has values between -0.2 to 0.2, which corresponds to very less correlation. This represents that the features mentioned are indeed independent of each other and hence no feature can be eliminated based on their dependency on each other.</p><p>Since the number of total fraudulent transactions is too small as compared to non-fraudulent transactions, we need to resample the dataset. By applying <strong>oversampling</strong>, we repeat the fraudulent transactions until they are close in number to non-fraudulent transactions. By applying <strong>undersampling</strong>, we eliminate a number of non-fraudulent transactions so that the final number of non-fraudulent transactions is roughly the same as fraudulent transactions in the dataset. By applying oversampling to this dataset, the training dataset will become huge (284315 non-fraudulent transactions as compared to just 492 fraudulent ones), so we use undersampling.</p><pre>df_train = df[:200000]<br>df_train_fraud = df_train[df_train[‘Class’] == 1]<br>df_train_not_fraud = df_train[df_train[‘Class’] == 0]</pre><pre>print(df_train_fraud.shape[0]) # 385</pre><p>Since there are 385 fraud transactions, we’ll bring down non-fraudulent transactions to around this number to have equal number of training examples of each kind.</p><pre>df_sample = df_train_not_fraud.sample(400)<br>df_train_final = df_train_fraud.append(df_sample)<br>df_train_final = df_train_final.sample(frac = 1).reset_index(drop = True)</pre><pre>df_train_final.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*c-9OL8xouBfjSNk2oUHfow.png" /></figure><p>We can now see that the ‘Class’ column has both 0s and 1s. We took the first 200,000 samples from the dataset and chose 400 (close to 385) non-fraudulent transactions randomly from the total of 284,315 non-fraudulent transactions. Hence, we have successfully implemented undersampling and our final training set consists of 785 training examples. Undersampling can lead to the loss of some important features in the data. But first of all, let’s see the results we get by applying the SVM classifier. Let’s now split data into train and test sets.</p><pre>X_train = df_train_final.drop([‘Time’, ‘Class’],axis=1)<br>y_train = df_train_final[‘Class’]</pre><pre>X_train = np.asarray(X_train)<br>y_train = np.asarray(y_train)</pre><pre>df_test = df[200000:]<br>X_test = df_test.drop([‘Time’, ‘Class’],axis=1)<br>y_test = df_test[‘Class’]</pre><pre>X_test = np.asarray(X_test)<br>y_test = np.asarray(y_test)</pre><pre>print(df_test[‘Class’].value_counts())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*jQ-FPXagxH37iOwnLt9-1w.png" /></figure><p>We see that test dataset contains 107 fraudulent transactions. If the SVM classifier performs considerably well on non-fraudulent transactions and can also detect a lot of these fraudulent transactions, we can say that our model did pretty good.</p><pre>classifier = svm.SVC(kernel=’linear’)<br>classifier.fit(X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*_jFLmNXLO2PK8jUiHnNDVQ.png" /></figure><pre>predictions = classifier.predict(X_test)</pre><p>Now, we have applied the SVM classifier on the training dataset and have stored the prediction results on the test dataset in a ‘predictions’ variable. To evaluate the model’s performance, let’s plot the confusion matrix and identify the following:</p><p>(i) <strong>True positives</strong>: The original output class was <strong>a positive example </strong>(here non-fraudulent transaction) and the predicted output class was also <strong>a positive example </strong>(here non-fraudulent transaction).</p><p>(ii) <strong>False positives</strong>:<strong> </strong>The original output class was <strong>a positive example</strong> (here non-fraudulent transaction) but the predicted output class was <strong>a negative example </strong>(here fraudulent transaction).</p><p>(iii) <strong>False negatives</strong>: The original output class was <strong>a negative example</strong> (here fraudulent transaction) but the predicted output class was <strong>a positive example </strong>(here non-fraudulent transaction).</p><p>(iv) <strong>True negatives</strong>: The original output class was <strong>a negative example </strong>(here fraudulent transaction) and the predicted output class was also <strong>a negative example </strong>(here fraudulent transaction).</p><p>For a banking system, it’s fine if some non-fraudulent transactions are detected as fraudulent, they’ll look into it, but if fraudulent transactions are labelled as non-fraudulent, then that can cause huge losses. Hence, our objective is to reduce the total number of false negatives as much as possible and on the same hand, try that the number of false positives are on the lower side as well. Now, let’s plot the confusion matrix.</p><pre>import itertools</pre><pre>classes = np.array([‘0’,’1&#39;])</pre><pre>def plot_confusion_matrix(cm, classes,title=’Confusion matrix’, cmap=plt.cm.Blues):<br>  plt.imshow(cm, interpolation=’nearest’, cmap=cmap)<br>  plt.title(title)<br>  plt.colorbar()<br>  tick_marks = np.arange(len(classes))</pre><pre>  plt.xticks(tick_marks, classes, rotation=45)<br>  plt.yticks(tick_marks, classes)</pre><pre>  fmt = ‘d’<br>  thresh = cm.max() / 2.</pre><pre>  for i, j in itertools.product(range(cm.shape[0]),    range(cm.shape[1])):<br>    plt.text(j, i, format(cm[i, j], fmt),<br>    horizontalalignment=”center”,<br>    color=”white” if cm[i, j] &gt; thresh else “black”)</pre><pre>plt.tight_layout()<br>plt.ylabel(‘True label’)<br>plt.xlabel(‘Predicted label’)</pre><pre>cm = confusion_matrix(y_test, predictions)<br>plot_confusion_matrix(cm,classes)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*hjHjfmWk5pAWO9_DZNUFTg.png" /></figure><p>The confusion matrix has</p><p>(i) 81746 true positives</p><p>(ii) 3224 false positives</p><p>(iii) 11 false negatives</p><p>(iv) 96 true negatives</p><p>From this, we can conclude that most of the fraudulent transactions have been captured and only 11 of them were misclassified, which is way better than a model which yields an extremely high accuracy but doesn’t capture any fraudulent transaction as we discussed earlier while solving this problem.</p><pre>print(‘Total fraudulent transactions detected: ‘ + str(cm[1][1]) + ‘ / ‘ + str(cm[1][1]+cm[1][0]))<br>print(‘Total non-fraudulent transactions detected: ‘ + str(cm[0][0]) + ‘ / ‘ + str(cm[0][1]+cm[0][0]))</pre><pre>print(‘Probability to detect a fraudulent transaction: ‘ + str(cm[1][1]/(cm[1][1]+cm[1][0])))<br>print(‘Probability to detect a non-fraudulent transaction: ‘ + str(cm[0][0]/(cm[0][1]+cm[0][0])))</pre><pre>print(“Accuracy of the SVM model : “+str(100*(cm[0][0]+cm[1][1]) / (sum(cm[0]) + sum(cm[1]))) + “%”)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Mit8sFcjxtx5V2pWH_JZMw.png" /></figure><p>The entire code for this post can be found <a href="https://www.kaggle.com/vardaanbajaj/credit-card-fraud-svm?scriptVersionId=38180580">here</a>.</p><p>Our primary focus was on capturing as many fraudulent transactions as we could and we’ve done a great job by detecting 96/107 fraudulent transactions given that we had only around 800 fraudulent examples in the entire dataset.</p><p>That’s it for this post. We went into a lot of depth into the concepts of SVMs and I made sure I provided intuition for each part in order for the readers to better grasp things quickly. The only topic that we didn’t discuss in detail was sub-gradient descent, but trust me, all the python packages that implement SVMs, as long as you know how SVMs work, with all their parameters, sub-gradient descent is implemented automatically in these packages. In the <a href="https://medium.com/analytics-vidhya/machine-learning-v-decision-trees-random-forest-kaggle-dataset-with-random-forest-3ebfe6d584be">next</a> post, we’ll dive deep into random forest and decision trees and solve a Kaggle dataset using them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57d7c885652a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/machine-learning-iv-support-vector-machines-kaggle-dataset-with-svms-57d7c885652a">Deep Dive Into Support Vector Machines</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing With High Bias and Variance]]></title>
            <link>https://medium.com/data-science/contents-9b2e49f49fe9?source=rss-168771086803------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b2e49f49fe9</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regularization]]></category>
            <category><![CDATA[variance]]></category>
            <category><![CDATA[bias]]></category>
            <dc:creator><![CDATA[Vardaan Bajaj]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 13:34:44 GMT</pubDate>
            <atom:updated>2020-07-24T16:43:09.888Z</atom:updated>
            <content:encoded><![CDATA[<h4>Regularization Explained Through Equations</h4><h3>Contents</h3><p>In this post, we’ll be going through:</p><p>(i) The methods to evaluate a machine learning model’s performance</p><p>(ii) The problem of underfitting and overfitting</p><p>(iii) The Bias-Variance Trade-off</p><p>(iv) Addressing High Bias and High Variance</p><p>In the <a href="https://medium.com/analytics-vidhya/machine-learning-ii-logistic-regression-explained-data-pre-processing-hands-on-kaggle-728e6a9d4bbf">previous</a> post, we looked at logistic regression, data pre-processing and also went hands-on on titanic dataset on Kaggle on which we obtained decent results. In both the posts so far, you must have noticed that I threw the term overfitting here and there and also mentioned that it can lead to poor performance of the machine learning model. Now, we’ll be having a detailed look into the problems machine learning models can go through and what are their possible solutions. We won’t be going hands-on in this post but in the upcoming posts, we’ll apply the concepts that we’ll learn in this post.</p><h3>Evaluating model’s performance</h3><p>Before directly going into the problems that occur in machine learning models, how do we know that there is an issue with our model? For this, we need an evaluation metric for our model. We’ve already seen a couple of them. We used the coefficient of determination (r² score) to evaluate the linear regression model and accuracy to evaluate the logistic regression model. Both these metrics are calculated by the underlying error we get through their respective cost functions. To address the problems of machine learning models, we will be using this <strong>error </strong>to make decisions.</p><p>Errors are calculated in different ways in linear and logistic regression. To make things easy to understand and develop intuition, we’ll be looking at things from linear regression perspective but the terms that we’ll define and the roles they play will be exactly the same as for any other machine learning model.</p><p>An error is a ‘mistake’ and the extent of this mistake can be quantified as the absolute difference between the true value and the estimated value. For ’n’ quantities, it can be represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*LbGh5BbW5AAXiWP3Y0CX-w.png" /></figure><p>Computing error for the model’s performance on the training and test set helps us to identify the problems faced by the model. Consider the following scenarios:</p><p>(i) Low training set error, low test set error</p><p>(ii) Low training set error, high test set error</p><p>(iii) High training set error, high test set error</p><p>(iv) High training set error, low test set error</p><p>Let’s look at these scenarios one by one.</p><p>If both the training set error and the test set error are low, it means the model learnt the input-output mappings well on the training set and was able to generalize it well to the test set as well. This is the desired output of a good machine learning model. This was the case with the logistic regression model we trained in the previous post.</p><p>When the training set error is low but the test set error is high, we say that the model is over-fitting the training set. This means that after training the machine learning model on the training set, it learnt the input-output mappings exceptionally well for the training set but couldn’t generalize these mappings to the test set. Let’s try to understand why this happens. Data collected for any task can never be error free, no matter how careful the process be. A good machine learning model should always sample out noise and only generate those input-output mappings that exclude the noisy data points i.e. a good machine model is robust to noise. Consider the case of a music concert where there is both, the melody of the artists and the noise of the crowd, but we pay attention only to the artists’ melody (input) as it makes us cheerful (output), ignoring all the <em>noise</em> of the crowd. If we pay heed to all the voices (artists + noise), we probably won’t be as much happy. Overfitting is the case where the machine learning model pays heed to each and every voice (artist + noise) when in reality we just need to focus on the melody. A machine learning model that overfits on the training data is said to suffer from <strong>high variance.</strong> Later in the post we’ll see how to deal with overfitting.</p><p>If both, the training and test set error are high, then it symbolizes that the machine learning model has not properly learnt the input-output mapping on the training set and is also unable to generalize on the test set. In other words we can say that our machine learning model is in a raw state. Such a model is said to underfit on both, the training and test dataset and suffers from <strong>high bias</strong>.</p><p>A machine learning model that has high training set error and low test set error is a rare occurrence but it happens when the training and test data is not properly sampled (eg. almost equal no. of samples for each class in a classification problem) which causes a substantial difference in the statistical properties of the test set. Consider a binary classification problem where predictions for class A give 10% training error and predictions for class B give 40% training error. Average classification accuracy gives us 25% error on the overall dataset. But this is not a good measure. It may very well be the case that the number of occurrences of class A outnumber class B in a real life test set. This means that actual prediction error in real life datasets will be significantly less than 25%. Another case in which this scenario occurs is when the test set is significantly smaller than the training set and although being similar to the training set, we get less error on test set as it does not have that much noise as compared to the training set. Nothing much can be done to avoid these type of scenarios other than studying and sampling the data before applying any machine learning algorithm on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*z8AtfeawLH2ffP4G9jC8Kw.png" /><figcaption>Visual representation of high bias, a perfect fit and high variance (<a href="https://www.pinterest.com/pin/52706258122128665/">Source</a>)</figcaption></figure><h3>Definitions of Bias and Variance</h3><p>The terms bias and variance must not sound new to the readers who are familiar with statistics. Standard deviation measures how close or far enough are data points from a central position and mathematically, variance is just squared standard deviation. So, variance measures how far a set of data is spread out. Data used for machine learning tasks doesn’t have a specific input-output mapping and the task of these models is to find a good enough mapping which generalize the results. A machine learning model, which (over)fits to all the data points, including the noisy ones, or in other words, fits to all the data points no matter how wide they are spread, is said to suffer from high variance.</p><p>In statistics, the bias (or bias function) of an estimator (here, the machine learning model) is the difference between the estimator’s expected value and the true value for a given input. An estimator or a decision rule with zero bias is called unbiased. High bias of a machine learning model is a condition where the output of the machine learning model is quite far off from the actual output. This is due to the simplicity of the model. We saw earlier that a model with high bias has both, high error on the training set and the test set.</p><h3>The Bias-Variance Tradeoff</h3><p>The Bias-Variance tradeoff is a property that lies at the heart of supervised machine learning algorithms. Ideally, we want a machine learning model which takes into account all the patterns as well as the outliers in the training data and generalize them to the test (unseen real world) data in order to achieve very small error and very high accuracy. We saw earlier that high variance models are complex and represent all the features of the training set very well leading to minimal error on the training set but fail to generalize to the unseen data. In contrast, high bias models represent extremely simple mappings and can generalize some features to the unseen data, but the simplicity of these models leads to underfitting on the training set and generates predictions with lower variance (high bias) when applied to data outside of the training set. The ideal amount of bias and variance that a particular machine learning model should have depends on the minimization of the error (which includes bias error, variance error and noise).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*2RNoedJQVL1Ex3gmAvQxBQ.png" /><figcaption>Bias-Variance Tradeoff (<a href="https://www.ncbi.nlm.nih.gov/books/NBK543534/figure/ch8.Fig3/">Source</a>)</figcaption></figure><h3>Addressing Issues In Machine Learning</h3><p>Building a machine learning model is an iterative process. After having a look at the dataset, we should always start with simple models and then keep on increasing their complexity until we get desired results on the unseen data. An extremely simple machine learning model suffers from high bias and an extremely complex machine learning model suffers from high variance. Since we move from simple to complex models step-by-step, we get rid of the problem of high bias but getting rid of high variance isn’t that easy since there are scenarios when with the given set of parameters and methods, we don’t get an optimum model and the model with high variance needs to be treated to get an optimum model. So let’s discuss a few ways to solve the problem of high variance first.</p><h4>Addressing High Variance</h4><p>Consider the example of a logistic regression classifier. If we say that the classifier overfits on the training data, this means that the output of the equation y = sigmoid(Wx + b) is very close to the actual training data values. So, what is the root cause of overfitting? Clearly, it is the parameter values that we trained while building the classifier responsible for the high variance (overfitting) of the machine learning model. Regulating these parameter values helps get rid of overfitting and this process is called regularization. In formal terms, regularization is the process of adding information in order to solve an ill-posed problem or to prevent overfitting. Regularization makes the parameter values small and this prevents overfitting. Later in the post, we’ll see why does this work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*E581ySiDPEdAHJki9Yhlqw.png" /><figcaption>Train and Test Error for a High Variance Model</figcaption></figure><h4>Regularization</h4><p>Since we are modifying the parameter values, we need to update our cost function in order to see the effects of regularization. <strong>L2 regularization</strong> is most commonly used with the cost function and yield considerably good results. The cost function after L2 Regularization is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*ZwIeOdXdBNF_ku__GxdhqA.png" /></figure><p>where y(i) represents the actual output for the training example i, Φ(z(i)) is the predicted value for the training example i through logistic regression, <strong>λ </strong>is the regularization parameter and ||w||² is the <strong>L2 norm</strong> of the vector of weights W. Vectorization of weights is nothing but all the Wi stacked against each other enclosed by a vector. Python’s machine libraries use the vectorized parametric equations to speed up the calculations.</p><p>Suppose the vector W has 3 values W1, W2, W3, then L2 norm of the vector W is calculated as:</p><p>||W||² = sqrt(W1² + W2² + W3²)</p><p>Notice here that we didn’t regularize the parameter b as in a general logistic regression classifier, each feature has a corresponding W value, so there are multiple W values and just a single bias b value and regularizing the bias parameter does not make any difference practically. Just for the sake of completeness, we regularize b by adding (<strong>λ/2)*||b||² </strong>at the end of the cost function and use separate <strong>λ </strong>values for both.</p><h4>Why and how does regularization work?</h4><p>Now, while performing gradient descent to update the parameters, the updates will look as follows:</p><p>W = W — alpha * dJ/dW</p><p>b = b — alpha * dJ/db</p><p>The dJ/dW term consists of an additional term due to regularization and is positive in value i.e. the partial derivative value for the cost function wrt W is greater when the cost function is regularized than when it was not. So, on updating the parameters, we subtract a bigger chunk from the previous state of W and we do this for a number of iterations and the final value of W is smaller than the one we would have obtained without regularization. Similarly, we can compute dJ/db with regularization.</p><p>Now we know that regularization leads to small parameter values which lead to convergence on the global minima of the cost function. We’ll use logistic regression with ’n’ examples to see why regularization works. We know that y = sigmoid(W1x1 + W2x2 + W3x3 + ………. + Wnxn + b). Since regularization results in smaller parameter values than the non-regularized ones, let’s consider that the parameters values Wi are very small and very close to 0. So the output of the logistic regression classifier will be simply y = sigmoid(b), which is a very simple and a very poor estimation of the output. In other words, this output is so extremely simple that it has an extremely <strong>high bias</strong>. From the bias-variance trade-off, we know that high bias and high variance are 2 opposite ends of a machine learning model and ideally we want to land somewhere in between with our model. To achieve this, we have to choose the regularization parameter <strong>λ </strong>very wisely. <strong>λ </strong>is set using a development set, where we try a variety of <strong>λ </strong>values and choose the one which yields the best performance for our machine learning model and then use this model to make predictions on the test set.</p><p>Like the L2 regularization, there is yet another type of regularization term we can add to the cost function. The cost function after addition of this <strong>L1 Regularization </strong>term is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*vGcFtTL3NjJIGMOOUQkbUg.png" /></figure><p>where ||w|| is the <strong>L1 norm</strong> of the vector W. L1 norm of the vector W with 3 elements is computed as:</p><p>||W|| = |W1| + |W2| + |W3| where,|Wi| represents the absolute value of Wi.</p><h4>Adding More Training Data</h4><p>Another way of dealing with overfitting of machine learning model is the addition of more data to the training set. The reason behind this is simple. If a machine learning model is overfitting on the training set, it is learning the noisy inputs in the data as well. Adding more data will result in more noise in the data and it becomes difficult for the machine learning model to account for so much noise that it ends up leaving the noisy inputs and focuses more on the general pattern of the input-output pairs. This leads to models which don’t overfit the training data and are free from the problem of high variance. The amount of data to be added to the training set depends on the extent of overfitting of the machine learning model.</p><h4>Addressing High Bias</h4><p>Bias in the machine learning model is not big of an issue as we saw earlier and is easy to remove. Since high bias leads to an extremely simple machine learning model which does not capture all the necessary features to make more accurate predictions, we can do the following things to remove high bias:</p><p>(i) Use a more complicated machine learning model (by introducing polynomial features instead of the linear ones like y = Wx + b) than the existing one as it might well capture all the important features and patterns in the training data.</p><p>(ii) We saw that regularization shrinks the values of the parameters drastically, which can also lead to high bias. So, decreasing the regularization parameter helps in getting rid of high bias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*ELCci29mbdPDyoC9Tn6zcw.png" /><figcaption>Train and Test Error for a High Bias Model</figcaption></figure><p>In this post, we first developed intuition about high bias and high variance, then understood the problems a machine learning model can run into when either or both of them creep in. Later we looked at ways to get rid of high bias and high variance from a machine learning model and also developed insights into working of regularization.</p><p>In the <a href="https://medium.com/analytics-vidhya/machine-learning-iv-support-vector-machines-kaggle-dataset-with-svms-57d7c885652a">next</a> post, we’ll have a look at another supervised machine learning method called Support Vector Machines and will also solve a dataset from Kaggle using it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b2e49f49fe9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/contents-9b2e49f49fe9">Dealing With High Bias and Variance</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive Into Logistic Regression and Data Pre-Processing]]></title>
            <link>https://medium.com/analytics-vidhya/machine-learning-ii-logistic-regression-explained-data-pre-processing-hands-on-kaggle-728e6a9d4bbf?source=rss-168771086803------2</link>
            <guid isPermaLink="false">https://medium.com/p/728e6a9d4bbf</guid>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[kaggle]]></category>
            <dc:creator><![CDATA[Vardaan Bajaj]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 14:33:40 GMT</pubDate>
            <atom:updated>2020-07-22T15:51:46.124Z</atom:updated>
            <content:encoded><![CDATA[<h3>Contents</h3><p>In this post, we’ll be going through:</p><p>1. The Problem Solved By Logistic Regression</p><p>2. Activation Functions</p><p>3. Cost Function for Logistic Regression</p><p>4. Gradient Descent for Logistic Regression</p><p>5. The Need for Data Pre-processing</p><p>6. Techniques of Data Pre-processing</p><p>7. Solving the Titanic dataset on Kaggle through Logistic Regression</p><p>In the <a href="https://medium.com/analytics-vidhya/machine-learning-i-introduction-linear-regression-explained-bc5bfee25832">previous</a> post, we looked at Linear Regression Algorithm in detail and also solved a problem from Kaggle using Multivariate Linear Regression. In this post, we’ll be looking at another regression problem i.e. Logistic Regression. Later in the post, we’ll be discussing about data pre-processing as data pre-processing is quite an important and the most time consuming step of any machine learning task.</p><p>Logistic Regression is a type of supervised learning problem where the output values are discrete i.e. the output is a fixed number of classes. Logistic Regression problems are of 2 types:</p><p><strong>(i) Binary Classification</strong></p><p><strong>(ii) Multi-class Classification</strong></p><p>Binary classification is the task of classifying the input data into 2 groups whereas multi-class classification is the task of classifying the input data into more than 2 groups. Pretty much self-explanatory, right. To understand things, we’ll be looking at binary classification and later on, we’ll generalize logistic regression to multi-class classification.</p><h3>Binary Classification</h3><p>Let’s denote the 2 output classes by 0 and 1. Our logistic regression model cannot output the values 0 and 1 with 100% confidence as we know from the previous post that the model should only learn the patterns (general rules) and not go into specifics of each training example, because if it does, then we’re probably dealing with overfitting. So, we can expect that our binary classification model outputs a value between 0 and 1 i.e. the probability of each class and the probabilities for all classes (here 2) should add up to 1. In this case, that class is assigned to the output which has the higher probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*HXfuppljtMOa0gFY4fYLQg.png" /><figcaption>Binary Classification Example</figcaption></figure><p>Now, the obvious question of how to let the model output probabilities arises. In linear regression, we saw that our output was depicted by the equation y = Wx + b, where y can have any real values. If we use this equation as our baseline, then to convert this equation’s output into a probability, we need a function that can input any real number and outputs a value between 0 and 1. The function we use for this purpose is called the activation function.</p><h3>Activation Functions</h3><p>Consider the final output of 0 or 1 as a switch, where 0 is the ‘off state’ and 1 is the ‘on state’. The probability values that we input to the activation function can be thought of as current (electricity) values. When the current is above a certain threshold, our switch gets ‘activated’ to the on state otherwise, it stays in the off state. Various activation functions mimic this behaviour and the most common one is the <strong>sigmoid activation function</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*RLwgGHYnEZGPaRkFqMS0oA.png" /><figcaption>Sigmoid Activation Function (<a href="https://www.researchgate.net/figure/An-illustration-of-the-signal-processing-in-a-sigmoid-function_fig2_239269767">Source</a>)</figcaption></figure><p>For binary classification, the sigmoid function inputs the output of the equation y = Wx + b and then outputs the probability value for each class. In the formula shown above for sigmoid function, we see that for x = 0, the output of the sigmoid function is exactly 0.5. So, for all values of x &gt; 0, the output switch is activated and the corresponding input data is classified as belonging to category 1, otherwise it belongs to category 0.</p><p>Other examples of activation functions are:</p><p><strong>(i) Hyperbolic Tangent function (tanh)</strong> — The tanh(x) is defined as (e^x-e^-x)/(e^x+e^-x) and has values in the range of (-1, 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*bfui_8f95ZcXovjrAKAcEw.png" /><figcaption>Tanh activation function (<a href="https://mathworld.wolfram.com/HyperbolicTangent.html">Source</a>)</figcaption></figure><p><strong>(ii) Rectified Linear Unit function (ReLU)</strong> — The ReLU activation function is a smartly designed non-differentiable activation function as they are much easy to compute and reduce computational cost significantly. The ReLU activation function is widely used in deep learning problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*LftbQ1sYLEhnL-qi9c5bdA.png" /><figcaption>ReLU Activation Function (<a href="https://www.quora.com/What-does-ReLU-layer-do">Source</a>)</figcaption></figure><p><strong>(iii) Softmax Function</strong> — Softmax activation function works well with multi-class classification problem and computes the probability of the occurrence of each class. The class corresponding to the highest probability value is then considered to be the output class for the input.</p><p>Now that we know the problem logistic regression deals in and how activation functions work, let’s have a look at the cost function for logistic regression.</p><h3>Cost Function For Logistic Regression</h3><p>The output of our logistic regression binary classifier is the composition of two functions, the linear regression function y = Wx + b and the sigmoid activation function. If f(x) = Wx + b and S(x) = 1/(1 + e^-x), then the output of the logistic regression binary classifier is S(f(x)).</p><p>So far, we only know about the Euclidean Distance cost function which we saw in Linear Regression. It is represented by: J = sum_over_all_training_examples((y_hat_i — y_i)²), where y_hat_i is the predicted output and y_i is the actual output for training example i. But can we use this same cost function for logistic regression? The answer is no because the output values in linear regression were real values whereas y_hat_i and y_i in logistic regression are probabilistic and a finite set of discrete values respectively. For example consider y_i is 1. If y_hat_i is 0.9, the the loss for this training example is (1–0.9)² i.e. 0.01. If, y_hat_i is 0.1, then the loss for this training example is (1–0.9)² i.e. 0.81. Clearly, the difference between the loss function values is not much even though according to the first prediction, we get the output class of 1 and according to the second prediction, we get the output class of 0. So, we need to penalize the probability values which lead to wrong classification much more than the probability values leading to the right classification. For this reason, we use a different kind of cost function for logistic regression which is the <strong>binary crossentropy </strong>which would enable us to solve the minimization problem on the parameters W and b.</p><h4>Binary Crossentropy</h4><p>In order to gain insight into choosing this function as the cost function for logistic regression, let’s understand the meaning of binary crossentropy. The information entropy, often just entropy, is a basic quantity in information theory associated to any random variable, which can be interpreted as the average level of “information”, “surprise”, or “uncertainty” inherent in the variable’s possible outcomes. Crossentropy determines how close is the predicted probability distribution (entropy) of the output classes to the true distribution. Binary crossentropy as a cost function therefore, compares the probabilistic output of the sigmoid function with the correct class label (out of 2 classes) and computes the cost. The lower the cost, the better the prediction is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*mGsCcZUBO5M7Ak-GYuoYcA.png" /><figcaption>Binary Crossentropy Cost Function (N training examples)</figcaption></figure><p>We chose the binary crossentropy as the cost function for logistic regression to penalize the probability values leading to misclassification. How does using the log function help though? Well, to come up with log function for this purpose is a work of years by many genius statisticians out there, but I can help explaining it. Lets have a look at the edge cases. Consider that for the class label 1 (y), our logistic regression model outputs a probability of 0.9 (y_hat). Then the loss corresponding to this prediction will be –{1*log(0.9) + 0*log(0.1)} i.e. 1.05. If the logistic regression output for this class had been 0.1, then the loss for this training example would have been –{1*log(0.1) + 0*log(0.9)} i.e. 2.30. If we compare these values with the loss values in Euclidean distance cost function, we can clearly see that the binary crossentropy function penalizes wrong predictions more. So, when we perform the learning operation by minimizing the binary crossentropy loss through gradient descent, the values of the parameters would be updated in a way which yields us higher accuracy than the Euclidean distance cost function.</p><h3>Gradient Descent for Logistic Regression</h3><p>Now that we have the equation to represent the output values of logistic regression and the cost function to penalize the parameter valuesfor misclassifications, we can use Gradient Descent to update our parameters W and b until we get those values which help us reach the global minima of the cost function. Gradient Descent algorithm for Logistic Regression is exactly the same as that of Linear Regression discussed in the previous post, the only difference comes in the formula for partial derivatives. Let’s walk through the whole process of gradient descent through a pseudo code.</p><pre>temp_W = temp_b = random_values<br>flag_W = flag_b = False<br>do<br>  if ((abs(W — temp_W) &gt; delta_W) and flag_W = False)<br>    temp_W = W — alpha * partial_derivate_wrt_W(J)<br>  if ((abs(b — temp_b) &gt; delta_b) and flag_b = False)<br>    temp_b = b — alpha * partial_derivative_wrt_b(J)<br>  if(temp_W == W)<br>    flag_W = True<br>  if(temp_b == b)<br>    flag_b = True<br>  W = temp_W<br>  b = temp_b<br>while True</pre><p>To calculate the partial derivative of the cost function J wrt the parameters W and b, we first replace y_hat in the cost function with the composition function used to represent the output of logistic regression binary classifier as shown above and then calculate the derivatives. The whole calculation can be found on the answer to <a href="https://math.stackexchange.com/questions/2503428/derivative-of-binary-cross-entropy-why-are-my-signs-not-right">this</a> question’s answer on <a href="http://math.stackexchange.com/">math.stackexchange.com</a>. This answer ignores the bias parameter b and only computes the partial derivative of J wrt W, but the partial derivative of J wrt b can be calculated in a similar way.</p><p>Now that we have seen how binary classification in Logistic Regression works, lets extend this idea to multi-class classification in logistic regression. Additionally, we can also extend this problem with more than 1 input feature quite easily.</p><p>Let’s start by seeing the equations for binary classification with ’n’ input features. We can use the same equation we used for the multivariate linear regression problem and then take sigmoid value of the equation.</p><p>f(x) = W1x1 + W2x2 + W3x3 + ………. + Wnxn</p><p>S(x) = 1/(1 + e^-x)</p><p>Then, the output for binary classification with multiple input feature can be represented as S(f(x)).</p><p>Consider that there are a total of C classes labelled from 0 to C-1. Then there are 2 ways we can solve this problem.</p><p>(i) Let’s say that we are currently interested in predicting the class label k, then we divide the entire data into 2 classes, the class k represented as 1 and all other classes represented as 0 and then solve the binary classification problem. This process can be automated for all other classes as well. This works fine but is an inefficient method.</p><p>(ii) We can use a neural network with C outputs (and 1–2 hidden layers depending on the size and complexity of the data) and use the softmax activation function for the output layer. I’ll be covering more on this in the deep learning series.</p><p>Now that we’ve developed the understanding of how Logistic Regression works, let’s learn a bit about data pre-processing as not all data is as clean as the data we dealt with in the previous post.</p><h3>The Need Of Data Pre-processing</h3><p>One thing that may take you by surprise is the fact that to solve a Machine Learning problem, almost 90% of the time is spent in data pre-processing. Sounds strange right. I assume you might have conducted a survey at least once in your life. When we go through the responses of the survey, we can see that not all people answer all the questions. Some people may write numbers as words. There are tonnes of variations that can be seen in survey responses. Similarly, real world datasets are also prepared by surveying. So it’s quite possible that the given dataset may have missing values. There are many errors that humans can automatically resolve owing to their intelligence but the machine cannot. Additionally, we do not want our machine learning model to treat any of the input data features partially, so we need to scale down all the values to a specific range. Now that we have intuition about the need of data pre-processing, let’s have a look at some techniques one by one:</p><p><strong>(i) Taking care of missing data</strong></p><p>Some or all the features of the data may have missing values, which when loaded as a pandas dataframe are represent by NaN (Not a Number). For each input feature, we first check the percentage of NaN values in it. If the percentage of NaN values is significantly large for a feature, we can simply ignore this feature during the training process since its effect on the output is minimal. If we have training data loaded in a pandas dataframe as ‘train_df’, then we can check for the total number of NaN values across all features by the following line of code:</p><pre>train_df.isna().sum()</pre><p>This outputs all the features along with the total number of NaN values in each feature. Once we have decided on the features that we want to keep, the next step is to decide how to fill missing values in those features.</p><p><strong>(ii) Filling the missing values</strong></p><p>To fill the missing values in a feature, the first and foremost requirement is that the feature should have numerical values. Then we can use one of the <strong>mean, median or mode</strong> of the values of this feature and use this to fill the missing values. For example, if the ‘age’ column has missing values, then the code for filling missing values with the median of ‘age’ values will look like:</p><pre>train_df[“age”].fillna(train_df[“age”].median(skipna=True), inplace=True)</pre><p><strong>(iii) Encoding categorical variables</strong></p><p>Categorical variables are those features in the data which have a discrete number of non-numerical values. Suppose the dataset talks about the countries in the subcontinent, then the ‘country’ feature will only have a specific number of countries. Total number of different values inside a feature can be found out by one line in python:</p><pre>train_df[‘country’].value_counts()</pre><p>This outputs the number of instances of each country in the dataset. Suppose there are 8 distinct countries, then one way to replace the non-numerical values in the country column is by assigning each country a number between 1–8. This process is known as <strong>Label Encoding. </strong>In python, label encoding operation can be performed as follows:</p><pre>from sklearn.preprocessing import LabelEncoder<br>labelencoder = LabelEncoder()<br>train_df[‘country_encoded’] = labelencoder.fit_transform(train_df[‘country’])</pre><p>This creates a column called ‘country_encoded’ which has the numerical representation of each of the 8 countries. Other techniques of encoding categorical variables like one-hot encoding are also quite efficient, but the main idea here was to introduce you to this concept. More on one-hot encoding <a href="https://www.kaggle.com/dansbecker/using-categorical-data-with-one-hot-encoding">here</a>.</p><p><strong>(iv) Feature Scaling</strong></p><p>In feature scaling, we convert all the values of our input features to a specific range so that no feature is preferred over the other during the learning process. Most of the built-in implementations of machine learning models in python take care of feature scaling but there are some cases when this has to be done by hand, so it was worth mentioning here.</p><p>If you’ve made it this far on the post, you should be proud of yourself. We explored each of the elements of logistic regression in detail, learnt about various activation functions and also understood why data pre-processing is important and looked at some of the ways to pre-process data. Now, to consolidate all our concepts and get confidence over the topics covered in this post, let’s solve the <a href="https://www.kaggle.com/c/titanic/data">Titanic dataset </a>on Kaggle using the Logistic Regression binary classifier. This problem was a part of a competition, so even if we get ‘average’ results, we should be in good space for solving any of the logistic regression problems we encounter in the future. I’m talking about average results because there are many techniques better than logistic regression which we’ll see in later posts and they come with practice.</p><h3>Problem statement</h3><p>Click <a href="https://www.kaggle.com/c/titanic/data">here</a> for the dataset. The given data has 12 features. Training dataset has 891 examples and the data on which we have to submit the predictions has 418 examples. This problems can be stated as a logistic regression problem as:</p><p>Y = sigmoid(W1x1 + W2x2 + W3x3 + W4x4 + W5x5 + W6x6 + W7x7 + W8x8 + W9x9 + W10x10 + W11x11 + W12x12)</p><p>First of all let’s import all the python packages for data pre-processing, mathematical calculations, plotting graphs and performing logistic regression.</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn.model_selection import train_test_split, cross_val_score<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.metrics import accuracy_score, classification_report, precision_score, recall_score<br>from sklearn.metrics import confusion_matrix, precision_recall_curve, roc_curve, auc, log_loss<br>import matplotlib.pyplot as plt<br>import os</pre><pre>for dirname, _, filenames in os.walk(‘/kaggle/input’):<br>  for filename in filenames:<br>    print(os.path.join(dirname, filename))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*YmdYtmJNZGVpE_jHppqdXA.png" /></figure><p>Now, let’s look at a few examples from train and test dataset.</p><pre>train_df = pd.read_csv(“/kaggle/input/titanic/train.csv”)<br>test_df = pd.read_csv(“/kaggle/input/titanic/test.csv”)</pre><pre>train_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*pv_8ycKrrAKa9KOt_Hfl5Q.png" /></figure><pre>test_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*2JRVSJaQRc6M_YOJwwhi4w.png" /></figure><p>From the above outputs, it’s evident that we have to predict whether the passenger survived on the titanic or not, given his details. Now, before actually applying the logistic regression binary classifier to this data, let’s move on to data pre-processing phase, which will consume most of our time.</p><p>Let’s start by checking missing values.</p><pre>train_df.isna().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*y5XJNRh-Ljnyr8CCGY1SqQ.png" /></figure><p>We can see that out of 891 records, 177 records for age are missing, 687 records for cabin are missing and 2 records for embarked are missing, which in percentages can be represented as:</p><pre>print(“Percentage missing age values: “ + str((train_df[‘Age’].isna().sum()/train_df.shape[0])*100))</pre><pre>print(“Percentage missing cabin values: “ + str((train_df[‘Cabin’].isna().sum()/train_df.shape[0])*100))</pre><pre>print(“Percentage missing embarked values: “ + str((train_df[‘Embarked’].isna().sum()/train_df.shape[0])*100))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*b8royuftxCinmZD7HbW7tA.png" /></figure><p>We observe that close to 80% values in Cabin column are missing, so we can’t confidently fill these values. So we drop the entire Cabin column. Now to see which values we can fill for age, let’s see how age values are distributed across the dataset.</p><pre>age_distribution = dict(train_df[“Age”].value_counts())<br>lists = sorted(age_distribution.items())<br>x, y = zip(*lists)<br>plt.plot(x, y)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*AASUPnN58OLal8YC9ROXgg.png" /></figure><p>We can see that the age distribution is a bit skewed to the left. So using the median values will hold good for missing age values. On the other hand, the Embarked column only has 3 types of values, so we fill the missing 2 values with the most frequent value i.e. the mode of the Embarked column.</p><pre>train_data = train_df.copy()<br>train_data[“Age”].fillna(train_df[“Age”].median(skipna=True), inplace=True)<br>train_data[“Embarked”].fillna(train_df[‘Embarked’].value_counts().idxmax(), inplace=True)</pre><pre>train_data.drop(‘Cabin’, axis=1, inplace=True)</pre><p>We can now see that all the missing values are gone.</p><pre>train_data.isna().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*uF3Q_VcAMxvORSGOqXnjuQ.png" /></figure><p>Now, let’s have a look at the current state of the training data.</p><pre>train_data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*EK2Ev2AW8U_-dyx9ngU79g.png" /></figure><p>There are still a few things we need to fine tune. We don’t need the Name and Ticket column at all because they clearly have no role to play in predictions (unless you can make your machines learn astrology). Now, we need to encode the categorical column values i.e. Pclass, Sex, Embarked. Even though Pclass has integer values, these integers represent the location on the titanic for which the passenger bought the ticket. We use one-hot encoding to encode these columns.</p><pre>training=pd.get_dummies(train_data, columns=[“Pclass”,”Embarked”,”Sex”])<br>training.drop(‘Sex_female’, axis=1, inplace=True)<br>training.drop(‘PassengerId’, axis=1, inplace=True)<br>training.drop(‘Name’, axis=1, inplace=True)<br>training.drop(‘Ticket’, axis=1, inplace=True)<br>final_train = training</pre><pre>final_train.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*b9uOEiXVibGMnzvl81GnfQ.png" /></figure><p>Now, our training set looks good. Let’s check for missing values in the test set and apply all the transformations on it that we did for the training set.</p><pre>test_df.isna().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*_6EknUrGbTYtPtUbGpvOwQ.png" /></figure><pre>test_data = test_df.copy()<br>test_data[“Age”].fillna(train_df[“Age”].median(skipna=True), inplace=True)<br>test_data[“Fare”].fillna(train_df[“Fare”].median(skipna=True), inplace=True)<br>test_data.drop(‘Cabin’, axis=1, inplace=True)</pre><pre>testing = pd.get_dummies(test_data, columns=[“Pclass”,”Embarked”,”Sex”])<br>testing.drop(‘Sex_female’, axis=1, inplace=True)<br>testing.drop(‘PassengerId’, axis=1, inplace=True)<br>testing.drop(‘Name’, axis=1, inplace=True)<br>testing.drop(‘Ticket’, axis=1, inplace=True)</pre><pre>final_test = testing<br>final_test.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Z1aZ1Ea7vUQcDbge6UdoeQ.png" /></figure><p>Now, for a small dataset like this, we are left with too many features. In the previous post, we used only 8 features, so let’s try selecting top 8 features. Feature ranking with <strong>recursive feature elimination(RFE)</strong> helps us in doing so. It is available as a function in sci-kit learn. More on RFE can be found <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.RFE.html">here</a>. But for this recursive operation to converge, we need to scale down the values in the training data as RFE does not apply scaling operation itself, which can lead to bad feature selection.</p><pre>sc = StandardScaler()</pre><pre>final_train[[“Age”, “Fare”]] = sc.fit_transform(final_train[[“Age”, “Fare”]])<br>final_test[[“Age”, “Fare”]] = sc.fit_transform(final_test[[“Age”, “Fare”]])</pre><pre>final_train.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*G8pgG7vnb0yyzevPd6o2Kg.png" /></figure><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.feature_selection import RFE</pre><pre>cols = [“Age”, “SibSp”, “Parch”, “Fare”, “Pclass_1”, “Pclass_2”, “Pclass_3”, “Embarked_C”, “Embarked_Q”, “Embarked_S”, “Sex_male”]</pre><pre>X = final_train[cols]<br>y = final_train[‘Survived’]</pre><pre>model = LogisticRegression()</pre><pre># selecting top 8 features<br>rfe = RFE(model, n_features_to_select = 8)<br>rfe = rfe.fit(X, y)</pre><pre>print(‘Top 8 most important features: ‘ + str(list(X.columns[rfe.support_])))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*XP4HowwpUjAIXoh867HIkw.png" /></figure><p>Now, that we these features, let’s finally go and apply Logistic Regression on our training data.</p><pre>selected_features = [‘Age’, ‘SibSp’, ‘Pclass_1’, ‘Pclass_3’, ‘Embarked_C’, ‘Embarked_Q’, ‘Embarked_S’, ‘Sex_male’]</pre><pre>X = final_train[selected_features]\<br>y = final_train[‘Survived’]</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=2)</pre><pre>logreg = LogisticRegression()<br>logreg.fit(X_train, y_train)<br>y_pred = logreg.predict(X_test)<br>y_pred_proba = logreg.predict_proba(X_test)[:, 1]</pre><pre>print(‘Train/Test split results:’)<br>print(“Logistic Regression accuracy is: “ + str(accuracy_score(y_test, y_pred)))<br>print(“Logistic Regression log_loss is: “ + str(log_loss(y_test, y_pred_proba)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*6uXqTWWYJALUY8EJAmqnEQ.png" /></figure><p>We get around 78% accuracy, which is decent. When I submitted my submission file on Kaggle by predicting the Survived values on the test dataset they provided, I got a public score of 0.7703, which is good considering the fact that we applied nothing other than logistic regression. The way we processed data helped us in getting this score. Without data pre-processing, our results would have been way worse. The entire code for this post can be found <a href="https://www.kaggle.com/vardaanbajaj/kernel6a7859f833?scriptVersionId=36752368">here</a>.</p><p>Phew!! This was a long post. Thank you all for bearing with me and making it this far. Believe me the strategies we went through in this article are used by Data Scientists across the world on a daily basis. Even I used these strategies during my internship period. In the <a href="https://medium.com/analytics-vidhya/contents-9b2e49f49fe9">next</a> post, we’ll have a detailed look at underfitting and overfitting problems in machine learning and see techniques to address these problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=728e6a9d4bbf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/machine-learning-ii-logistic-regression-explained-data-pre-processing-hands-on-kaggle-728e6a9d4bbf">Deep Dive Into Logistic Regression and Data Pre-Processing</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[Introduction to Machine Learning and Deep Dive into Linear Regression]]></title>
            <link>https://medium.com/analytics-vidhya/machine-learning-i-introduction-linear-regression-explained-bc5bfee25832?source=rss-168771086803------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc5bfee25832</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <dc:creator><![CDATA[Vardaan Bajaj]]></dc:creator>
            <pubDate>Mon, 15 Jun 2020 20:19:38 GMT</pubDate>
            <atom:updated>2020-07-22T15:53:53.844Z</atom:updated>
            <content:encoded><![CDATA[<h3>Contents</h3><p>In this post, we’ll be going through:</p><p>1. Introduction to Machine Learning</p><p>2. Different types of Machine Learning problems</p><p>3. Cost function for Linear Regression</p><p>4. Gradient Descent Algorithm</p><p>5. Hands on Multivariate Linear Regression problem on a Kaggle Dataset.</p><h4>What is Machine Learning?</h4><p>Remember the first code you wrote on a computer? Majority of us start with ‘Hello World’ programs but think of the time you wrote something that made you feel proud of yourself. For most of the computer science enthusiasts out there, these might be either solving the entire programming assignment on your own or solving competitive programming questions. Let’s not forget that for the majority of us, these have been the initial steps that have helped us dive into the world of computer science.</p><p>Since computers perform deterministic operations, all these programs have the same template. We supply the logic (rules) for the program and the input (data) and the program gives us the desired output. But for machine learning, things are different. Machine learning is a field of computer science where we supply the input (data) and the output and leave it to the machine learning algorithms to generate the rules for the input-output mapping. Once these rules are generated, we can use them to make predictions for any given input data related to this context.</p><p>In this series of blogs, we’ll be exploring Machine Learning in depth by looking at all the concepts, some of the mathematics behind it to gain insights into working of machine learning algorithms and at the end of each post, we’ll be solving a real-life problem (preferably from Kaggle) using the concepts mentioned.</p><p>There are 2 ways we can make a computer learn things we want it to, either spoon-feed (supervised learning) it or leave it to explore (unsupervised learning).</p><h4>Supervised Learning</h4><p>How humans learn through examples is an analogy to supervised learning. In supervised learning, we provide our machine a labelled data set i.e. we provide both, the input and the output and by applying one of the various supervised machine learning algorithms (models), we expect our machine learning model to learn the mapping between input and output. Supervised learning algorithms are divided into 2 broad categories:</p><p><strong>(i) Classification Algorithms</strong></p><p><strong>(ii) Regression Algorithms</strong></p><p>In classification problems, the output is divided into a fixed number of classes and the job of the classification algorithm is to predict the probability of the class that most likely matches with the data fed into the algorithm.</p><p>In regression problems, the output can be any number (in case of numerical output) and the job of the regression algorithm is to predict the closest numerical value for the data fed to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*DMYTWmCSaUAOoIrC53WlRw.png" /><figcaption>Image source: <a href="https://www.javatpoint.com/regression-vs-classification-in-machine-learning">https://www.javatpoint.com/regression-vs-classification-in-machine-learning</a></figcaption></figure><p>Supervised learning has found its applications in Healthcare, Natural Language Processing, Stock Price Prediction systems to name a few.</p><h4>Unsupervised Learning</h4><p>In unsupervised learning, we feed our algorithm with unlabelled data and leave it to the algorithm to find patterns in the data. Unsupervised learning problems are quite overwhelming to work on since there is no simple way to evaluate their performance. Unsupervised learning algorithms are divided into 2 broad categories:</p><p><strong>(i) Clustering Algorithms</strong></p><p><strong>(ii) Association Algorithms</strong></p><p>Clustering deals with finding a structure or pattern in a collection of unlabelled data. Clustering algorithms process data and find natural clusters (groups) if they exist in the data. We can tell our algorithm to categorize a certain number of clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*sSgYdTU4JZ5JhZmZ4ygfww.png" /><figcaption>Image source: <a href="https://www.datacamp.com/community/tutorials/k-nearest-neighbor-classification-scikit-learn">https://www.datacamp.com/community/tutorials/k-nearest-neighbor-classification-scikit-learn</a></figcaption></figure><p>Association is concerned with establishing associations among data objects in large databases. One example is the recommendation system of Amazon where after buying a certain item, it suggests the user other products to buy.</p><p>In this post and the upcoming posts, we’ll dive into supervised machine learning algorithms and problems. After getting a good look into supervised learning problems, we’ll have a look into unsupervised learning problems as well.</p><p>One of the most simple supervised machine learning technique is Linear Regression. Linear Regression can be easily implemented in python using sci-kit learn library with the assistance of pandas and numpy, but first let us understand how this algorithm works.</p><h3>Linear Regression</h3><p>Consider a straight line y=Wx+b. In coordinate geometry terms, x and y are variables, W is the slope of this line and b is the intercept on the y axis. We supply various x values to the this equation and the corresponding y values on the graph result in a straight line, given the values of W and b. In machine learning terms, ‘x’ is the ‘input data’, y is the ‘output’ and W and b are the parameters that we want the linear regression algorithm to learn to give the ‘rules’ so that it can generalize to new input data.</p><h4>Division of Training and Test Sets</h4><p>We need a good amount of data for our training algorithms to learn the x -&gt; y mappings (rules) in order to get optimum values of W and b. For datasets with &lt; 10,000 records, it is preferred to have an 80–20 train-test split i.e. only 80% of the data is used to train the model and the rest 20% is used to evaluate its performance. Additionally, we can also use development set to tune the model’s parameters but the problem we’ll be solving later in this post is a small dataset, so we’ll not use dev set for now.</p><h4>How does learning take place?</h4><p>For a good linear regression model, we want W and b values to be an optimum one i.e. they learn from the input data and acquire such values so that they can generalize results to new data. So, the main question that arises is how to get the optimum values for these parameters. For this let’s have a look at the cost function.</p><h4>Cost function for Linear Regression</h4><p>Let’s denote the predicted values of the linear regression model by y_hat. The main idea behind the cost function is to obtain W and b such that y_hat is close to y for our training examples represented by (x,y) pairs. In other words, we are going to solve a minimization problem on W and b and our cost function will enable us in doing so. Let’s denote our cost function with J. The cost function will help us choose the optimum values of W and b. There are tons of cost functions out there but the one we’ll be using for linear regression is very intuitive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*D6iMUXIqpgSQ-DvOjtQs1g.png" /><figcaption>Image source: en.wikipedia.org</figcaption></figure><p>The above image is an example of Linear Regression (with one variable i.e. y=Wx+b) in action, where the blue dots are the training examples and the red line is the output of a linear regression model. This line passes roughly between all the blue points. In other words, this line has the minimum overall distance from all the possible lines that exists in this 2D plane, which leads us to using the ‘Euclidean Distance’ as the loss function. For the training example (x_i, y_i) and the corresponding prediction (x_i, y_hat _i), Euclidean Distance is defined as:</p><p>L = (y_hat_i — y_i)²</p><p>Note that we have removed the square root without the loss of generality. Now, we need to find the values for W and b that minimize this loss function. Here, we’ll make use of derivatives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*Pk5pKetcJcT94fIUdwByKw.png" /></figure><p>Considering that we have ‘m’ training examples the cost function is defined as:</p><p>J = sum_over_all_training_examples((y_hat_i — y_i)²)</p><p>Remember that we initialize W and b randomly, so, since we have a quadratic equation, these random values will give us a value at some point in this parabolic graph. Our goal is to reach the minima of the graph. By taking the derivative of the of the cost function J wrt W and b gives us the slope of the graph and we want to continue this process until our slope becomes ideally zero (practically very close to zero).</p><p>Let’s think for a moment about the parameters needed to achieve this objective. We want to make sure that we crawl towards the minima, not too slow, not too fast. Crawling slowly towards the minima involves taking small steps and moving rapidly towards the minima involves taking large steps and sometimes these large strides can result in jumping over the minima to the point of no return. Clearly, we need to define a parameter that controls this process. In machine learning, we call this parameter the ‘learning rate’ denoted by ‘alpha’. The algorithm that helps us perform this shift towards the minima is called Gradient Descent.</p><h4>Gradient Descent</h4><p>Gradient Descent is a self-explanatory term and the whole algorithm lies in the meaning of this term. Gradient is just another name for slope/derivative we talked about previously and descent just means to drop/fall. So, the job of gradient descent is to take the starting point on the cost function curve and just drop it at every step until it reaches the minima and report the optimum values of the parameters (here W and b). Let us define the variables ‘delta_W’ and ‘delta_b’ that help us to terminate the algorithm at convergence. If the change between 2 consecutive updates of the W is less than the ‘delta_W’ and that of b is ‘delta_b’, we can terminate the gradient descent algorithm. Pseudo code for gradient descent is as follows:</p><pre>temp_W = temp_b = random_values<br>flag_W = flag_b = False<br>do<br>if ((abs(W — temp_W) &gt; delta_W) and flag_W = False)<br>    temp_W = W — alpha * partial_derivate_wrt_W(J)<br>if ((abs(b — temp_b) &gt; delta_b) and flag_b = False)<br>    temp_b = b — alpha * partial_derivative_wrt_b(J)<br>if(temp_W == W)<br>    flag_W = True<br>if(temp_b == b)<br>    flag_b = True<br>W = temp_W<br>b = temp_bwhile True</pre><p>Gradient descent is implemented with a lot of optimizations in python’s machine learning libraries. Our main aim here was just to get an understanding of how gradient descent works.</p><p>The formula for partial derivatives for the cost function (here Euclidean distance) can be found <a href="https://math.stackexchange.com/questions/2297660/derivative-of-vector-consisting-of-euclidean-distances">here</a>.</p><p>With this, we have reached the end of this section where we discussed Linear Regression with 1 variable (x). In case of more than one variable, our equation of the line is slightly modified as follows;</p><p>Y = W1x1 + W2x2 + W3x3 + ……… + Wnxn + b ……….(1)</p><p>where there are total n number of input features. Representing the predicted values by y_hat, our cost function for Linear Regression with multiple variables becomes:</p><p>J = sum_over_all_training_examples((y_hat_i — y_i)²)</p><p>Here, we’ll put y_hat_i as equation (1) and y_i as the original value for the training example i.</p><p>In the gradient descent algorithm, we’ll compute partial derivatives of the cost function for all the parameters (W1, W2, …. Wn, b) and then update these parameters until convergence.</p><p>Since we’ve developed an understanding of how Linear Regression works, let’s dive into a <strong>problem from Kaggle</strong> in order to cherish this accomplishment.</p><h4>Problem Statement</h4><p>Click <a href="https://www.kaggle.com/mohansacharya/graduate-admissions?select=Admission_Predict_Ver1.1.csv">here</a> for the dataset. This dataset has 8 features and one output variable. Since the output values are real number values, this is a regression problem. This problem can be stated as multivariate linear regression problem as:</p><p>Y = W1x1 + W2x2 + W3x3 + W4x4 + W5x5 + W6x6 + W7x7 + W8x8 + b</p><p>Let’s see how python packages help us in solving this linear regression problem.</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn import datasets, linear_model<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import mean_squared_error, r2_score</pre><p>We have imported numpy for linear algebra and other mathematical operations, pandas for data pre-processing and sklearn for applying linear regression and evaluating the model’s performance.</p><pre>df = pd.read_csv(‘/kaggle/input/graduate-admissions/Admission_Predict_Ver1.1.csv’)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*osTj6GN8SVpG_oIFhnUe3Q.png" /></figure><p>We read the input csv file through pandas and display the first 5 rows to study the properties of the data. Here, all the values are either integers or floating point numbers. If we had strings or other data types, we would have to parse them and convert them to numerical form to feed it to our linear regression model. The given data has 500 records, which is pretty small.</p><pre>X = df.iloc[:, 1:-1].values<br>y = df.iloc[:, -1].values<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.15)</pre><p>First of all, we separate our input and output values. Observe that we have ignored the serial no. column as serial no. has no effect on admission chances. Further, we split our data into corresponding training and test sets. We use 85% of the data for training and 15% of data for testing.</p><pre>regressor = linear_model.LinearRegression()<br>regressor.fit(X_train, y_train)<br>y_pred = regressor.predict(X_test)</pre><p>Now, we initialize the LinearRegression object from the scikit-learn library and feed it our training data for the linear regression algorithm to fit the best possible line for it. By default, the mean_squared_error cost function is used for training the model, so we don’t need to explicitly mention it here.</p><p>Let’s have a loot at first 5 predicted output values.</p><pre>print(y_pred[:5])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*TRZKdTBq92CoxCAsyJDuTw.png" /></figure><p>To conclude, let’s have a look at the weight parameters and the r² score</p><pre>print(‘Coefficients: \n’, regressor.coef_)<br>print(‘R2 Score: %.2f’ % r2_score(y_test, y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*B020EAnGxCJYruITaftMug.png" /></figure><p>r² score of 0.83 tells us that we are making predictions with 83% confidence and is a metric used to evaluate regression problems. More on r² score can be found <a href="https://en.wikipedia.org/wiki/Coefficient_of_determination">here</a>. These are good results for a small dataset like this one. We can apply feature selection techniques which can lead our model to be more accurate. But since this is a very small dataset, this can lead to over-fitting. We’ll discuss about these problems and techniques in later posts.</p><p>The code for this post can be found <a href="https://www.kaggle.com/vardaanbajaj/kernel440c3f9443/">here</a>.</p><p>That’s it for this post. In the <a href="https://medium.com/analytics-vidhya/machine-learning-ii-logistic-regression-explained-data-pre-processing-hands-on-kaggle-728e6a9d4bbf">next</a> post, we’ll have a detailed look at logistic regression. I’d love to hear your feedback for this post so please leave your invaluable suggestions down below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc5bfee25832" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/machine-learning-i-introduction-linear-regression-explained-bc5bfee25832">Introduction to Machine Learning and Deep Dive into 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>
    </channel>
</rss>