<?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 Arunank Divya Sharan on Medium]]></title>
        <description><![CDATA[Stories by Arunank Divya Sharan on Medium]]></description>
        <link>https://medium.com/@arunanksharan?source=rss-44790c6c6ebb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lnklehFEhMU488H_9Ljxwg.png</url>
            <title>Stories by Arunank Divya Sharan on Medium</title>
            <link>https://medium.com/@arunanksharan?source=rss-44790c6c6ebb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:05:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arunanksharan/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[Part IV: Decision Trees]]></title>
            <link>https://medium.com/datadreamsdragons/part-iv-decision-trees-4992e2038a00?source=rss-44790c6c6ebb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4992e2038a00</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Arunank Divya Sharan]]></dc:creator>
            <pubDate>Fri, 09 Nov 2018 18:09:46 GMT</pubDate>
            <atom:updated>2018-11-09T18:09:46.756Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Decision Trees, referred to as DT from now onwards, are simple, intuitive and versatile algorithms.</strong></p><h3><strong>Basic Flow of Decision Trees</strong></h3><p>In essence, it is just a <strong>series of Yes or No questions on different features</strong>! Based on this series of Yes or No questions, the predictor space (a fancy name for all the independent variables i.e. X =&gt; X1, X2, X3, …, Xn) is split into segments. It is important to note that these segments are distinct and non-overlapping.</p><p>Intuitively, we can think of this process as developing flowchart for a computer program. We used to ask these questions like:</p><ul><li>Is i &gt; 99? If yes, then stop the loop else continue the next loop</li><li>Does ‘apple’ contain ‘a’? If yes, then increase count of ‘a’ by 1 else do nothing.</li></ul><p>Similarly, here, we ask, is feature1 &gt; threshold1? If yes, split the predictors into two segments. Segment 1 has the value of feature1 &gt; threshold1 and Segment2 has the value of feature1 &lt;threshold1. This process is then repeated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GpU6NGfxLjHieeJj" /><figcaption><strong>Image 1: Basic Flow of Decision Trees</strong></figcaption></figure><p>Referring to the image above, DT algorithm asks the following questions for every instance.</p><ul><li>For Split 1 at X1 = 8: Is X1 (feature) less than 8 (threshold)? If ‘Yes’, the instance is assigned to segment S1, else it is assigned to other segment which comprises of segment S2 and segment S3 at this moment.</li><li>Once all instances are assigned to either segment S1 or the combination of segment S2 and segment S3 i.e. the first split at X1 = 8 is completed, the second split is carried out at X2 = 7.</li><li>It is important to note here that segment S1 is pure i.e. comprised only of single class (Class I) after the first split is completed. So, it does not participate in second split at X2 = 7. The second split is carried out only in the other segment comprising of segment S2 and segment S3.</li><li>For Split 2 at X2 = 7: Is X2 (feature) less than 7 (threshold)? If ‘Yes’, the instance is assigned to segment S2, else it is assigned to segment S3.</li><li>After Split 2, we have three pure segments i.e. each of S1, S2, S3 comprise of instances belonging to single class only. Thus, no further splitting is required and the Decision Tree is ready.</li></ul><p>Please note that the above illustration was a very simple example to just provide a taste of how the DT algorithm flows.</p><p><strong>Let us now denote jth segment created by splitting as Sj.</strong></p><ul><li>If the output/response variable (Y_training) is continuous, this obviously becomes a <strong>Regression</strong> task. We calculate the mean of all the output/response variable values that are present in the jth segment denoted by Sj. Our Y_predicted for segment Sj is this mean value!</li><li>If the output/response variable (Y_training) is categorical, this becomes a <strong>Classification</strong> task. We calculate the mode i.e. most frequently occurring category or class among all the output/response variable values that are present in the jth segment denoted by Sj. And voila, our Y_predicted for segment Sj is this mode value!</li><li>In addition, in Classification, we may also be interested in determining the class proportions of training observations falling in segment Sj. It means, we are interested in finding the number of observations that belong to each different class in a particular segment Sj.</li></ul><p>The above description gave us an intuitive feel as to how the DT algorithm flows.</p><p>If this feels too much, do not despair! It will become clearer if you refer to the image shown below and the discussion based on Iris Dataset on the process of splitting and the different components involved in this algorithm.</p><p>In a nutshell, when applying DT algorithm:</p><ul><li>Take a dataset.</li><li>Ask the predictors a series of Yes or No questions. This will create segments (Sj).</li><li>Calculate mean of all response values in a segment for Regression. This is Y_predicted.</li><li>Calculate mode of all response values in a segment for Classification. This is Y_predicted.</li><li>DT is ready. Simple and elegant, isn’t it!</li></ul><h3><strong>Key Questions</strong></h3><p>Let us now get into the key questions that are associated with the DT algorithm. We will address these questions alongside discussion for Classification by DT.</p><ul><li><strong>What are splits?</strong></li><li><strong>What is the basis for making splits/segments? How does the DT know where to make the split? (Similar Questions)</strong></li><li><strong>What is meant by the statement that DT is a greedy algorithm?</strong></li><li><strong>What is meant by recursive binary splitting?</strong></li><li><strong>What is the associated Cost Function for Regression and Classification tasks?</strong></li><li><strong>What are the ‘pros and cons’ of DT?</strong></li></ul><h3><strong>Classification Using Decision Trees</strong></h3><p>Let us start with Classification using Decision Trees. Personally, I find Classification using DT to be more intuitive.</p><p>We will use one of the simplest and most famous datasets: Iris Dataset for this discussion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*yTsI4iCB2z3q0EdT" /><figcaption><strong>Image 2: Decision Tree (with depth=2) for Iris Dataset Visualized</strong></figcaption></figure><p><strong>The above shown graph has been created using export_graphviz from sklearn. It is a very important and handy tool to visualize Decision Trees.</strong></p><h4><strong>What are splits?</strong></h4><p>Split (as shown in the image above) is the process of segmenting at a node. A split happens at a node and children nodes are created. Using the same Tree analogy, trees are ‘grown’ i.e. splits are made or nodes are created through an upside down approach.</p><p>The first split that is made at the top of the tree is called the <strong>Root Node</strong>. It is assigned a depth of 0. It is node #0 in the image above.</p><p>Similarly, the points along the tree where the predictor space is split are called <strong>Internal Nodes</strong>. They have one or more children nodes. It is node #2.</p><p>Finally, the final nodes without any child node are called ‘leaves’ or <strong>Terminal Nodes</strong>. These are node #1, node #3 and node #4 in the image above.</p><h4><strong>What is the basis for making splits?</strong></h4><p>To understand this, we need to first look into different attributes/properties associated with every node.</p><ul><li><strong>Samples: </strong>It is a count of the number of training instances a node applies to. e.g. It will be the entire length (number of observations/instances) of training dataset for the Root Node.</li><li><strong>Values: </strong>It is a count of the number of training instances of each class that a node applies to.</li><li><strong>Gini Impurity: </strong>It measures a node’s impurity. A node is said to be ‘pure’ if it has all the training instances it applies to (samples) belonging to the same class.</li></ul><p>With these three attributes of a node known to us, we can now look into how a DT is created. Creating and training a DT is called ‘growing a tree’!</p><p><strong>The first split or Root Node is created by using a single feature f and threshold t(f). This pair of f and t(f) is chosen in way that the resulting subsets that are created, are the purest.</strong></p><p>Thus, the algorithm goes through different pairs of feature f and threshold tf till it finds the one pair resulting in purest subsets. For every pair, the DT algorithm follows the following steps:</p><ul><li>It selects a pair of feature f(1) and t(f1) for splitting.</li><li>Then, it selects a training instance (i) and asks the Yes or No question: Is the value of feature f(1) for the instance (i) less than the threshold or not? If the answer is ‘Yes’, the instance (i) is assigned to one of the children nodes (say, the left child node). If the answer is ‘No’, the instance (i) is assigned to the other or the right child node.</li><li>Once the instance is assigned to a child node, the DT also keeps a count of the values i.e. how many instances belong to which class using the known labels (Y_training). Thus, it determines if the resulting split into children nodes producing the purest subsets or not. This is the Cost Function that DT looks to minimize. In other words, it looks to minimize impure subsets after splits.</li></ul><p><strong>More formally, the Cost Function is shown in the image below</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a8ZB5cqmtqX30Sr4" /><figcaption><strong>Image 3: Cost Function for Classification</strong></figcaption></figure><h4><strong>What is Gini Impurity?</strong></h4><p>Gini Impurity is a measure of node impurity. If a node is pure i.e. contains instances only belonging to the same class, Gini is zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*42EQfi0odfcqg1uK" /><figcaption><strong>Image 4: Gini Impurity</strong></figcaption></figure><p><strong>Let us calculate Gini Impurity for Root node as shown in Image 2 above.</strong></p><ul><li>Root Node: node #0: Samples = 150. This means that there are total of 150 instances this node applies to. It is obvious as it is the Root Node where the first split is being made. So, it will apply to all the observations (X_training) in the training set.</li><li>i = 0 i.e. node is 0</li><li>j takes the value of 1,2,3 as it represents the three classes (Setosa, Versicolor, Virginica).</li><li>For j=1 i.e. class Setosa, there are 50 training instances.</li><li>For j=2 i.e. class Versicolor, there are 50 training instances.</li><li>For j=3 i.e. class Virginica, there are 50 training instances.</li></ul><p><strong>Thus, calculating p for node #0 or Root Node:</strong></p><ul><li>i=0, j=1: p(0,1) = Ratio of instances of class Setosa in total training instances at node #0 = (Value of Setosa at node #0/Samples at node #0) = (50)/(150) = 1/3</li><li>i=0, j=2: p(0,2) = Ratio of instances of class Versicolor in total training instances at node #0 = (Value of Versicolor at node #0/Samples at node #0) = (50)/(150) = 1/3</li><li>i=0, j=3: p(0,3) = Ratio of instances of class Virginica in total training instances at node #0 = (Value of Virginica at node #0/Samples at node #0) = (50)/(150) = 1/3</li></ul><p><strong>Calculating Gini Impurity for node #0 i.e. G(0):</strong></p><p>G(0) = 1 — (p(0,1))²— (p(0,2))² — (p(0,3))² = 1 — (1/3)² — (1/3)² — (1/3)² = 1 — (3/9) = ⅔ = 0.667 (as shown in Image 1)</p><p>Similarly, calculation of Gini Impurity can be made using the Value and Samples attribute for every node. You should try calculating it as an exercise.</p><h4><strong>What is entropy?</strong></h4><p>Similar to Gini Impurity, there is another way to measure node purity called Entropy. If the node has instances belonging only to single class, entropy becomes 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IwE2y47w0fecLpYY" /></figure><p>Let us perform a calculation similar to the one we performed above for Gini Impurity. This time, we calculate for node #4. We use the Value and Samples attribute for this node.</p><ul><li>Terminal Node: node #4: Samples = 46. This means that there are total of 46 instances this node applies to.</li><li>i = 4 i.e. node is 4</li><li>j takes the value of 1,2,3 as it represents the three classes (Setosa, Versicolor, Virginica).</li><li>For j=1 i.e. class Setosa, there are 0 training instances. So, this will be ignored.</li><li>For j=2 i.e. class Versicolor, there is 1 training instance.</li><li>For j=3 i.e. class Virginica, there are 45 training instances.</li></ul><p><strong>Thus, calculating p for node #4:</strong></p><ul><li>i=4, j=1: p(4,1) = Ratio of instances of class Setosa in total training instances at node #4 = (Value of Setosa at node #4/Samples at node #4) = 0/46</li></ul><p>However, in case of Entropy calculation, p(i,j) cannot be 0 as we need to calculate log(p(i,j)) which becomes undefined if p(i,j) = 0. So, p(4,1) is ignored.</p><ul><li>i=4, j=2: p(4,2) = Ratio of instances of class Versicolor in total training instances at node #4 = (Value of Versicolor at node #4/Samples at node #4) = 1/46</li><li>i=4, j=3: p(4,3) = Ratio of instances of class Virginica in total training instances at node #4 = (Value of Virginica at node #4/Samples at node #4) = 45/46</li></ul><p><strong>Calculating Entropy for node #4:</strong></p><ul><li><strong>H(4)</strong> = — (p(4,2)log(p(4,2)) + p(4,3)log(p(4,3))) = — ((1/46)*log(1/46) + (45/46)*log(45/46)) = 0.0455</li></ul><p>This low value of Entropy indicates the node is pure which is evident from the fact that there are 45 instances of Virginica and 1 instance of Versicolor out of total 46 Samples.</p><h4><strong>What is meant by recursive binary splitting?</strong></h4><ul><li>Once the Root Node has been created i.e. the first split has been made, the above mentioned steps are followed again and again for different nodes using different features (say f(2)) and thresholds (t(f2)). This is called Recursive Binary Splitting into subsets. Thus, the segment 1 (S1) and segment 2 (S2) created after the first split are then again split into further subsets using f(2) and t(f2).</li><li>With each splitting, depth of the tree increases by 1.</li><li>It continues this split or segmentation of predictor space into smaller and smaller subsets till one of the two following things happen: It reaches the maximum depth defined by the max_depth parameter or there is no further split that can reduce the impurity in the subsets and produce the purest subsets.</li><li>Some other constraints can also be defined to stop this process of recursive splitting such as defining the minimum number of samples a child node can have after the split or the minimum number of samples that a leaf node can have.</li></ul><h4><strong>What is meant by the statement that DT is a greedy algorithm?</strong></h4><p>It is computationally very expensive to evaluate every possible combination of splitting of predictor space into j segments (as discussed earlier). So, the DT approaches the objective of producing the purest subsets after splitting at every node with a ‘greedy’ intent. DT selects the best split at every step and does not consider whether such a split at the present step will ultimately lead to a better step in the future. Thus, DT selects the combination of feature f and threshold t that produces the purest subsets at the present step without any thought for the future steps.</p><h3><strong>Regression using Decision Tree</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fY518Mm7EC8Ugb24" /></figure><p>DT tries to split the training set at Root Node in a way that MSE and, in turn, the Cost Function is minimized.</p><p>If you want to read Regression by Decision Trees in greater detail, you can always look up Page 304, 305, 306 and 307 in ISLR.</p><h3><strong>What are the ‘pros and cons’ of DT?</strong></h3><h4><strong>The major pros are considered to be the following:</strong></h4><ul><li>Decision trees mirror human decision-making.</li><li>As seen in Image 1 above, Decision Trees can be easily represented graphically. This makes them easy to visualize and interpret, especially if they are of a small size.</li><li>Decision Trees do not require significant amount of pre-processing of data such as scaling or centering. In fact, they can even handle qualitative predictors (categorical input variables) without creating dummy.</li></ul><h4><strong>The major cons are:</strong></h4><ul><li>Decision Trees have a strong tendency to overfit unless the hyperparameters are controlled properly and regularization is performed. We will study Regularization separately for the different algorithms.</li><li>Small changes in data may cause large changes in the final model. They are very sensitive to training data and, thus, are non-robust.</li><li>Decision Trees have orthogonal decision boundaries. Thus, they sensitive to training set orientation and rotation. Principal Component Analysis may need to be used which we will study as part of Dimensionality Reduction in a later post.</li></ul><p>In this post, we covered the workings of Decision Trees. There are certain concepts of overfitting, pruning of tree and parameters of testing the model that have not been covered. We will cover them in a separate post on avoiding overfitting and regularization. Right now, the goal is to first become comfortable with how the different algorithms are working, their Cost Function and how they are trained.</p><p>See you soon in Part V! I hope you have enjoyed the posts so far. Please do clap and share if you like this post and respond with queries, recommendations and criticisms!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4992e2038a00" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datadreamsdragons/part-iv-decision-trees-4992e2038a00">Part IV: Decision Trees</a> was originally published in <a href="https://medium.com/datadreamsdragons">DataDreamsDragons</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part III: Logistic Regression]]></title>
            <link>https://medium.com/datadreamsdragons/part-iii-logistic-regression-4a024c896ed?source=rss-44790c6c6ebb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a024c896ed</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cost-function]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <dc:creator><![CDATA[Arunank Divya Sharan]]></dc:creator>
            <pubDate>Thu, 08 Nov 2018 05:31:04 GMT</pubDate>
            <atom:updated>2018-11-08T07:37:15.745Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Logistic Regression is one of the most widely used algorithms in the industry!</strong></p><p>But, first, <strong>let us recap</strong> on our journey so far.</p><p>First, we went through a gentle introduction to ML which discussed ML on a high-level.</p><p>Then, we understood the general flow of any ML algorithm which involved the following steps:</p><ol><li>General structure of dataset (Labelled/Supervised or Unlabelled/Unsupervised)</li><li>Discovering the underlying function (Y is the function of X: Y = f(X))</li><li>Cost Function to represent the difference between Y_training (known labels) and Y_predicted (based on X_training)</li><li>Training or determining model parameters that minimize the Cost Function</li></ol><p>We studied all the parts in the flow of an ML algorithm for Linear Regression. This post will be an extension of the same flow for the mighty Logistic Regression.</p><p>Remember, how we saw that Linear Regression is essentially fitting a straight line to the given data points. Logistic Regression, in essence, is just an extension of Linear Regression.</p><p><strong>The major difference between Linear Regression and Logistic Regression is that Linear Regression is used where the output variable is continuous while Logistic Regression is used where the output variable belongs to one of the given classes/categories (Classification).</strong></p><p>The data is represented as given in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wB55RcqTkzY2DSCS4XXxJg.jpeg" /></figure><p>Let us take this step-by-step to keep it simple and easy.</p><h4><strong>Step I: Logistic Regression calculates weighted sum of input variables.</strong></h4><p>Let us assume the case with single variable again:</p><ul><li>X_training is Age</li><li>Y_training was Height in cm for Linear Regression.</li><li>For this case, let us assume Y_training is categorical with the class ‘Short’ representing Height &lt; 100 cm and the class ‘Tall’ representing Height &gt;= 100 cm. This categorization has just been done to make the output categorical.</li></ul><p><strong>In this step, the same computation as Linear Regression happens and a straight line is fitted.</strong></p><p><strong>The calculation made is: Step_I_Output = mX + c</strong></p><p>If we use this Step_I_Output as Y_predicted, it will be a number while the Y_training (known) is actually categorical.</p><p><strong>So, how do we solve this problem?</strong></p><p>One way could be to define a threshold for the value of Y_predicted, say 100. If the value of (mX + c = Step_I_Output) is greater than or equal to 100, the particular instance will be assigned to the class ‘Tall’ and vice-versa (‘Short’ if Step_I_Output &lt; 100).</p><p>However, there are multiple problems with this approach including the case that what happens when the value of Step_I_Output falls to less than 0.</p><p><strong>In a classifier, it makes more intuitive sense to be able have an output between 0 and 1 which can be interpreted as a probability of belonging to a particular class. The class ‘Tall’ is taken as the positive class here and denoted as 1 while the other class ‘Small’ is taken as negative class and denoted with 0. This leads us to the second step.</strong></p><h4>Step II: Logistic Function</h4><p><strong>Step_I_Output is fed into a logistic function. Thus, the logistic of Step_I_Output is the final Step_II_Output which is used as the estimated probability of belonging to a particular class (‘Tall’ or positive class).</strong></p><p>I think the previous sentence packed a bit too much in it. The obvious questions you may be thinking of are:</p><ul><li>What is the Logistic Function?</li><li>What is the Step_II_Output? What is meant by the logistic of Step_I_Output?</li><li>How can Step_II_Ouput be used as estimated probability of belonging to a particular class? How can it be suddenly a probability? After all, Step_I_Output is mX + c and can be any number! What sorcery is this?!!!</li></ul><p><strong>Let us start with “What is the Logistic Function?”</strong></p><p>It is simple. It is just a mathematical function which takes a number as input and outputs another number, just like any other function! However, it is special in the sense that the output it gives is a number between 0 and 1. It is also called Sigmoid Function and has an S-shaped curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eVQnBrErIjwIqQPy" /><figcaption><strong>Logistic or Sigmoid Function: Equation</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K-ZahX8PTO0gcA80" /><figcaption><strong>Logistic or Sigmoid Function: Graph</strong></figcaption></figure><p>And make no mistake, this is no coincidence! This function has been deliberately chosen so that the Step_I_Output, which is weighted sum of features (mX + c) and can be any number, is converted into a number between 0 and 1 which can represent probability of belonging to a class.</p><h4>Step III: Predicting Y_predicted for training</h4><p>Once we have found Step_II_Output which is probability (p) that the instance belongs to the positive class, Y_predicted for the training instance can be easily obtained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fmYASu8ypqXC4t-2" /><figcaption><strong>Flow of Logistic Regression</strong></figcaption></figure><p>Now let us obtain a generalized version of this in vectorised form. If you remember, the vectorised form was written for a training instance as shown in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hbsGYcCQaqdvJ6aj" /><figcaption><strong>Vectorized Representation for an Instance</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AI05KUl0Ebdm6pmp" /><figcaption><strong>Steps in Logistic Regression</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O-cut1jFS9_SLTvP" /><figcaption><strong>Logistic Regression: Prediction</strong></figcaption></figure><h4><strong>Cost Function</strong>: Log Loss</h4><p>In Linear Regression, we used a straight line to estimate the actual relationship between X_training and Y_training. Then formulated a Cost Function of Mean Squared Error (MSE) to determine how far off our estimated relationship, which outputted Y_predicted, is from the actual one or Y_training. Here, higher the value of MSE, greater was the difference between estimated and actual relationship.</p><p>Similarly, for Logistic Regression, we need a Cost Function which indicates this problem i.e. the value of Cost Function needs to be high when the model predicts an instance or observation as belonging to a particular class (say ‘Tall’ or positive or 1) while it actually belongs to the other class (‘Small’ or negative or 0). Cost Function needs to be high when the model makes an error and misclassifies the instance.</p><p>The ultimate goal in training of an ML algorithm is to estimate the parameter vector m which minimizes the Cost Function, which in turn indicates that the estimated relationship between X_training and Y_training is close to the actual one.</p><p>For Logistic Regression, we need to find parameter vector m which ensures that the model outputs high probability (as close to 1 as possible) for any instance belonging to the class ‘Tall’ or positive or 1 and low probability (as close to 0 as possible) for any instance belonging to the class ‘Small’ or negative or 0.</p><p>The Cost Function shown in the image is called the Log-Loss function. Let us see the possible cases for a single training instance for this log loss function as the general equation looks a bit intimidating!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8cMK8mfKeto9wNT8" /><figcaption><strong>Log Loss Function: Cost Function for Training Set</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fcREw8_3j5jFfC6P" /><figcaption><strong>Log Loss for Single Instance with graph of Logarithm Function</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dP2ct051nI2-BXkg" /><figcaption><strong>Interpretation of Log Loss Cost Function for a Single Instance</strong></figcaption></figure><p><strong>It is important to note that there is no mathematical or closed-form equation i.e. there is no solution available to us that resembles the Normal Equation we saw for the Linear Regression.</strong></p><p>The approach to minimize this Cost Function, thus, use optimization algorithms like Gradient Descent by randomly initializing the weights and the reiterating towards minimizing the Cost Function.</p><p>Thus, Logistic Regression is a binary classifier in this form. It can be generalized and extended into a multi-class classifier known as Softmax Classifier or Multinomial Logistic Regression.</p><p>It uses Softmax Function instead of Sigmoid function. The Cost Function used here is Cross Entropy.</p><p>We will not be discussing these in detail here to keep things simple and keep us focused on Logistic Regression as binary classifier.</p><h4>An often asked question:</h4><p><strong>Why is Logistic Regression considered part of generalized linear models when its actual output is not linear?</strong></p><p>It is easy to see why it is considered a linear model if you are clear with nature the Step_I_Output. It is the weighted sum of input features (mT.X). Thus, these features are additive in nature. There is no term in which the input features are being multiplied or divided or have any other type of interaction between themselves.</p><p>So, that ends our journey with the basic flow and functioning of Logistic Regression!</p><p>I will be discussing the different ways to evaluate a model such as Confusion Matrix, AIC, AUC-ROC Curve in separate posts where we will go through them one by one.</p><p>With this background, you are now ready to go through Chapter 3 and 4 of ISLR (Introduction of Statistical Learning in R).</p><p>See you soon in the next post on Decision Trees! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a024c896ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datadreamsdragons/part-iii-logistic-regression-4a024c896ed">Part III: Logistic Regression</a> was originally published in <a href="https://medium.com/datadreamsdragons">DataDreamsDragons</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithms: The Pillars of Data Science]]></title>
            <link>https://medium.com/datadreamsdragons/algorithms-the-pillars-of-data-science-72543d0e1473?source=rss-44790c6c6ebb------2</link>
            <guid isPermaLink="false">https://medium.com/p/72543d0e1473</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Arunank Divya Sharan]]></dc:creator>
            <pubDate>Tue, 06 Nov 2018 14:33:57 GMT</pubDate>
            <atom:updated>2018-11-15T09:26:20.590Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Part II: Algorithms: The Pillars of Data Science</strong></h3><p>A data scientist without his algorithms is like Joker without chaos, Bane without darkness, Obi wan Kenobi without his force, Wakanda without vibranium and Thanos without his gauntlet! I could go on but you get the gist!</p><p>As Bane says, you do not only adopt the algorithms! You need to be born in it! Molded by it! Or they will betray you and you will just be a man without plan like the Joker!</p><p>Enough said!</p><p><strong>Let us start with a high level classification of algorithms used:</strong></p><ol><li><strong>Supervised Learning</strong></li><li><strong>Unsupervised Learning</strong></li></ol><p>(There are other types of as well which are not mentioned or explained here! Remember, No Overfitting!)</p><h4>Supervised Learning</h4><p>In supervised learning, there are independent (or input or predictor or feature or X) variables which are used to predict the dependent (or output or predicted or response or target or Y) variable.</p><p>The key point here is that for the training set, we also have the corresponding value of target variable i.e. the desired solution or labels. We have the values for Y for every instance of X.</p><p>This is different from the Unsupervised learning where the value of Y is not available for the training dataset.</p><p>(Optional: For anyone looking to go into more detail, the below mentioned link is very useful:)</p><p><a href="https://www.statisticshowto.datasciencecentral.com/independent-variable-definition/">https://www.statisticshowto.datasciencecentral.com/independent-variable-definition/</a></p><p>Within supervised learning, the output variable can be of two types: Continuous and Categorical</p><ol><li>Continuous Output (Y): In this case the the output variable can take a value on a continuous range. For such cases, we use Regression (a common example being Linear Regression). e.g. Prediction of price of houses (Kaggle)</li><li>Categorical Output (Y) : The output variable belongs to one of the two or more classes/categories. We use Classification (a common example being Logistic Regression). e.g. The most famous dataset — Predicting Survival for Titanic Passengers: The objective is to predict whether the output belongs to class 0 (Did Not Survive) or class 1 (Survived).</li></ol><h4><strong>Regression:</strong></h4><p>We will start with Linear Regression since it is a simple and intuitive way to understand what is happening. There are other algorithms as well which can perform Regression. We will discuss that in the later posts.</p><p>Right now, the first objective is to develop an intuition for the commonly used jargon and terms and the basic flow of how any algorithm works. (Prioritize!)</p><h4><strong>Linear Regression and Flow of ML in general</strong></h4><p>Before we start, let me make it clear — Linear Regression is just a fancy name for a straight line! See, not so difficult now, is it! We all know the equation of a straight line:</p><p>y = mx + c</p><ul><li>y = Output/Dependent/Response/Predicted variable</li><li>x = Input/Independent/Feature/Predictor variable</li><li>m = Slope</li><li>c = Intercept/Bias (in ML) and it is same as m0 used later.</li></ul><p>That is all there is to Linear Regression in a nutshell!</p><p>Surprised and disappointed? Don’t be! Let us dive deeper now.</p><h4><strong>General Structure of Dataset in Supervised Learning</strong></h4><p>Imagine a case: (Read slowly and carefully! Read it again and then again and then once more!)</p><ul><li>You are given the age of 5 children between 0 and 15 years. This is your independent/input variable X. It will be the training set.</li><li>You are given the corresponding height of these 5 children in centimeters. This is your dependent/output variable Y. It is a continuous variable. This data is already known. This will form the output for the training set.</li><li>You are asked to predict the height for the 6th child based on age which will be provided. This is the test set i.e. you will need to predict Y for a previously unseen X.</li><li>In a nutshell, this means you have been asked to build a Regression model to predict the height of a child given the age.</li></ul><p>Now, go back and read the case once more!</p><p>If you are able to visualize this and separate the different parts in your head:</p><ul><li>training data, X_training or input in training data, Y_training or known output in training data, Y_predicted or predicted output based on training data</li><li>test data, X_test or input in testing data, Y_test which is unknown, Y_test_predicted or predicted output based on testing input data,</li></ul><p>mark my words — you have won a significant battle!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYiQIlCzw-JLOnBdmF09yw.png" /></figure><p><strong>The above is the basic structure of data that you will receive for any Supervised Learning task.</strong></p><p>Since the output is continuous, it is Regression. If the output was categorical, the task would be Classification.</p><h4><strong>General Flow of Machine Learning Modelling</strong></h4><h4><strong>1. Discovering the ‘Function’</strong></h4><p>If you were one of the diligent ones in your 11th standard, you might recall from basic algebra and calculus, we studied something called ‘functions’. Functions based expressed how one varying quantity (Y) depended on another (X). Basically, the function f() represented the link between X and Y. It was written as:</p><p><strong>Y = f(X); Y is the function of X.</strong></p><p>In ML, as you go deeper, you will see a close parallel happening in the algorithms.</p><p>In the above dataset and in fact, in any dataset for supervised learning, there will be X_training and Y_training which is known. This X_training and Y_training will have a relationship between themselves.</p><p>Our objective in ML is to discover a function which closely resembles this relationship between X_training and Y_training. We are not looking for an exact and perfect function but a reasonable estimation.</p><p>(Note: This estimation is not the end in itself. There is another part to it which is generalization. The generalization performance of a model indicates its prediction capability on independent and previously unseen test data. This is our ultimate goal — to predict the output for previously unseen data correctly and efficiently! This aspect is discussed briefly in a later post on Bias-Variance Tradeoff and separately with respect to every model. :))</p><p>This process of estimating the function is called modelling an ML algorithm. This function may be linear, exponential, polynomial etc.</p><p>In Linear Regression, we assume that this relationship is linear and it can be represented by a straight line. So, we take a straight line and pass it through the training data with the objective of trying to find the best slope (m) and intercept or bias (c ), so that the line is able to resemble the actual relationship as closely as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M-KYxVbPmpE9RrFI" /><figcaption>Essence of linear regression: Fitting a straight line</figcaption></figure><p>Thus, Linear Regression makes predictions by using a weighted sum of input features (mx) and a constant term or intercept or bias (c ). To keep things simple, I have assumed only a single input (Age) for this particular example.</p><p>We will venture into the territory of multivariate regression now!</p><p>The names appear scary but in reality, it is another fancy name for a case where the input variable is more than 1 in number. e.g. Weight is added as another input variable in addition to Age in the above example. Thus, for every single point, the equation will become:</p><p><strong>Y_predicted = m0 + m1 * Age + m2 * Weight</strong></p><ul><li>m0 is the intercept or bias here (same as c shown in the image).</li></ul><p>We can generalize this as given below in form of matrix. Please observe the image given below very carefully and try and understand what is happening.</p><p><strong>In matrix notation: Y_predicted = X.M</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cvbM1jB9a62gTiR0" /><figcaption>Matrix Form</figcaption></figure><p>(In some cases, you will see an additional irreducible error term after X.M. We omit that here to keep it simple. I will explain that in bias-variance tradeoff discussion).</p><p><strong>Let us select a particular instance, say y2. </strong>This can be represented in vectorised form as shown in image below. For the vectorised form, we will use m as notation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i-RP77Cks3jRKMkM" /></figure><p>Our goal is to calculate the values in the M matrix or m vector which are the ‘parameters’ of this algorithm. We need to find that value of M which minimizes Cost Function. What is Cost Function and how is this minimisation achieved? It is discussed in the points below.</p><h4><strong>2. The ‘Cost Function’</strong></h4><p>Remember, as we discussed in the previous point, we are trying to estimate a function that represents the actual relationship between X_training and Y_training.</p><p>This function gives an output Y_predicted based on X_training.</p><p>Please be very clear on this point: Y_predicted on X_training is different from Y_training which is already known.</p><p>Just to be clear, I am repeating myself for the nth time — there are three different components:</p><ul><li>X_training</li><li>Y_training which is known for training set</li><li>Y_predicted which is predicted by the model during training based on X_training as input</li></ul><p>Now, we are estimating a function which can output Y_predicted which is as close to Y_training which is already known. The objective is to minimize the difference between Y_predicted and Y_training! The smaller the gap, the better our estimated function resembles the actual relationship between X_training and Y_training. This is what is meant by the statement — ‘how well does a model fit the data’!</p><p>First, we need a metric, a measure or number of some sort which measures this difference between Y_training and Y_predicted. Then, we need a way to somehow minimize that difference between Y_training and Y_predicted for the training set.</p><p>This is where the ‘Cost Function’ comes into picture. And make no mistake, Picture abhi baaki hai mere dost! Also, keep in mind that different algorithms have different cost functions.</p><p><strong>Mean Squared Error:</strong></p><p>For Linear Regression, we use a metric called Mean Squared Error (MSE) as the cost function.</p><p>Please do not be afraid of the name! It is what is says. Let us break it down.</p><h4><strong>Mean + Squared + Error</strong></h4><p><strong>a. Error:</strong> This is the difference of Y_training and Y_predicted for every point.</p><ul><li>Point 1: (82.5–79.6) = 2.9 cm</li><li>Point 2: (94.2–97.3) = -3.1 cm</li><li>Point 3: (112.9–115) = -2.1</li><li>Point 4: (47–45.7) = 1.3 cm</li><li>Point 5: (160–159.2) = 0.8 cm</li></ul><p><strong>b. Squared:</strong></p><ul><li>Point 1 Squared: (2.9)² = 8.41</li><li>Point 2 Squared: (-3.1)² = 9.61</li><li>Point 3 Squared: (-2.1)² = 4.41</li><li>Point 4 Squared: (1.3)² = 1.69</li><li>Point 5 Squared: (0.8)² = 0.64</li></ul><p><strong>c. Mean:</strong> (Point 1 Squared + Point 2 Squared + Point 3 Squared + Point 4 Squared+ Point 5 Squared)/(Total Number of Points or Instances i.e 5) = (8.41+9.61+4.41+1.69+0.64)/5 = 4.952</p><p><strong>So, you calculate the error for every point/instance in training, square the error and take its mean. And, voila, you get the Mean Squared Error.</strong></p><p>This cost function, as we discussed, measures how far our estimated function or model is from the actual relationship and the goal is to minimize this value of MSE.</p><h4><strong>3. Minimising Cost Function: Training the Model</strong></h4><p>We discussed earlier that the ultimate objective is to estimate the M matrix from the equation Y = X.M in a way that it minimizes the Cost Function i.e. MSE for Linear Regression.</p><p>This is called training the model. There are different approaches to achieve this.</p><ul><li><strong>Normal Equation Approach:</strong> For Linear Regression, this can be done mathematically. It is clear that the equation is Y = X.M in the matrix form. Also, we saw another representation for the ith instance in the vectorized form. Here, the values of X_training (shown as X in the image) and Y_training are already known to us. Thus, all we need is to perform for linear algebra operations.</li></ul><p>In the end, we get the solution as shown in the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O45ncCGArj1xWxoA" /></figure><p>This M is the value that will minimize the cost function and will be used for predictions.</p><p>There is an important catch here, however. This method becomes very slow if the number of input features becomes very large as it involves calculating the transpose and inverse of large matrices (X_training).</p><ul><li><strong>Gradient Descent Approach: </strong>Here, the values in the M matrix is randomly initialized i.e. we randomly assign values to M. Then, predictions are made. After that, the values in the M matrix are changed bit-by-bit (iteratively) in a way that the Cost Function decrease and ultimately reaches a minimum.</li></ul><p>The details of how this approach works will be discussed separately. I have kept it brief here so as to keep this post to the point with respect to the general workings of ML algorithm.</p><p>So, concluding this discussion on general flow of ML algorithms and Linear regression in particular, we need to keep in mind the following points:</p><ul><li>What is the structure of dataset?</li><li>Are the values for Y_training i.e. output variable available for training dataset meaning that is it a Supervised or Unsupervised learning problem</li><li>Is the Y_training i.e. output variable continuous or categorical meaning that is it a Regression or a Classification problem?</li><li>The goal is to discover the function f() which closely represents the actual relationship between X_training and Y_training. This function f() outputs Y_predicted based on X_training data.</li><li>Cost Function is used to determine how closely the function f() estimated above resembles the actual relationship between X_training and Y_training. The goal is to minimize the Cost Function.</li><li>Mean Squared Error is used as the Cost Function for Linear Regression. Different algorithms have different Cost Functions.</li><li>For Linear Regression, direct mathematical solution can be used to calculate the value of M which minimizes the Cost Function and obtains a good model. This mathematical solution is not available for other algorithms like Logistic Regression.</li><li>Gradient Descent is a generic approach for finding the optimal value of M matrix.</li></ul><p>The concept of Bias-Variance Tradeoff and Regularisation will be discussed in separate posts.</p><p>Phew! That was a lot! If you have made it this far, you truly are a ‘Special One’, my friend.</p><p>In my next post, I will discuss Logistic Regression in detail.</p><p>See you there soon! Sayonara!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72543d0e1473" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datadreamsdragons/algorithms-the-pillars-of-data-science-72543d0e1473">Algorithms: The Pillars of Data Science</a> was originally published in <a href="https://medium.com/datadreamsdragons">DataDreamsDragons</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning: An Introduction]]></title>
            <link>https://medium.com/datadreamsdragons/machine-learning-an-introduction-88a7187bcbfd?source=rss-44790c6c6ebb------2</link>
            <guid isPermaLink="false">https://medium.com/p/88a7187bcbfd</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Arunank Divya Sharan]]></dc:creator>
            <pubDate>Tue, 06 Nov 2018 14:07:10 GMT</pubDate>
            <atom:updated>2018-11-08T07:22:42.706Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part I: Machine Learning: An Introduction</h3><p><strong>Hi everyone,</strong></p><p><strong>This is the first post in a series of many that will soon come on anything and everything around data science.</strong> So, grab a double espresso and join me on this ride! :)</p><p><strong>There are two quotes which have always stuck with me.</strong></p><ul><li>“Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away.” — Antoine de Saint-Exupery (French Writer)</li><li>“80% of the effects come from 20% of the causes.” — Vilfredo Pareto (Italian Economist)</li></ul><p>I have tried to model my every endeavour on these two principles of simplicity and prioritisation of key factors. Data Science is no different!</p><h4><strong>Keep things simple! Prioritize!</strong></h4><p>This and the following write-ups will be an effort to reach out and explain the core aspects of Machine Learning after removing all the noise and clutter. The goal is to keep these posts a light read but provide enough context for you to understand what is going on. Wherever possible, I will use data science jargons in a general context to help build an intuitive ‘feel’ for it.</p><p>So, in this journey, our goal will be to behave like a well-fitted machine learning model where neither unnecessary details are added (No Overfitting!) nor important details are left out (No Underfitting!).</p><p>Occasionally, some external links will be added at some places for those interested in going deeper. For others, please be rest assured that the content given in the posts will be sufficient to get a thorough understanding of ML and answer any interview questions.</p><p>The most frequently asked questions by anyone starting out in this field are</p><ul><li><strong>What is Machine Learning?</strong> (From now onwards, I will refer Machine Learning as ML because I am lazy!)</li><li><strong>How is it different from AI? Is it AI?</strong> (This question will be addressed in a separate post. Remember, No Overfitting!)</li><li><strong>Why, where and when do we use ML?</strong></li></ul><h4><strong>Let us tackle the first question: What is ML?</strong></h4><p>If you search long enough, you will realize that there are so many definitions, all given in different contexts and for different use cases. Some are technical, others more generic.</p><p><strong>To keep things simple, I like this definition -</strong></p><p>“A computer program is said to learn from experience <em>E</em> with respect to some class of tasks <em>T</em> and performance measure <em>P</em> if its performance at tasks in <em>T</em>, as measured by <em>P</em>, improves with experience <em>E</em>.” — Tom Mitchell (American Computer Scientist)</p><p>It is formal enough to give a taste of engineering perspective while simultaneously being generic enough to provide an intuitive ‘feel’.</p><p>The three key aspects are:</p><ul><li><strong>Task (T): </strong>This can be framed in terms of what we are looking to achieve, say, classification or regression.</li><li><strong>Experience (E):</strong> This can be framed as every observation that is used to train a model and every mistake it makes. Cost function and updating weights can be said to be a ‘Learning Experience’ for the model. (Friends, Indians, Countrymen! I come to explain, not to confuse you!)</li><li><strong>Performance (P):</strong> This can be framed as a metric used to assess how well our model is achieving the desired target. For a classification task, it may be accuracy or f-score. (Explanation is coming!)</li></ul><h4><strong>The Why, When and Where of ML</strong></h4><p>Now, let us tackle the other often asked questions with respect to ML. On a generic level, these are the main conditions where it is suitable to use ML.</p><ul><li>There is no mathematical solution easily available. The problem is too complex to obtain a traditional solution. So, instead of completing a PhD in mathematics and becoming a maths wizard, we use ML approach which detects the patterns and does the heavy lifting for us.</li><li>There is a decent amount of data present. Without a decent amount of data, it is difficult to use ML.</li><li>There is a pattern in data. If the data is completely at random, it may become difficult for ML algorithms to achieve any prediction power.</li><li>The problem has so many different variations that it is not feasible to write rules for all the different cases. ML approach helps us find patterns which can generalize better to unseen data. The ML model can adapt to changing data. Otherwise, the rule-based system may have to be written from scratch if the new and previously unseen data changes drastically.</li></ul><p>Let us stop here and keep the post at this digestible length. It is best to avoid the trap of TL;DR!</p><p>Based on my experiences in interviews and interacting with experienced people working in the industry, the above written content is all that you will need to tackle generic interview questions discussing ML and its use cases at a meta-level. In the second post, we will start with the algorithms.</p><p>Just as a good ML algorithm and model building requires data to be cleaned and pre-processed, similarly, you need to to pre-process yourself and be prepared with the prerequisites mentioned below before you move into the next post of algorithms.</p><h4>If you are really serious about learning ML, please go through:</h4><ul><li>Page 1 to 41 of Introduction to Statistical Learning in R.</li><li>It includes Chapter 1: Introduction and Chapter 2: Section 2.1, Section 2.2. It is fine if you are not able to exactly understand Section 2.2: Bias-variance Tradeoff. It will be discussed later.</li></ul><p>See you there, soon! Ciao, ciao!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88a7187bcbfd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datadreamsdragons/machine-learning-an-introduction-88a7187bcbfd">Machine Learning: An Introduction</a> was originally published in <a href="https://medium.com/datadreamsdragons">DataDreamsDragons</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>