<?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 Sidharth Sekhar on Medium]]></title>
        <description><![CDATA[Stories by Sidharth Sekhar on Medium]]></description>
        <link>https://medium.com/@sidharths758?source=rss-58435b5eda82------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-nLlgbQACuWGbIVn.jpg</url>
            <title>Stories by Sidharth Sekhar on Medium</title>
            <link>https://medium.com/@sidharths758?source=rss-58435b5eda82------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:30:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sidharths758/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[Intuition and working behind AdaBoost]]></title>
            <link>https://medium.com/analytics-vidhya/intuition-and-working-behind-adaboost-1c559f8d7a73?source=rss-58435b5eda82------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c559f8d7a73</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sidharth Sekhar]]></dc:creator>
            <pubDate>Wed, 04 Sep 2019 12:15:49 GMT</pubDate>
            <atom:updated>2019-09-09T04:02:49.718Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Intuition and working behind AdaBoost</h3><p>There are multiple machine learning algorithms that classify data. We have seen the working of <a href="https://medium.com/analytics-vidhya/math-behind-support-vector-machines-642421e45b08">Support Vector Machines</a> and <a href="https://medium.com/analytics-vidhya/logistic-regression-b35d2801a29c">Logistic Regression</a> in the previous blog posts, now it’s time to explore another algorithm called AdaBoost or Adaptive Boosting. This is a variant of Decision Tree algorithm.</p><p>AdaBoost is a part of bigger set of algorithms that belong to methods called Ensemble learning. The entire idea behind Ensemble learning is to create multiple learning models instead of one model and predict the values.</p><p>AdaBoost does this process of predicting the value by creating multiple weak learners, associating a weight to each data point based on the predictions of that point in each learner and finally giving the output.</p><p><strong>Weak Learners and Boosting :</strong></p><p>They are basically multiple models(in this case Decision Tree) that are run on subset of data features. These weak learners have one particularly interesting property that we will take advantage of while creating boosting algorithms which is underfitting or low variance.</p><p>To understand better look at the diagram below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*131sBdM2wNqbj5IBp_bFCw.jpeg" /><figcaption>Multiple Decision stumps</figcaption></figure><p>Let us assume we have to predict whether someone is going to buy a house or not using Machine Learning algorithms. Instead of creating one decision tree or logistic regression model to predict, what we do is create multiple weak learner i.e. Decision Stumps or poor logistic regression model or tree with depth 1 or 2, one after the other to predict the output. In AdaBoost we rig the system in such a way that features that are predicted poorly in previous learner are predicted with better results in the subsequent model.</p><p>Let us give an example input to the above Decision stumps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*-jD-SGLBbGSAb17ne_TgaQ.gif" /><figcaption>input to the stumps</figcaption></figure><p>The <em>Numbedroom</em> in the above input is ‘<em>2</em>’, this will go to the primary stump and yield prediction ‘<em>+1</em>’. The <em>sqft </em>will go to the second stump and will yield a prediction of ‘<em>+1</em>’, <em>Lawn </em>will get a prediction of ‘<em>-1</em>’ and similarly <em>Area</em> will get a prediction of ‘<em>+1</em>’ . So the final question that we need to ask is , how do we combine all these predictions from various weak learners and give one final prediction to the above data point?. This is done with the formula below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*24N7Pv8Goe7VVFx24Fy39w.gif" /><figcaption>weighted voting scheme for 1st data point</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*KzTQRnOLvrAGvHiQJF2EFA.gif" /><figcaption>Predictions from each scheme i.e. +1 or -1</figcaption></figure><p>We basically take the final sign after we multiply a weight associated with each stump is multiplied with the prediction and added with the rest of the values from each stump.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/1*e2oCyMEht7dVhGntT_Z_Ew.gif" /><figcaption>Equation of final prediction. L number of stumps.</figcaption></figure><p><strong>AdaBoost:</strong></p><p>The way AdaBoost works is as follows:</p><p>1.) Primarily each data point is initialized with a weight ‘<em>alpha</em>’ that is equal to (1/number of data points).</p><p>2.) Then for each weak learner or model, we iterate to calculate the predicted value, then go onto compute the weight ‘<em>w</em>’(weighted error) and based on that re-adjust the ‘<em>alpha</em>’ term for next iteration until the very end.</p><p>3.) After all the iterations are done we calculate the prediction based on the above equation.</p><p>There are two fundamental questions with respect to AdaBoost that we need to ask here, How are we going to update the weights ‘<em>w</em>’ and how are we going to update the ‘<em>alpha</em>’ values.?</p><p>In this algorithm what we do is add all the weights of data points that have been miss-classified and divide it by the weight of all data points i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/101/1*I-eJUBiTTOf0BcPHoiNOQA.gif" /><figcaption>Summing over weights of misclassified points</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*rWhYyl-6meBTC5Lv1A202Q.png" /><figcaption>Weighted error formula</figcaption></figure><p>Following the creation of weighted error, we ensure that we update the weight associated with each stump , whose formula is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*xies2dpxdSsAV6SMzQk2aA.gif" /><figcaption>updating weight for each stump</figcaption></figure><p>The above equation is a very interesting one:</p><p>For a value of weighted error = 0.5, it will yield a ‘0’ since the output as (1/2) * log(1) equals 0 while a a good decision stump that classifies the points in a right way will have very low weighted error which implies a high value for ((1-weighted_error)/weighted_error), taking the half of log of this value will yield a positive weight with high value. For stumps with poor classifications the weights will be pretty low.</p><p>In the section below on updating ‘<em>alpha</em>’ , we will see why decision stumps with good classification have high weights and stumps associated with poor classification have low value for weights.</p><p>After the weights are updated we update alpha’s in such a way that the points that are classified wrongly are given more importance than the points classified correctly thereby ensuring that our machine learning model caters to miss-classified points more. This is done with the help of the exponent function.When predictions are correct the alphas associated with each data point are updated using the below formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/123/1*CyNKQF-vKvEZX_5QegBVbg.gif" /><figcaption>i -&gt; For each data point, j-&gt;for each stump</figcaption></figure><p>When the predictions are incorrect, then we update the alpha value associated with each data point using this formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/113/1*E8MXki8nLzJTH220qCIKfA.gif" /><figcaption>i -&gt; For each data point, j-&gt;for each stump</figcaption></figure><p>The use of the exponential function with negative and positive sign here is critical as each time a point is classified right we use a negative value on top of the exponent along with the weight associated with the stump. A high value for ‘<em>w</em>’ means points that are classified right are given less importance in the next stump. In the event that a stump has done miss-classified on certain set of data points, the alpha value associated with those points will have higher value in the next stump there by giving them more importance.</p><p>Finally, once we have all our stumps based on our training data along with associated weights(not the weighted_error but the weights associated with each stump), we calculate the predictions for the data that has to be classified with,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/1*e2oCyMEht7dVhGntT_Z_Ew.gif" /><figcaption>Equation of final prediction. L number of stumps.</figcaption></figure><p>The github gist is given below.</p><p><strong>Note: </strong>The gist is only for adaboost and not for creating a decision stump</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a739f2c65b78074b821dea6b25e0498/href">https://medium.com/media/1a739f2c65b78074b821dea6b25e0498/href</a></iframe><p>Feel free to point out any errors in comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c559f8d7a73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/intuition-and-working-behind-adaboost-1c559f8d7a73">Intuition and working behind AdaBoost</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[Math Behind Support Vector Machines]]></title>
            <link>https://medium.com/analytics-vidhya/math-behind-support-vector-machines-642421e45b08?source=rss-58435b5eda82------2</link>
            <guid isPermaLink="false">https://medium.com/p/642421e45b08</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <dc:creator><![CDATA[Sidharth Sekhar]]></dc:creator>
            <pubDate>Tue, 27 Aug 2019 08:25:16 GMT</pubDate>
            <atom:updated>2019-09-02T04:13:20.716Z</atom:updated>
            <content:encoded><![CDATA[<p>We have seen about <a href="https://medium.com/analytics-vidhya/logistic-regression-b35d2801a29c">Logistic </a>Regression in one of our previous posts on classification. In this post, we will look at another machine learning algorithm which is support vector machines.</p><p>Support Vector machines create n-dimensional hyperplanes to segregate the data based on parameters. If the data has 2 variables then it’s a line, 3, it’s a plane and so on.</p><h4><strong>Problem Definition:</strong></h4><p>Consider a classification problem, with two classes. The objective is to find a hyperplane that classifies the two-classes in such a way that we maximize the margin between the points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*ltHWLdqzaomul_4DUt8_iA.png" /><figcaption>Visualizing Support vectors</figcaption></figure><p>In the above picture there are two classes that are differentiated by the shape in which they are depicted. The ‘<em>+</em>’ sign is set of points whose classification is ‘-<em>1</em>’ while the ‘<em>o</em>’ is for the ‘<em>+1</em>’ class. The points which are in colors blue and orange are called the support vectors. The entire goal of support vector machines is to maximize the distance between the two dotted lines i.e. the separation between the two class’, the street there is as wide as possible.</p><h4><strong>Intuition:</strong></h4><p>Let us consider all points in a support vector problem as a vector. i.e. it has magnitude and direction. The way that the points are classified as ones that belong to a positive class or negative class is by taking the vector of the point(<em>x</em>), projecting it onto another vector ‘<em>w</em>’ that is perpendicular to the middle line in the picture(The middle line will be called the median line hence). If that projection value is greater than a constant ‘<em>c</em>’, then it isa positive sample else it is negative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/75/1*BkGQkzTsPRIxl4oMymyFjQ.gif" /><figcaption>Dot product of two vectors, with x being the input and w the perpendicular vector to the median line</figcaption></figure><p>The above equation can be written as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/105/1*-y6iOY6A24mlA9oMbbY2zw.gif" /><figcaption>With c = -b</figcaption></figure><p>The above equations give the basic intuition of Support vector machines with any value that equates to zero will be on the hyper plane.</p><p>Let us take the above equation and frame it for every positive class ‘<em>+1</em>’ and every negative class ‘<em>-1</em>’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*9dPhCPKPESQtfdo9Zr0Yuw.gif" /><figcaption>For positive class</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/1*4ASA1oqUEDuUAeQYBlmcTA.gif" /><figcaption>For negative class</figcaption></figure><p>The distance between the values [-1,1] is the margin which we try to maximize. To make it mathematically convenient, we introduce another variable ‘<em>y</em>’ and combine the above two equations into one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*2WTWSjRRMT0KLlnHwf9Arg.gif" /><figcaption>yi=+1 for positive class and yi = -1 for negative class</figcaption></figure><p>So for any points within the street, the equation translates to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*vdzGHFtZ_Mf7Nte-Fge8dg.gif" /><figcaption>Equation 1 for values in the street.</figcaption></figure><p>Let us consider two points on the dotted lines, one on the positive side and the other on the negative side ,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*KsG2iwwYLoM--oK7sxg3LA.png" /></figure><p>We need to find the distance between the two dotted lines or the street as we call it. So let us consider a unit normal vector. Since we used ‘<em>w</em>’ as a normal vector to the median line, we will take that and divide it by its magnitude to get unit normal vector. Let the vectors representing the points for negative and positive be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/19/1*atIZCr1VQI35GwReBMZePg.gif" /><figcaption>Vector for the point in negative class</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/20/1*HXTf3BHd3NIqZ0c8xN-jhQ.gif" /><figcaption>vector for the point in positive class</figcaption></figure><p>Both of these points lie on the dotted line on either side of the street which implies the difference between these two points and the dot product of unit normal will be the width of the street.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*XUxqbgRbWvWTGFAlLoJ_0w.gif" /></figure><p>Now substituting the values for ‘<em>x+</em>’ and ‘<em>x-</em>’ in the above equation from equation 1 we get the value before taking the dot product for ‘<em>x+</em>’ and ‘<em>x-</em>’ with unit normal vector ’<em>w</em>’ gives</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*cCNHJzLahgmcZ6YXxcFCZg.gif" /></figure><p>This yields</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/49/1*Ig-y23-AU_Nlh5jxNKpWmg.gif" /><figcaption>Maximizing the value for SVM</figcaption></figure><p>This can be written alternatively as minimizing ‘<em>w</em>’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/48/1*2HkOjt_CvF6GIcBZ0TXF-A.gif" /><figcaption>1 in numerator as it is a constant value.</figcaption></figure><p>and to make it mathematically convenient we can convert the equation to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/79/1*8Sho-vugzIl45lxIXl5R4w.gif" /><figcaption>Minimizing value for SVMs</figcaption></figure><p>Now if we use the Lagrangian multiplier to maximize the above equation with the constrain in equation 1, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*bF5ItbjM-oI5gU8saIRgbw.gif" /><figcaption>Using Lagrange multiplier, equation 2</figcaption></figure><p>If we take in the derivative of ‘<em>w</em>’ and ‘<em>b</em>’, set it to zero and substitute that back in equation 2, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*xOCCeqiR4QOpBogMq_sAgQ.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*2gVDB6jTibFqpD2wvBpzXQ.gif" /></figure><p>When we set the above two equations to zero and substitute it into equation 2, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*ZQFLwf8nlhyEl5k_PgxhBA.gif" /></figure><p>Which when simplified gives</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*cEXMSjlMQCld7qaxXwLo3Q.gif" /></figure><p>One can clearly observe this equation depends on the dot product of the sample values in ‘<em>x</em>’.</p><p>Until now we have talked about linearly separable classes i.e. when there is no overlapping of data points in the dataset. However, in an actual dataset this is not possible, there will be certain data points that are on either side and we need our support vector machine model to take this into consideration and still produce a the best hyper plane.</p><p>This is done with the introduction of slack variable into the traditional support vector machine equation. The slack variable penalizes the points that are not on the right side of hyper plane. In the below equation it is the eta, while C is a hyper parameter we need to tune to tell how much we penalize each error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*zZ1vVUbP03XfbKl2H_7G5w.gif" /></figure><p>The above equation is subjected to the constraint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*5u-0tj7mevU874ys2awIyA.gif" /></figure><p>Then our entire SVM equation boils down to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*4HQNrnSPPFC5IzzydLajEQ.gif" /></figure><p>The hyper parameter ‘<em>c</em>’ defines by what margin we penalize the error. The larger the value of ‘<em>c</em>’ , greater is the chance for the model to become a hard margin classification.</p><p>The loss function that is associated with support vector machines is called Hinge loss as, the second term is ‘<em>0</em>’ if the value of second term within the max function is negative and it is ‘<em>1</em>’ if the second term within the max function is 0.</p><blockquote>The github gist is</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94c0d4422d79c4b59aca3467a3968f8f/href">https://medium.com/media/94c0d4422d79c4b59aca3467a3968f8f/href</a></iframe><blockquote>Feel free to comment if you find any errors.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=642421e45b08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/math-behind-support-vector-machines-642421e45b08">Math Behind Support Vector Machines</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[Math behind Linear, Ridge and Lasso Regression]]></title>
            <link>https://medium.com/analytics-vidhya/math-behind-linear-ridge-and-lasso-regression-b9de216ebdf8?source=rss-58435b5eda82------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9de216ebdf8</guid>
            <category><![CDATA[math]]></category>
            <category><![CDATA[lasso-regression]]></category>
            <category><![CDATA[ridge-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Sidharth Sekhar]]></dc:creator>
            <pubDate>Fri, 23 Aug 2019 04:37:36 GMT</pubDate>
            <atom:updated>2019-08-28T04:26:21.895Z</atom:updated>
            <content:encoded><![CDATA[<p>Regression models are used to predict the values of the dependent variable based on the values of independent variables/variables. The most used linear models are Linear Regression, Ridge Regression, and Lasso Regression. This article is not one that is going to be talking about the applications of these three models but the intuition behind these models and the math behind it. If you want an introduction to these models, check out the other <a href="https://medium.com/me/stories/public">articles</a> that I have written on them.</p><p>There are 2 well known ways as to how a linear model fits a line through the data points.</p><ul><li>The ordinary least squares method</li><li>The Gradient Descent method.</li></ul><p>In this article we are going to explore Gradient Descent method. The mathematical equation that is used to predict the value of the dependent variable that is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*YSCAncjdh0gw40K9UP9lLQ.gif" /><figcaption>Equation of linear model</figcaption></figure><p>The above mentioned equation is what the a Machine learning model tries to optimize. It tries to pick the best set of weights (w) for each parameter(x).</p><p>Now having said that the linear regression models try to optimize the above-mentioned equation, that optimization has to happen based on particular criteria, a value that has to tell the algorithm that one set of weights is what is best when compared to other sets of weights. This value is called the cost function, which is given by the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*GTVK5SSt79dBlCP8ar03Lw.gif" /><figcaption>Cost function, with n being the number of observations</figcaption></figure><p>where the difference between the actual value of y and the predicted value is called the error term .</p><p><strong>Reason for mean squared error(Assuming one independent variable):</strong></p><p>When we expand the squared error term algebraically, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*2At9OmuP_3HV_H9mgs0Muw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*lVJeAipYUF62ZozGUr3owQ.gif" /></figure><p>Expanding the squared terms again and grouping the like terms we get,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*dylryH7Ne3OFCtrCQNh2GA.gif" /></figure><p>After this once we take the mean or average of the terms in bracket we get the equation. For <em>y </em>alone we are going to see and the rest of the terms are similarly arrived at</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*PDZ3TCfsE6thV35B7AaGcA.gif" /></figure><p>we get the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Q2bB3GlzVhh5io69eUSw_g.gif" /></figure><p>If you actually observe the above equation, it is obvious that barring the weights(w0,w1) or coefficients the rest of the terms are constants. So we need to find the values for (w0,w1) that minimizes the above equation. For doing that, imagine plotting w0 and w1 and for values of w0 and w1 that satisfies the equation, one will get a convex curve with minimum at lower most point</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*Rxn7PH2Hdu6S7CxJ_dQ8dQ.png" /><figcaption>Minimum at lowest point, red dots are costs associated with different values of w0,w1</figcaption></figure><p>This curve is important, you will get to know why in the sections below.</p><p>The entire idea is simple, start with random initialization of weights, keep multiplying it with each feature and then sum them up to get the predictions, compute the cost term and try to minimize the cost term iteratively based on the number of iterations or a tolerance value below which iteration will be stopped. Thus we generate a certain number of regression lines for particular data points and pick the one that has the least cost.</p><p>Until now we have established a cost function for the regression model and we have seen as to how the weights with the least cost get picked as the best fit line. All seems well but there is a slight catch here — random selection of weights for 100(example) iterations can give us 100 different sets of weights and 100 different lines. The machine can pick the best line from among them but it will be difficult to say that this line is the best fit line as there can be many combinations better than the 100 we picked.</p><p>So we need to find a way to systematically reduce the weights to get to the least cost and ensure that the line created by it is indeed the best fit line no matter what other lines you pick. This can be better understood in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*sKxRBbdaLzydTOWcAsv47Q.png" /><figcaption>Convex curve with global minima at the red dot.</figcaption></figure><p>If we consider the above curve as the set of costs associated with each weights, the lowest cost is at the bottom most point indicated by the red curve. Our algorithm must ensure it gets to that point and this task is difficult with only a finite set of weights. So to overcome this we use one of the most sought after optimizing algorithms in machine learning which is Gradient Descent.</p><p>We start with a set of weights, compute its cost and take steps in moving towards the lower most point(in mathematical terms, global minima).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*mI6S9j-1Ot1aIE23mCUF-g.png" /><figcaption>Gradient Descent moving towards global minima(convex optimization, reason why the curve is important)</figcaption></figure><p>The red points are costs associated with different set of weights and the values keep minimizing to get to the global minima. This way of minimizing cost to get to the lowest value is called Gradient Descent, an optimization technique.</p><p>Gradient Descent accomplishes this task of moving towards the steepest descent(global minima) by taking the derivative of the cost function, multiplying it with a learning rate (a step size explained below) and subtracting it with the weights in previous steps. The equation for weight update is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*Bo1GHtcjraPVj3CHXHs5Og.gif" /><figcaption>Weights update.</figcaption></figure><p><strong>Learning Rate:</strong></p><p>In the previous paragraph we spoke about a term called learning rate(alpha in the above equation). This learning rate decides how much we need to come down the curve to get to the global minima. A large value for this hyper-parameter will ensure that our algorithm will overshoot the lowest cost and a very small value will take time to converge at the lowest cost. So choosing this value is extremely important for the machine learning model as whole.</p><p><strong>Derivatives:</strong></p><p>The <em>dw</em> term is the first order derivative of the cost function. It is calculated by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*lUSfRSm8fE6hAhuBM1P70w.gif" /><figcaption>First order derivative</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/0*lGC-Gwem5viXYGbx" /></figure><p>and this is the math behind linear regression. The mean squared error is also preferred as it penalizes the points with higher differences much more than the points with lower differences and it also ensures that the negative and positive values in equal proportions do not get cancelled out when they are added as adding the error terms without squaring ensures that.</p><p>The GitHub Gist for linear regression is given below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a96a02c1b233a4c316ade13b69cb4b4/href">https://medium.com/media/6a96a02c1b233a4c316ade13b69cb4b4/href</a></iframe><p><strong>Ridge and Lasso:</strong></p><p>Ridge regression and Lasso regression are very similar in working to Linear Regression. The only difference is the addition of <em>the l1 </em>penalty in Lasso Regression and <em>the l2 </em>penalty in Ridge Regression. The primary reason why these penalty terms are added is two ensure there is regularization, shrinking the weights of the model to zero or close to zero to ensure that the model does not overfit the data.</p><p>Overfitting is a problem that occurs when the regression model gets tuned to the training data too much that it does not generalize well. It is also called a model with high variance as the difference between the actual value and the predicted value of the dependent variable in the test set will be high.</p><p>So how does Ridge and Lasso overcome the problem of overfitting? Both of these techniques use an additional term called penalties in their cost function. The equation for these two techniques are given below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*XN9hxyk82UySDAvQ_9w76Q.gif" /><figcaption>Ridge Regression cost fucntion</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*PJav7bnRliTqNaeDVOjLWQ.gif" /><figcaption>Lasso Regression Cost</figcaption></figure><p>So what are the above two equations and how do they solve the problem of overfitting?</p><p>To answer this question we need to understand the actual way these two equations were derived. The equation for Ridge is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*AQcMZkJEzrUqV_KdrJQY4Q.png" /><figcaption>Ridge constrains</figcaption></figure><p>we will begin by by expanding the constrain, the <em>l2 </em>norm which yields,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*q0Q6Rzm17Z_8r1TMJ6cdxw.png" /><figcaption>Constrain expansion for 2 parameters wo and w1</figcaption></figure><p>The term on the right hand side in the above equation can be any constant value. This gives us an equation of circle, with origin (0,0) and radius C. So what a ridge regression essentially does is that it creates a solution that minimizes the cost function such that the values of <em>w0 </em>and <em>w1 </em>can only be from points within or on the circumference of the circle.</p><p>The equation one tries to minimize becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*lfM_BhxvUIRo8aBYD-MI2g.gif" /><figcaption>Equation we need to minimize</figcaption></figure><p>For fixed values of lambda in the second term, the multiplication of lambda along with <em>c </em>yields a constant term. So essentially we will be minimizing the equation we have for ridge above.Lambda is a hyper-parameter that we tune and we set it to a particular value based on our choice. If it is set to zero then the equation of ridge gets converted to that of normal linear regression.</p><p>From then on out the process is similar to that of normal linear regression with respect to optimization using Gradient Descent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*5d9Nn0-QbeHJCLfboxvgnQ.gif" /><figcaption>Derivative of ridge function</figcaption></figure><p>The Github Gist for Ridge is</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7834b7b04373cb266d4c7b3904c37f69/href">https://medium.com/media/7834b7b04373cb266d4c7b3904c37f69/href</a></iframe><p><strong>Lasso Regression:</strong></p><p>Ridge regression has one small flaw as an algorithm when it comes to feature selection i.e. when there are two features that are highly correlated with each other, the weights are equally distributed between those two features implying there will be two features with lesser value of coefficients rather than one feature with strong coefficients. This becomes problematic when you want to select certain features based on threshold the single feature with higher value might get selected if it had been alone but due to multi collinearity, both of those features would not get selected as their weights are split.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*SD9gXUS25axCKkaEXtlj7Q.png" /></figure><p>The lasso regression like the ridge regression does regularization i.e. shrinks the coefficient to zero.This is important when there are large number of features to model the the machine learning algorithm. The way it does is by trying to minimize the cost function i.e. the Residual sum of squares subject to a constrain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/93/1*Zstaco2-yAYBmHDCbsQstQ.gif" /><figcaption>Lasso constrain</figcaption></figure><p>On expanding this equation for <em>w0 </em>and <em>w1 </em>we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/108/1*jIOc7kzmSbDdEZoBBUnQqQ.gif" /></figure><p>Similar to the Ridge model, Lasso regression minimizes the cost subject to constrains, but for lasso when we plot the points for the constrain, there will be a diamond that is created with (0,0) as center. The intuition behind this is that we will have the contour plot with the Residual sum of squares value which are bound to be within or on the circumference of the diamond. Since the chances of the contour plot touching the end points of the diamond are quite high, thereby driving the weights for certain features zero.</p><p>Considering that Lasso regression uses the <em>l1 </em>norm, the derivative of that when we try updating the cost function is either negative 1 or positive 1 and at point 0 it cannot be determined. Hence it is not feasible to update the weights of the features using closed form approach or gradient descent so Lasso uses something called coordinate descent to update the weights. In that it uses soft thresh holding to get the value of weights associated with the features. This can be explained better with the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84f59ccdef0fe90918ae2db94d729b35/href">https://medium.com/media/84f59ccdef0fe90918ae2db94d729b35/href</a></iframe><blockquote>Please do point out for any errors in the comment sections.</blockquote><blockquote>For other articles on implementation on <a href="https://medium.com/@sidharths758/polynomial-regression-overfitting-and-ridge-regression-an-overview-70de53f0ccab">ridge</a> or <a href="https://medium.com/@sidharths758/least-absolute-shrinkage-and-selection-operator-lasso-regression-9132dc80654b">lasso</a> regression.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9de216ebdf8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/math-behind-linear-ridge-and-lasso-regression-b9de216ebdf8">Math behind Linear, Ridge and Lasso Regression</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Math Behind Logistic Regression Algorithm]]></title>
            <link>https://medium.com/analytics-vidhya/logistic-regression-b35d2801a29c?source=rss-58435b5eda82------2</link>
            <guid isPermaLink="false">https://medium.com/p/b35d2801a29c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sidharth Sekhar]]></dc:creator>
            <pubDate>Tue, 20 Aug 2019 06:43:00 GMT</pubDate>
            <atom:updated>2019-08-30T07:29:59.254Z</atom:updated>
            <content:encoded><![CDATA[<p>One often deals with real life problems of choosing between different sets of things. For example, whether a customer is going to buy a product or not, which package a customer is going to subscribe. All these come under the gambit of classification, predicting which set a particular data point belongs.</p><p>Linear classification is the means by which classification is made based on predictor function that is linear, combining weights with the values of dependent variable. Non- linear operations may be involved in this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wFOWSUKXt95qoBfv97HAkg.jpeg" /><figcaption>Logistic regression Flow</figcaption></figure><p>In the above two equations, Eq 1 associates each feature with a weight. The reason why we call logistic regression one of the generalized linear model. Following which there is a use of link function(explanation will be provided below) that converts the data provided within the range of (0,1).Here Eq 2. is the link function which is a sigmoid function and z is a value that gives you the probability of one of the events happening.</p><h4><strong>Logistic Regression process</strong></h4><p>Given a data(X,Y), X being a matrix of values with m examples and n features and Y being a vector with m examples. The objective is to train the model to predict which class the future values belong to. Primarily, we create a weight matrix with random initialization. Then we multiply it by features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*zgHJk04MnT-KHseMx5UplA.gif" /><figcaption>Eq 1.</figcaption></figure><p>We then pass the output obtained from Eq 1. to a link function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*W-eV7ojoYq8FKTHrDyxKEw.gif" /><figcaption>Link Function</figcaption></figure><p>This is followed by calculating the cost for that iteration whose formula is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*oWzox2Raoi-HkqEAkdgJuA.gif" /><figcaption>cost function</figcaption></figure><p>The derivative of this cost is calculated following which the weights are updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*fBcG0OClMcbvR704jynxfQ.gif" /><figcaption>Gradient</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/154/1*zbGFw_u7ay1UagAPkE6PMw.gif" /><figcaption>Update</figcaption></figure><p>The entire code in python for logistic regression from scratch is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*K5d-8qvUzF60PoaZ8XlDLw.png" /><figcaption>Logistic regression from scratch</figcaption></figure><p><strong>Math and Intuition behind Logistic Regression</strong></p><p>The goal of the logistic regression algorithm is to create a linear decision boundary separating two classes from one another. This decision boundary is given by a conditional probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*zwJSij87fzcsbT6-pT4SQw.png" /><figcaption>The line in between is the decision boundary with two classes above and below it.</figcaption></figure><p>Let us assume that the class above the black line(decision boundary) i.e. the <em>‘+’ </em>is classified as <em>‘1’ </em>and class below the decision boundary <em>‘o’ </em>is defined as <em>‘0’. What logistic regression does is that it calculates a conditional probability i.e.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/1*FU0Nigzvpemy3MJUlxGUqw.gif" /><figcaption>Probability for class ‘1’</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/1*qqKpGBJkxelSyExgOUFgew.gif" /><figcaption>Probability for class ‘0’</figcaption></figure><p>Logistic regression calculates the probability of a particular set of data points belonging to either of those class’ given the value of <em>x </em>and <em>w. </em>The logic is that say, we have a set of values that we obtain from negative infinity to positive infinity based on the linear model, we need to narrow it down to a score that is in between zero and one as probabilities always are in that range and logistic regression talks about probabilities. The link function, sigmoid function takes care of this work.</p><p>The use of exponent in the sigmoid function is justified as probability is always greater than zero and the property of exponents takes care of this aspect. Then we need to worry about the limiting the values less than one, which is done by dividing the value in the numerator by value greater than it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*jQuR6pcfDoBfgnC0EM9nOA.gif" /><figcaption>Probability greater than 0</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*Iet19xnD9S5E5xv863CimQ.gif" /><figcaption>Probability greater than 0 and less than 1</figcaption></figure><p>Now to get the probability of the alternate class we just have to subtract the value obtained above by 1. When we divide the above equation by the numerator term, we obtain the sigmoid link function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*ZqLdj1Uohg0AykU03IuKXA.gif" /></figure><p><strong>Odds Ratio</strong></p><p>We hear the term “what are the odds of a team winning”, from many people around us. Odds is basically the probability of an event occurring to that of an event not occurring. In logistic regression, the odds of an event occurring can be given by the formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*hWQGnNaeVX4TgV1g6-C8bA.gif" /><figcaption>Odds of an event occurring</figcaption></figure><p>The log odds or log-likelihood of the event is given by taking log of the above equation. The odds ratio is log transformed to remove the restricted range as probabilities are in the range (0,1).Log transformation changes this to values from negative infinity to positive infinity. The second reason is that log values are easier to interpret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*fANFmXlXhvcP8bXalhx8Sw.gif" /><figcaption>Log(odds)</figcaption></figure><p>If we take into consideration the conditional probability of getting an output P(y=1|x;w) is equal to the sigmoid function and the p(y=0|x;w) = 1-p(y=0|x;w) and if take in that our sample has a Bernoulli distribution then the cost function for the logistic regression model is derived by,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*u3HtNCoEiG7Z2yFr6uYOsQ.gif" /></figure><p>Taking log this equation can be transformed into the cost function above. The presence of the minus sign in the beginning of the function is to ensure we try minimizing the negative of likelihood instead of maximizing the value as gradient descent minimizes the error.</p><p>The Scikit-learn implementation of logistic regression is given below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JwQsln1aUCCJKm--tU7DSA.png" /><figcaption>Sklearn implementation</figcaption></figure><blockquote>Do comment in case you find any discrepancies.</blockquote><blockquote>The github link to the notebook is <a href="https://github.com/sidsekhar/Regression-Basics/blob/master/Logistic%20Regression.ipynb">https://github.com/sidsekhar/Regression-Basics/blob/master/Logistic%20Regression.ipynb</a><br>The metrics associated with classification will be dealt as a separate writing.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b35d2801a29c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/logistic-regression-b35d2801a29c">Math Behind Logistic Regression Algorithm</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[Least Absolute Shrinkage and Selection Operator(LASSO Regression)]]></title>
            <link>https://medium.com/@sidharths758/least-absolute-shrinkage-and-selection-operator-lasso-regression-9132dc80654b?source=rss-58435b5eda82------2</link>
            <guid isPermaLink="false">https://medium.com/p/9132dc80654b</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sidharth Sekhar]]></dc:creator>
            <pubDate>Fri, 16 Aug 2019 12:05:34 GMT</pubDate>
            <atom:updated>2019-08-16T12:05:34.283Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine learning models tend to overfit the data they are trained in leading to high variance. This problem of overfitting can be dealt with the process of regularization, reducing the complexity of the function. In the last <a href="https://medium.com/@sidharths758/polynomial-regression-overfitting-and-ridge-regression-an-overview-70de53f0ccab">blog</a> post, I wrote about Ridge Regression which is one form of regularization, in this blog post we are going to see about LASSO regression.</p><p>LASSO or Least Absolute Shrinkage and Selection Operator uses <em>l1 </em>regularization does variable selection(choosing the Independent variable arbitrarily)and regularization. It is very similar to how ridge regression works, which uses the sum of the square of weights to constrain the regression model, while Lasso uses the absolute sum of weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*_wAyS26riM7mXBY2ZsyA1g.gif" /><figcaption>Cost function to be minimized for Lasso</figcaption></figure><p>This is basically the residual sum of squares added with lambda times the absolute sum of weight. The hyper parameter lambda is the one that decides how much to shrink the coefficient.</p><p>The packages that need to be imported are</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DsRGYJxsuAQBn8VRGqN2A.png" /><figcaption>Imported packages</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*wE-OG65jFagP8NDQhRpJaQ.png" /><figcaption>Plotting the training dataset.</figcaption></figure><p>The plot method creates a scatter plot of the training dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXw7c1Jsb7PNUtn-tlim9w.png" /><figcaption>Scatter plot of the Independent and dependent variables</figcaption></figure><p>After this we create a method to create polynomial features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVq7OaanDYE_7z7vK9QQZg.png" /><figcaption>poly_features</figcaption></figure><p>The poly_features method ensures it takes in a <em>dataframe</em> and degree as input. The first line in the method creates a copy of the <em>dataframe</em>. Following which the shape of the <em>dataframe</em> is checked. If the <em>dataframe</em> has only one feature then it is reshaped into a <em>numpy</em> array with dimensions (-1,1). The negative one in reshape denotes that <em>numpy</em> needs to figure out the dimensions on its own i.e. it needs to figure out the number of rows while the number of columns is one. In case the number of examples is only one in the <em>dataframe</em> then we reshape the <em>dataframe</em> as(1,-1). We then go onto use the <em>PolyFeatures </em>method from the <em>sklearn </em>library to transform the dataset into one of polynomial features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lA_BHf4t1upq3ZdrGHzpJQ.png" /></figure><p>The above python snippet takes in a <em>dataframe, </em>degree, a list of lambda values and the dependent variable as input. The first line creates a <em>dataframe </em>with polynomial features. We then create an object for Kfold validation with 10 as its input. In the looping structure used, we iterate for every lambda value that we give in as input inside which we use another loop to iterate over each of the 10 <em>KFold </em>training and testing splits. For each of those subsets of training and testing splits we create a <em>Lasso </em>object, train the model on the training subset and test the model on testing subset. We then take the <em>mse </em>or mean squared error for each of those subsets. Considering we obtained a mean squared error for all the subsets of training and testing data, we divide by 10 the number of folds to get the actual <em>mse </em>for that particular lambda value. We then append the mse value associated with each lambda value into as list and use an <em>if </em>condition to get the least mse value, i.e. comparing the current <em>mse </em>to previous <em>mse </em>and based on that returning the best model, lambda values along with the entire set of <em>mse </em>values obtained for each lambda value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*7eswB0ZB5xkaDYtZBb_Eeg.png" /><figcaption>A model with degree 4.</figcaption></figure><p>We the plot the predicted value’s curve for the data based on the snippet below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*aR4F4AN-vprf6l_ytQDZmg.png" /><figcaption>Plotting the lasso curve</figcaption></figure><p>The plot method is used to create a scatter plot as described above. We then create a test dataset with 200 random values for predicting and use the model we created for predicting the value for this test dataset. The <em>sorted and zip </em>methods are used here to sort the test and the prediction values associated with each test value. We then create two variables to hold these two values and plot them giving us the lasso best fit line</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*xzaiVHhhfWz3eyxIWqyKXw.png" /><figcaption>Lasso best fit line</figcaption></figure><blockquote>The github link for the jupyter notebook is <a href="https://github.com/sidsekhar/Regression-Basics/blob/master/Lasso%20%26%20Regularization.ipynb">https://github.com/sidsekhar/Regression-Basics/blob/master/Lasso%20%26%20Regularization.ipynb</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9132dc80654b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polynomial Regression, OverFitting and Ridge Regression- An Overview]]></title>
            <link>https://medium.com/@sidharths758/polynomial-regression-overfitting-and-ridge-regression-an-overview-70de53f0ccab?source=rss-58435b5eda82------2</link>
            <guid isPermaLink="false">https://medium.com/p/70de53f0ccab</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sidharth Sekhar]]></dc:creator>
            <pubDate>Wed, 14 Aug 2019 11:47:15 GMT</pubDate>
            <atom:updated>2019-08-16T09:26:50.204Z</atom:updated>
            <content:encoded><![CDATA[<h3>Polynomial Regression, OverFittingg and Ridge Regression- An Overview</h3><p>In many real-world data sets, the relationship between the dependent and independent variables is non-linear and it is difficult to get a linear relationship even with transformations. For these kinds of data, one can use polynomial regression. The best fit line for a polynomial regression won’t be a straight line but a curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*kX6E71wfaeSWKgg_N5hd3g.gif" /><figcaption>Equation of Polynomial Regression</figcaption></figure><p>In this type of regression the input parameters are used to create higher nth degree polynomials on which a model is trained for prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05PGwI57LpzVa8srjlMwjA.png" /><figcaption>Importing the necessary datasets.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*584cOhfVMQGGImvijlOEEQ.png" /><figcaption>Scatter plot for X and Y axis</figcaption></figure><p>One can clearly see that a linear relationship does not exist and a regression line won’t fit this data well. Hence we need another model.</p><p>We try creating a degree 2 polynomial for this data and look at the fitted line</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*LWTgtw7ZpCyq3ZiRCm0mOQ.png" /><figcaption>degree 2 polynomial</figcaption></figure><p>The plot_predictions method first creates a scatter plot to plot the training dataset. The we create a test dataset <em>x_test</em> using the the <em>np.array</em> command creating a random numbers with 20 rows. In the next line we predict the values for the <em>x_test </em>using the model we have already trained on the original dataset. We then sort the <em>x_test </em>and <em>y_test</em> and plot the predicted values using a line plot.</p><blockquote>We the try playing with different degrees of polynomial</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*IxWZMvH4zG7P9bFsRmdt6Q.png" /><figcaption>Degree 4 polynomial</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*I_8wK-p_12p2sRaRcCakDg.png" /><figcaption>Degree 16 Polynomial with High variance i.e. Overfitting.</figcaption></figure><p><strong>High Variance:</strong></p><p>When the model is trained too good only on the training data that it does not generalize well with test data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0HGNOjG8wpIML3EhnUZxg.png" /><figcaption>The r-squared score for each degree polynomial regression.</figcaption></figure><p>There is the tendency for the regression model to overfit the data. In instances such as these we need to ensure that we balance between bias and variance.</p><p>Hence to overcome the problem of overfitting we use a machine learning algorithm called Ridge Regression. It is very similar to Linear Regression only that it differs in cost function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*Zs4ZVerKxWu4WVf5KXdAtQ.gif" /><figcaption>Cost function for Ridge</figcaption></figure><p>In Ridge regression we square the weight, multiply it by a <em>l2_penalty</em> term(lambda) and add it to the RSS(Residual sum of square).Then we try to minimize this value. The lambda parameter controls the shrinkage of the term. If it’s set to 0 then the entire equation becomes like normal Linear Regression curve and high values of lambda ensure the ridge regression to overfit the data. An optimal value for lambda by using cross validation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o09Z_4bqFlJ4PwGVLwnrjg.png" /><figcaption>Using Kfold to pick the best lambda value</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*Ly6FJ5tbCtRfwg4PZhC6ig.png" /><figcaption>Plotting all the lambda values vs error terms to decide which is the best l2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*0Fz1o2W5iV0GTm1fWMuHLg.png" /><figcaption>Final best fit of data.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*o3jxyFq3dxDaHgXV8YV7vQ.png" /><figcaption>Ridge regression from scratch in python</figcaption></figure><blockquote>Feel free to comment and point out any errors.</blockquote><blockquote>The github link is <a href="https://github.com/sidsekhar/Regression-Basics">https://github.com/sidsekhar/Regression-Basics</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70de53f0ccab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple Regression]]></title>
            <link>https://medium.com/@sidharths758/multiple-regression-18b0cf6528d9?source=rss-58435b5eda82------2</link>
            <guid isPermaLink="false">https://medium.com/p/18b0cf6528d9</guid>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sidharth Sekhar]]></dc:creator>
            <pubDate>Tue, 13 Aug 2019 10:31:31 GMT</pubDate>
            <atom:updated>2019-08-13T16:02:08.670Z</atom:updated>
            <content:encoded><![CDATA[<p>More often than not in regression problems, there is more than one independent variable based on which the dependent variable’s value differs. A simple regression model won’t suffice for these kinds of problems hence there is a need to create a model that will take into consideration each of the independent variables. That is exactly what multiple regression does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*4XnUi9KCnh-Y_JkB9UMeEA.gif" /><figcaption>D is the number of independent variables</figcaption></figure><p>The above mathematical relation is used to establish the relationship between the variables. There are a certain number of assumptions one must verify before using multiple regression as deviations from these assumptions will result in spurious models that won’t predict the right values. The assumptions are,</p><blockquote>The relationship between the dependent variable and independent variables should be linear in nature.</blockquote><blockquote>There should be no Auto correlation between the residue terms.</blockquote><blockquote>There should not be correlation between the independent variables.</blockquote><blockquote>The residue terms should be homoscedastic and normally distributed.</blockquote><p>The primary assumption i.e. test for linearity can be checked with scatter plot before which we check for normality of the data distributions. Using a distplot in<strong> seaborn</strong> package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*PtkIogKrL7GwqDpw4hSXpQ.png" /><figcaption>Data is not normally distributed.</figcaption></figure><p>Log transforming the data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*zjMarnTftam9gPTimUZO_w.png" /><figcaption>Distribution after log transformtion.</figcaption></figure><p>Then scatterplots are plotted next to check linear relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*xdJ9uBg7M8TVHQ5hadtgFA.png" /><figcaption>Scatterplot showing linear relationship</figcaption></figure><p>Next we are going to check for correlation between the 2 independent variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*wdEAbNXvvdCFLeSYcJN7wg.png" /><figcaption>The continuous independent variables sqft_living and sqft_living15 are highly correlated.</figcaption></figure><p>So we remove sqft_living15 following which we one hot encode all categorical data in the dataset.</p><p>Our dataset is now ready to be fed into regression algorithm for predictions.</p><p>When given as input to a regression model, it being</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*27ou-VcR7_QLkIXVQ_so6Q.png" /><figcaption>Code snippet</figcaption></figure><p>The data given to the model had 19 input parameters and for each of them there were weights produced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*ATM7_4_ymMB5s28Fiynobw.png" /></figure><p><strong>Interpreting Weights</strong></p><p>When there is a multiple regression problem, there will be a weight associated with each of the input parameter. It is important how we interpret these weights to understand multiple regression better. The weights are interpreted as, “how much does the dependent variable change for unit change in one independent variable, keeping rest of the features constant.It’s for this reason we don’t take two highly correlated features as input to the model.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*CXErpL5zbCYEVe8RYbEMOA.png" /><figcaption>The residual vs fitted values plot. (Also used to check for assumption of regression)</figcaption></figure><p>The random spread of the residual vs fitted plot says that there is linear relationship between dependent and independent variable, presence of outliers is less and variance or error terms are equal.</p><p>In this work, I used scikitlearn’s train_test_split to split the data into training and testing set. The input parameters were log transformed. Log transformations are important as certain independent variables were skewed. To reduce the skew and to have more linear trends we transform the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*XWjEjZPKqHkopdBOaNXi_A.png" /><figcaption>Predict method used to give the final output.</figcaption></figure><p>The trained model had a R2 score of 72.13 with mean squared error of 223.62</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18b0cf6528d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scraping using BeautifulSoup]]></title>
            <link>https://medium.com/@sidharths758/web-scraping-using-beautifulsoup-281bafbc1aa4?source=rss-58435b5eda82------2</link>
            <guid isPermaLink="false">https://medium.com/p/281bafbc1aa4</guid>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sidharth Sekhar]]></dc:creator>
            <pubDate>Thu, 08 Aug 2019 10:48:02 GMT</pubDate>
            <atom:updated>2019-08-08T10:48:02.326Z</atom:updated>
            <content:encoded><![CDATA[<p>The internet is one of the biggest repositories of data. The ability to pull data from the websites and put it off use is of importance to any company. This blog will cover the basics of using BeautifulSoup, a python library that enables us to capture data from a particular website. We will be picking a random website for this project, pull data from that site and put it as an excel file.</p><p>The primary thing one has to do is import another package along with <strong>BeautifulSoup</strong>, which is the <strong>request</strong> package. The <strong>requests </strong>package is used to send HTTP requests and obtain an HTTP response. Here we will be using it only for establishing a connection with the page we need data from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FejjM65YCyhHN_7Cp2wN2Q.png" /><figcaption>Importing packages</figcaption></figure><p>After the packages are imported we then use <strong>requests </strong>to establish connection and the use <strong>BeautifulSoup </strong>to get the raw contents of the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JC0HBLTbhVI2WvEk0JVKiw.png" /></figure><p>The requests.get method receives all the data. The BeautifoulSoup class is initialized with the content of the page we established a connection with while the Html.parser that is passed on tells BeautifulSoup to parse those elements as an Html page. The output when you run the above 2 lines of code is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swHstScHSzLi3gEAlZoQPQ.png" /><figcaption>Part of the entire html content</figcaption></figure><p>Now we are all set to extract data from that website</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gmp7VgutkVvpDxa1zzmtqQ.png" /><figcaption>Inspecting elements</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*aJ4sWuj_27mLCmJClFwl0Q.png" /><figcaption>Data based on brand names</figcaption></figure><p>If one inspects the tags/elements of the website, the brand names are there inside the div element with the class name “<em>border_box m_b-20</em>”. So we instruct the BeautifulSoup object to find all instances of the div tag with the above class name and store it in a variable. Then we iterate over the variable and find all child nodes within the div tag which are the “<em>a</em>” and “<em>li</em>” elements. We then store the hyperlinks of all the pages that refer us to the pages where data based on each brand names are displayed. We also get the car brand names in that div element and store it in another python list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*vJsHh_Eu-CO1Bv9m8CBGOw.png" /><figcaption>Text(brand name) and the href link.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*YCxyodF53jx5kMOsFavkuQ.png" /><figcaption>The hyperlinks list.</figcaption></figure><p>We then iterate over the links for each of the cars brand name and store all the car names from each of the links based on the brand name in a python dictionary,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3FkhIDQEqWgyYBOVMAorkw.png" /><figcaption>Dictionary storing details of car brand and the car names under it.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*6LaGgFwJ7hshPf-vflbXEQ.png" /><figcaption>The website where elements and text are.</figcaption></figure><p>After that the contents of the dictionary are converted into an excel sheet using the<strong> XLSXWRITER </strong>package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*1wQ3z9qZOf_3S-w1S955Og.png" /></figure><blockquote>Note: The <strong>requests </strong>package should be used judiciously as it keeps making calls to website, increasing its traffic.</blockquote><blockquote>I have added the github link to the Jupyter notebook for this work. It will also have code on information about bikes.</blockquote><blockquote>Github link</blockquote><blockquote><a href="https://github.com/sidsekhar/Webscrap">https://github.com/sidsekhar/Webscrap</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=281bafbc1aa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Linear Regression — A comprehensive guide]]></title>
            <link>https://medium.com/@sidharths758/simple-linear-regression-a-comprehensive-guide-54df9b6253b?source=rss-58435b5eda82------2</link>
            <guid isPermaLink="false">https://medium.com/p/54df9b6253b</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sidharth Sekhar]]></dc:creator>
            <pubDate>Wed, 07 Aug 2019 12:42:09 GMT</pubDate>
            <atom:updated>2019-08-07T12:51:13.232Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simple Linear Regression — An Introduction.</h3><p>Supervised learning is a set of machine learning algorithms that predict an outcome y based on input data that are labeled. One of the most sought after supervised learning models is linear regression, a model that tries to define a linear relationship between the independent variable and the dependent variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3XizPz5gvj08PBjmFbpLQ.jpeg" /><figcaption>Flow of ML Model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*nq2pkmcskIfEngz_X6Q0Wg.png" /><figcaption>X — Independent variable, Y- dependent variable.</figcaption></figure><p>The entire idea of linear regression is to predict the future values of Y after training the regression model on the available data. This is done by establishing a mathematical relationship between the dependent and independent variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*FfE0Llrfs0Q8qZF-s6cBqQ.png" /><figcaption>Existence of linear relationship between Independent variable(Annual Franchise Fee) and dependent variable (Pizza Cost)</figcaption></figure><p>The mathematical function used to establish the relationship is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*V9tvjxTyUQNCkpMwSjOWDQ.gif" /></figure><blockquote>W — Weights associated with the independent variable <br>x — The inputs <br>Y — The dependent variable values (output)<br>b — Random noise</blockquote><p>The function used above delivers an output for each iteration whose result is constantly optimized based on a metric of user’s choice, which tells us how good the regression line fits the data points. The optimizing function that we are going to see in this post is Stochastic gradient Descent, a convex optimization function. The metric used for this post is Mean Square Error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/87/1*4XTI9_hTLFoS7SMefFRbig.gif" /><figcaption>Mean square error formula</figcaption></figure><p>The first term in the above formula is the predicted value while the second term y is the actual value associated with the input. What actually happens when we calculate the mean square error is that we are squaring and then summing over the residual values of our model which is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/1*LgdD16xrhHKge_nzB7F4Nw.gif" /><figcaption>Residue</figcaption></figure><p>The actual value minus the predicted one. The reason why we square the term is because, the more wider the difference between the predicted and actual value, the more MSE penalizes the cost.</p><p>The python snippet to the simple linear regression is presented below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*XxuFg6DAaiB8vT2a4ihYtQ.png" /><figcaption>Python code</figcaption></figure><blockquote>Note: The above data presented does have outliers and simple regression is not robust to outliers. Outlier detection will be covered separately as another write up.</blockquote><p>Mean Square error, the metric used will determine how good is the fit of the line.Lower the value of it, the better the fit of the regression line.Typically in a ML problem, multiple models with different algorithms are created and for each of them MSE is calculated and the best on according to the requirements are taken and used.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54df9b6253b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>